repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ahmedRaaj/cdi-tutorial
src/main/java/com/vaadin/cdi/tutorial/MyVaadinUI.java
550
package com.vaadin.cdi.tutorial; import javax.inject.Inject; import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.cdi.CDIUI; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.UI; @Theme("valo") @CDIUI("") @Push @SuppressWarnings("serial") public class MyVaadinUI extends UI { @Inject private javax.enterprise.event.Event<NavigationEvent> navigationEvent; @Override protected void init(VaadinRequest request) { navigationEvent.fire(new NavigationEvent("login")); } }
apache-2.0
antoinesd/weld-core
tests-arquillian/src/test/java/org/jboss/weld/tests/metadata/scanning/jboss/Baz.java
77
package org.jboss.weld.tests.metadata.scanning.jboss; public class Baz { }
apache-2.0
papicella/snappy-store
gemfire-core/src/main/java/com/gemstone/gemfire/admin/internal/DistributionLocatorConfigImpl.java
5613
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.gemstone.gemfire.admin.internal; import com.gemstone.gemfire.admin.DistributionLocator; import com.gemstone.gemfire.admin.DistributionLocatorConfig; import com.gemstone.gemfire.distributed.internal.InternalLocator; import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import java.net.InetAddress; import java.util.Properties; /** * Provides an implementation of * <code>DistributionLocatorConfig</code>. * * @author David Whitlock * @since 4.0 */ public class DistributionLocatorConfigImpl extends ManagedEntityConfigImpl implements DistributionLocatorConfig { /** The minimum networking port (0) */ public static final int MIN_PORT = 0; /** The maximum networking port (65535) */ public static final int MAX_PORT = 65535; ////////////////////// Instance Fields ////////////////////// /** The port on which this locator listens */ private int port; /** The address to bind to on a multi-homed host */ private String bindAddress; /** The properties used to configure the DistributionLocator's DistributedSystem */ private Properties dsProperties; /** The DistributionLocator that was created with this config */ private DistributionLocator locator; ////////////////////// Static Methods ////////////////////// /** * Contacts a distribution locator on the given host and port and * creates a <code>DistributionLocatorConfig</code> for it. * * @see InternalLocator#getLocatorInfo * * @return <code>null</code> if the locator cannot be contacted */ static DistributionLocatorConfig createConfigFor(String host, int port, InetAddress bindAddress) { String[] info = null; if (bindAddress != null) { info = InternalLocator.getLocatorInfo(bindAddress, port); } else { info = InternalLocator.getLocatorInfo(InetAddressUtil.toInetAddress(host), port); } if (info == null) { return null; } DistributionLocatorConfigImpl config = new DistributionLocatorConfigImpl(); config.setHost(host); config.setPort(port); if (bindAddress != null) { config.setBindAddress(bindAddress.getHostAddress()); } config.setWorkingDirectory(info[0]); config.setProductDirectory(info[1]); return config; } /////////////////////// Constructors /////////////////////// /** * Creates a new <code>DistributionLocatorConfigImpl</code> with the * default settings. */ public DistributionLocatorConfigImpl() { this.port = 0; this.bindAddress = null; this.locator = null; this.dsProperties = new java.util.Properties(); this.dsProperties.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); } ///////////////////// Instance Methods ///////////////////// /** * Sets the locator that was configured with this * <Code>DistributionLocatorConfigImpl</code>. */ void setLocator(DistributionLocator locator) { this.locator = locator; } @Override protected boolean isReadOnly() { return this.locator != null && this.locator.isRunning(); } public int getPort() { return this.port; } public void setPort(int port) { checkReadOnly(); this.port = port; configChanged(); } public String getBindAddress() { return this.bindAddress; } public void setBindAddress(String bindAddress) { checkReadOnly(); this.bindAddress = bindAddress; configChanged(); } public void setDistributedSystemProperties(Properties props) { this.dsProperties = props; } public Properties getDistributedSystemProperties() { return this.dsProperties; } @Override public void validate() { super.validate(); if (port < MIN_PORT || port > MAX_PORT) { throw new IllegalArgumentException(LocalizedStrings.DistributionLocatorConfigImpl_PORT_0_MUST_BE_AN_INTEGER_BETWEEN_1_AND_2.toLocalizedString(new Object[] {Integer.valueOf(port), Integer.valueOf(MIN_PORT), Integer.valueOf(MAX_PORT)})); } if (this.bindAddress != null && InetAddressUtil.validateHost(this.bindAddress) == null) { throw new IllegalArgumentException(LocalizedStrings.DistributionLocatorConfigImpl_INVALID_HOST_0.toLocalizedString(this.bindAddress)); } } /** * Currently, listeners are not supported on the locator config. */ @Override protected void configChanged() { } @Override public Object clone() throws CloneNotSupportedException { DistributionLocatorConfigImpl clone = (DistributionLocatorConfigImpl) super.clone(); clone.locator = null; return clone; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DistributionLocatorConfig: host=").append(getHost()); sb.append(", bindAddress=").append(getBindAddress()); sb.append(", port=").append(getPort()); return sb.toString(); } }
apache-2.0
pongad/api-client-staging
generated/java/proto-google-cloud-vision-v1p2beta1/src/main/java/com/google/cloud/vision/v1p2beta1/GeometryProto.java
5086
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1p2beta1/geometry.proto package com.google.cloud.vision.v1p2beta1; public final class GeometryProto { private GeometryProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p2beta1_Vertex_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p2beta1_Vertex_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p2beta1_NormalizedVertex_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p2beta1_NormalizedVertex_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p2beta1_BoundingPoly_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p2beta1_BoundingPoly_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p2beta1_Position_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p2beta1_Position_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n,google/cloud/vision/v1p2beta1/geometry" + ".proto\022\035google.cloud.vision.v1p2beta1\"\036\n" + "\006Vertex\022\t\n\001x\030\001 \001(\005\022\t\n\001y\030\002 \001(\005\"(\n\020Normali" + "zedVertex\022\t\n\001x\030\001 \001(\002\022\t\n\001y\030\002 \001(\002\"\225\001\n\014Boun" + "dingPoly\0227\n\010vertices\030\001 \003(\0132%.google.clou" + "d.vision.v1p2beta1.Vertex\022L\n\023normalized_" + "vertices\030\002 \003(\0132/.google.cloud.vision.v1p" + "2beta1.NormalizedVertex\"+\n\010Position\022\t\n\001x" + "\030\001 \001(\002\022\t\n\001y\030\002 \001(\002\022\t\n\001z\030\003 \001(\002B|\n!com.goog" + "le.cloud.vision.v1p2beta1B\rGeometryProto" + "P\001ZCgoogle.golang.org/genproto/googleapi" + "s/cloud/vision/v1p2beta1;vision\370\001\001b\006prot" + "o3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_google_cloud_vision_v1p2beta1_Vertex_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_vision_v1p2beta1_Vertex_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p2beta1_Vertex_descriptor, new java.lang.String[] { "X", "Y", }); internal_static_google_cloud_vision_v1p2beta1_NormalizedVertex_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_vision_v1p2beta1_NormalizedVertex_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p2beta1_NormalizedVertex_descriptor, new java.lang.String[] { "X", "Y", }); internal_static_google_cloud_vision_v1p2beta1_BoundingPoly_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_vision_v1p2beta1_BoundingPoly_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p2beta1_BoundingPoly_descriptor, new java.lang.String[] { "Vertices", "NormalizedVertices", }); internal_static_google_cloud_vision_v1p2beta1_Position_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_vision_v1p2beta1_Position_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p2beta1_Position_descriptor, new java.lang.String[] { "X", "Y", "Z", }); } // @@protoc_insertion_point(outer_class_scope) }
bsd-3-clause
f3rno/aurous-app
aurous-app/src/me/aurous/utils/playlist/package-info.java
73
/** * */ /** * @author Andrew * */ package me.aurous.utils.playlist;
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkPipelineViewportWScalingStateCreateInfoNV.java
21696
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Structure specifying parameters of a newly created pipeline viewport W scaling state. * * <h5>Valid Usage (Implicit)</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link NVClipSpaceWScaling#VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV}</li> * <li>{@code viewportCount} <b>must</b> be greater than 0</li> * </ul> * * <h5>See Also</h5> * * <p>{@link VkViewportWScalingNV}</p> * * <h3>Layout</h3> * * <pre><code> * struct VkPipelineViewportWScalingStateCreateInfoNV { * VkStructureType {@link #sType}; * void const * {@link #pNext}; * VkBool32 {@link #viewportWScalingEnable}; * uint32_t {@link #viewportCount}; * {@link VkViewportWScalingNV VkViewportWScalingNV} const * {@link #pViewportWScalings}; * }</code></pre> */ public class VkPipelineViewportWScalingStateCreateInfoNV extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, VIEWPORTWSCALINGENABLE, VIEWPORTCOUNT, PVIEWPORTWSCALINGS; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4), __member(4), __member(POINTER_SIZE) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); VIEWPORTWSCALINGENABLE = layout.offsetof(2); VIEWPORTCOUNT = layout.offsetof(3); PVIEWPORTWSCALINGS = layout.offsetof(4); } /** * Creates a {@code VkPipelineViewportWScalingStateCreateInfoNV} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkPipelineViewportWScalingStateCreateInfoNV(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** the type of this structure. */ @NativeType("VkStructureType") public int sType() { return nsType(address()); } /** {@code NULL} or a pointer to a structure extending this structure. */ @NativeType("void const *") public long pNext() { return npNext(address()); } /** controls whether viewport <b>W</b> scaling is enabled. */ @NativeType("VkBool32") public boolean viewportWScalingEnable() { return nviewportWScalingEnable(address()) != 0; } /** the number of viewports used by <b>W</b> scaling, and <b>must</b> match the number of viewports in the pipeline if viewport <b>W</b> scaling is enabled. */ @NativeType("uint32_t") public int viewportCount() { return nviewportCount(address()); } /** a pointer to an array of {@link VkViewportWScalingNV} structures defining the <b>W</b> scaling parameters for the corresponding viewports. If the viewport <b>W</b> scaling state is dynamic, this member is ignored. */ @Nullable @NativeType("VkViewportWScalingNV const *") public VkViewportWScalingNV.Buffer pViewportWScalings() { return npViewportWScalings(address()); } /** Sets the specified value to the {@link #sType} field. */ public VkPipelineViewportWScalingStateCreateInfoNV sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the {@link NVClipSpaceWScaling#VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV} value to the {@link #sType} field. */ public VkPipelineViewportWScalingStateCreateInfoNV sType$Default() { return sType(NVClipSpaceWScaling.VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV); } /** Sets the specified value to the {@link #pNext} field. */ public VkPipelineViewportWScalingStateCreateInfoNV pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; } /** Sets the specified value to the {@link #viewportWScalingEnable} field. */ public VkPipelineViewportWScalingStateCreateInfoNV viewportWScalingEnable(@NativeType("VkBool32") boolean value) { nviewportWScalingEnable(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@link #viewportCount} field. */ public VkPipelineViewportWScalingStateCreateInfoNV viewportCount(@NativeType("uint32_t") int value) { nviewportCount(address(), value); return this; } /** Sets the address of the specified {@link VkViewportWScalingNV.Buffer} to the {@link #pViewportWScalings} field. */ public VkPipelineViewportWScalingStateCreateInfoNV pViewportWScalings(@Nullable @NativeType("VkViewportWScalingNV const *") VkViewportWScalingNV.Buffer value) { npViewportWScalings(address(), value); return this; } /** Initializes this struct with the specified values. */ public VkPipelineViewportWScalingStateCreateInfoNV set( int sType, long pNext, boolean viewportWScalingEnable, int viewportCount, @Nullable VkViewportWScalingNV.Buffer pViewportWScalings ) { sType(sType); pNext(pNext); viewportWScalingEnable(viewportWScalingEnable); viewportCount(viewportCount); pViewportWScalings(pViewportWScalings); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkPipelineViewportWScalingStateCreateInfoNV set(VkPipelineViewportWScalingStateCreateInfoNV src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkPipelineViewportWScalingStateCreateInfoNV malloc() { return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkPipelineViewportWScalingStateCreateInfoNV calloc() { return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance allocated with {@link BufferUtils}. */ public static VkPipelineViewportWScalingStateCreateInfoNV create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, memAddress(container), container); } /** Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance for the specified memory address. */ public static VkPipelineViewportWScalingStateCreateInfoNV create(long address) { return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPipelineViewportWScalingStateCreateInfoNV createSafe(long address) { return address == NULL ? null : wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, address); } /** * Returns a new {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkPipelineViewportWScalingStateCreateInfoNV malloc(MemoryStack stack) { return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkPipelineViewportWScalingStateCreateInfoNV} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkPipelineViewportWScalingStateCreateInfoNV calloc(MemoryStack stack) { return wrap(VkPipelineViewportWScalingStateCreateInfoNV.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPipelineViewportWScalingStateCreateInfoNV.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkPipelineViewportWScalingStateCreateInfoNV.PNEXT); } /** Unsafe version of {@link #viewportWScalingEnable}. */ public static int nviewportWScalingEnable(long struct) { return UNSAFE.getInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.VIEWPORTWSCALINGENABLE); } /** Unsafe version of {@link #viewportCount}. */ public static int nviewportCount(long struct) { return UNSAFE.getInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.VIEWPORTCOUNT); } /** Unsafe version of {@link #pViewportWScalings}. */ @Nullable public static VkViewportWScalingNV.Buffer npViewportWScalings(long struct) { return VkViewportWScalingNV.createSafe(memGetAddress(struct + VkPipelineViewportWScalingStateCreateInfoNV.PVIEWPORTWSCALINGS), nviewportCount(struct)); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkPipelineViewportWScalingStateCreateInfoNV.PNEXT, value); } /** Unsafe version of {@link #viewportWScalingEnable(boolean) viewportWScalingEnable}. */ public static void nviewportWScalingEnable(long struct, int value) { UNSAFE.putInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.VIEWPORTWSCALINGENABLE, value); } /** Sets the specified value to the {@code viewportCount} field of the specified {@code struct}. */ public static void nviewportCount(long struct, int value) { UNSAFE.putInt(null, struct + VkPipelineViewportWScalingStateCreateInfoNV.VIEWPORTCOUNT, value); } /** Unsafe version of {@link #pViewportWScalings(VkViewportWScalingNV.Buffer) pViewportWScalings}. */ public static void npViewportWScalings(long struct, @Nullable VkViewportWScalingNV.Buffer value) { memPutAddress(struct + VkPipelineViewportWScalingStateCreateInfoNV.PVIEWPORTWSCALINGS, memAddressSafe(value)); if (value != null) { nviewportCount(struct, value.remaining()); } } // ----------------------------------- /** An array of {@link VkPipelineViewportWScalingStateCreateInfoNV} structs. */ public static class Buffer extends StructBuffer<VkPipelineViewportWScalingStateCreateInfoNV, Buffer> implements NativeResource { private static final VkPipelineViewportWScalingStateCreateInfoNV ELEMENT_FACTORY = VkPipelineViewportWScalingStateCreateInfoNV.create(-1L); /** * Creates a new {@code VkPipelineViewportWScalingStateCreateInfoNV.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkPipelineViewportWScalingStateCreateInfoNV#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkPipelineViewportWScalingStateCreateInfoNV getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link VkPipelineViewportWScalingStateCreateInfoNV#sType} field. */ @NativeType("VkStructureType") public int sType() { return VkPipelineViewportWScalingStateCreateInfoNV.nsType(address()); } /** @return the value of the {@link VkPipelineViewportWScalingStateCreateInfoNV#pNext} field. */ @NativeType("void const *") public long pNext() { return VkPipelineViewportWScalingStateCreateInfoNV.npNext(address()); } /** @return the value of the {@link VkPipelineViewportWScalingStateCreateInfoNV#viewportWScalingEnable} field. */ @NativeType("VkBool32") public boolean viewportWScalingEnable() { return VkPipelineViewportWScalingStateCreateInfoNV.nviewportWScalingEnable(address()) != 0; } /** @return the value of the {@link VkPipelineViewportWScalingStateCreateInfoNV#viewportCount} field. */ @NativeType("uint32_t") public int viewportCount() { return VkPipelineViewportWScalingStateCreateInfoNV.nviewportCount(address()); } /** @return a {@link VkViewportWScalingNV.Buffer} view of the struct array pointed to by the {@link VkPipelineViewportWScalingStateCreateInfoNV#pViewportWScalings} field. */ @Nullable @NativeType("VkViewportWScalingNV const *") public VkViewportWScalingNV.Buffer pViewportWScalings() { return VkPipelineViewportWScalingStateCreateInfoNV.npViewportWScalings(address()); } /** Sets the specified value to the {@link VkPipelineViewportWScalingStateCreateInfoNV#sType} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer sType(@NativeType("VkStructureType") int value) { VkPipelineViewportWScalingStateCreateInfoNV.nsType(address(), value); return this; } /** Sets the {@link NVClipSpaceWScaling#VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV} value to the {@link VkPipelineViewportWScalingStateCreateInfoNV#sType} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer sType$Default() { return sType(NVClipSpaceWScaling.VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV); } /** Sets the specified value to the {@link VkPipelineViewportWScalingStateCreateInfoNV#pNext} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer pNext(@NativeType("void const *") long value) { VkPipelineViewportWScalingStateCreateInfoNV.npNext(address(), value); return this; } /** Sets the specified value to the {@link VkPipelineViewportWScalingStateCreateInfoNV#viewportWScalingEnable} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer viewportWScalingEnable(@NativeType("VkBool32") boolean value) { VkPipelineViewportWScalingStateCreateInfoNV.nviewportWScalingEnable(address(), value ? 1 : 0); return this; } /** Sets the specified value to the {@link VkPipelineViewportWScalingStateCreateInfoNV#viewportCount} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer viewportCount(@NativeType("uint32_t") int value) { VkPipelineViewportWScalingStateCreateInfoNV.nviewportCount(address(), value); return this; } /** Sets the address of the specified {@link VkViewportWScalingNV.Buffer} to the {@link VkPipelineViewportWScalingStateCreateInfoNV#pViewportWScalings} field. */ public VkPipelineViewportWScalingStateCreateInfoNV.Buffer pViewportWScalings(@Nullable @NativeType("VkViewportWScalingNV const *") VkViewportWScalingNV.Buffer value) { VkPipelineViewportWScalingStateCreateInfoNV.npViewportWScalings(address(), value); return this; } } }
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/bgfx/src/generated/java/org/lwjgl/bgfx/BGFXCaptureFrameCallback.java
2367
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.bgfx; import javax.annotation.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; /** * Captured frame. * * <h3>Type</h3> * * <pre><code> * void (*{@link #invoke}) ( * bgfx_callback_interface_t *_this, * void const *_data, * uint32_t _size * )</code></pre> */ public abstract class BGFXCaptureFrameCallback extends Callback implements BGFXCaptureFrameCallbackI { /** * Creates a {@code BGFXCaptureFrameCallback} instance from the specified function pointer. * * @return the new {@code BGFXCaptureFrameCallback} */ public static BGFXCaptureFrameCallback create(long functionPointer) { BGFXCaptureFrameCallbackI instance = Callback.get(functionPointer); return instance instanceof BGFXCaptureFrameCallback ? (BGFXCaptureFrameCallback)instance : new Container(functionPointer, instance); } /** Like {@link #create(long) create}, but returns {@code null} if {@code functionPointer} is {@code NULL}. */ @Nullable public static BGFXCaptureFrameCallback createSafe(long functionPointer) { return functionPointer == NULL ? null : create(functionPointer); } /** Creates a {@code BGFXCaptureFrameCallback} instance that delegates to the specified {@code BGFXCaptureFrameCallbackI} instance. */ public static BGFXCaptureFrameCallback create(BGFXCaptureFrameCallbackI instance) { return instance instanceof BGFXCaptureFrameCallback ? (BGFXCaptureFrameCallback)instance : new Container(instance.address(), instance); } protected BGFXCaptureFrameCallback() { super(CIF); } BGFXCaptureFrameCallback(long functionPointer) { super(functionPointer); } private static final class Container extends BGFXCaptureFrameCallback { private final BGFXCaptureFrameCallbackI delegate; Container(long functionPointer, BGFXCaptureFrameCallbackI delegate) { super(functionPointer); this.delegate = delegate; } @Override public void invoke(long _this, long _data, int _size) { delegate.invoke(_this, _data, _size); } } }
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkSparseImageFormatProperties2KHR.java
11990
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * See {@link VkSparseImageFormatProperties2}. * * <h3>Layout</h3> * * <pre><code> * struct VkSparseImageFormatProperties2KHR { * VkStructureType sType; * void * pNext; * {@link VkSparseImageFormatProperties VkSparseImageFormatProperties} properties; * }</code></pre> */ public class VkSparseImageFormatProperties2KHR extends VkSparseImageFormatProperties2 { /** * Creates a {@code VkSparseImageFormatProperties2KHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkSparseImageFormatProperties2KHR(ByteBuffer container) { super(container); } /** Sets the specified value to the {@code sType} field. */ @Override public VkSparseImageFormatProperties2KHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the {@link VK11#VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2} value to the {@code sType} field. */ @Override public VkSparseImageFormatProperties2KHR sType$Default() { return sType(VK11.VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2); } /** Sets the specified value to the {@code pNext} field. */ @Override public VkSparseImageFormatProperties2KHR pNext(@NativeType("void *") long value) { npNext(address(), value); return this; } /** Initializes this struct with the specified values. */ @Override public VkSparseImageFormatProperties2KHR set( int sType, long pNext ) { sType(sType); pNext(pNext); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkSparseImageFormatProperties2KHR set(VkSparseImageFormatProperties2KHR src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkSparseImageFormatProperties2KHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkSparseImageFormatProperties2KHR malloc() { return wrap(VkSparseImageFormatProperties2KHR.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkSparseImageFormatProperties2KHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkSparseImageFormatProperties2KHR calloc() { return wrap(VkSparseImageFormatProperties2KHR.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkSparseImageFormatProperties2KHR} instance allocated with {@link BufferUtils}. */ public static VkSparseImageFormatProperties2KHR create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkSparseImageFormatProperties2KHR.class, memAddress(container), container); } /** Returns a new {@code VkSparseImageFormatProperties2KHR} instance for the specified memory address. */ public static VkSparseImageFormatProperties2KHR create(long address) { return wrap(VkSparseImageFormatProperties2KHR.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkSparseImageFormatProperties2KHR createSafe(long address) { return address == NULL ? null : wrap(VkSparseImageFormatProperties2KHR.class, address); } /** * Returns a new {@link VkSparseImageFormatProperties2KHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkSparseImageFormatProperties2KHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkSparseImageFormatProperties2KHR.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkSparseImageFormatProperties2KHR.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkSparseImageFormatProperties2KHR.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkSparseImageFormatProperties2KHR.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkSparseImageFormatProperties2KHR} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkSparseImageFormatProperties2KHR malloc(MemoryStack stack) { return wrap(VkSparseImageFormatProperties2KHR.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkSparseImageFormatProperties2KHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkSparseImageFormatProperties2KHR calloc(MemoryStack stack) { return wrap(VkSparseImageFormatProperties2KHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkSparseImageFormatProperties2KHR.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkSparseImageFormatProperties2KHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkSparseImageFormatProperties2KHR.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** An array of {@link VkSparseImageFormatProperties2KHR} structs. */ public static class Buffer extends VkSparseImageFormatProperties2.Buffer { private static final VkSparseImageFormatProperties2KHR ELEMENT_FACTORY = VkSparseImageFormatProperties2KHR.create(-1L); /** * Creates a new {@code VkSparseImageFormatProperties2KHR.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkSparseImageFormatProperties2KHR#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkSparseImageFormatProperties2KHR getElementFactory() { return ELEMENT_FACTORY; } /** Sets the specified value to the {@code sType} field. */ @Override public VkSparseImageFormatProperties2KHR.Buffer sType(@NativeType("VkStructureType") int value) { VkSparseImageFormatProperties2KHR.nsType(address(), value); return this; } /** Sets the {@link VK11#VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2} value to the {@code sType} field. */ @Override public VkSparseImageFormatProperties2KHR.Buffer sType$Default() { return sType(VK11.VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2); } /** Sets the specified value to the {@code pNext} field. */ @Override public VkSparseImageFormatProperties2KHR.Buffer pNext(@NativeType("void *") long value) { VkSparseImageFormatProperties2KHR.npNext(address(), value); return this; } } }
bsd-3-clause
dhis2/dhis2-core
dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/handler/DefaultAuthenticationSuccessHandler.java
4269
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.webapi.handler; import java.io.IOException; import javax.annotation.PostConstruct; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import lombok.extern.slf4j.Slf4j; import org.hisp.dhis.external.conf.ConfigurationKey; import org.hisp.dhis.util.ObjectUtils; import org.joda.time.DateTimeConstants; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.util.Assert; /** * Since ActionContext is not available at this point, we set a mark in the * session that signals that login has just occurred, and that LoginInterceptor * should be run. * * @author mortenoh */ @Slf4j public class DefaultAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { public static final String JLI_SESSION_VARIABLE = "JLI"; private static final int SESSION_MIN = DateTimeConstants.SECONDS_PER_MINUTE * 10; private static final int SESSION_DEFAULT = Integer .parseInt( ConfigurationKey.SYSTEM_SESSION_TIMEOUT.getDefaultValue() ); // 3600 // s private static final String SESSION_MIN_MSG = "Session timeout must be greater than %d seconds"; private static final String SESSION_INFO_MSG = "Session timeout set to %d seconds"; private int systemSessionTimeout; /** * Configurable session timeout. */ private Integer sessionTimeout; public void setSessionTimeout( Integer sessionTimeout ) { this.sessionTimeout = sessionTimeout; } @PostConstruct public void init() { systemSessionTimeout = ObjectUtils.firstNonNull( sessionTimeout, SESSION_DEFAULT ); Assert.isTrue( systemSessionTimeout >= SESSION_MIN, String.format( SESSION_MIN_MSG, SESSION_MIN ) ); log.info( String.format( SESSION_INFO_MSG, systemSessionTimeout ) ); } @Override public void onAuthenticationSuccess( HttpServletRequest request, HttpServletResponse response, Authentication authentication ) throws ServletException, IOException { HttpSession session = request.getSession(); final String username = authentication.getName(); session.setAttribute( "userIs", username ); session.setAttribute( JLI_SESSION_VARIABLE, Boolean.TRUE ); session.setMaxInactiveInterval( systemSessionTimeout ); super.onAuthenticationSuccess( request, response, authentication ); } }
bsd-3-clause
timmolter/XChange
xchange-stream-bitmex/src/main/java/info/bitrich/xchangestream/bitmex/dto/RawOrderBook.java
394
package info.bitrich.xchangestream.bitmex.dto; import java.math.BigDecimal; import java.util.List; public class RawOrderBook { private String symbol; private String timestamp; private List<List<BigDecimal>> asks; private List<List<BigDecimal>> bids; public List<List<BigDecimal>> getAsks() { return asks; } public List<List<BigDecimal>> getBids() { return bids; } }
mit
XristosMallios/cache
exareme-utils/src/main/java/madgik/exareme/utils/measurement/MeasurementFactory.java
335
/** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.utils.measurement; /** * @author herald */ public class MeasurementFactory { private MeasurementFactory() { } public static Measurement createMeasurement(String name) { return new SynchronizedMeasurement(new MeasurementImpl(name)); } }
mit
luizvneto/DC-UFSCar-ES2-201701-Grupo-NichRosaHugoLuizRodr
src/main/java/net/sf/jabref/gui/exporter/ExportToClipboardAction.java
5278
package net.sf.jabref.gui.exporter; import java.awt.Toolkit; import java.awt.datatransfer.ClipboardOwner; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import javax.swing.BorderFactory; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import net.sf.jabref.Globals; import net.sf.jabref.gui.BasePanel; import net.sf.jabref.gui.JabRefFrame; import net.sf.jabref.gui.worker.AbstractWorker; import net.sf.jabref.logic.exporter.ExportFormats; import net.sf.jabref.logic.exporter.IExportFormat; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.model.entry.BibEntry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ExportToClipboardAction extends AbstractWorker { private static final Log LOGGER = LogFactory.getLog(ExportToClipboardAction.class); private final JabRefFrame frame; /** * written by run() and read by update() */ private String message; public ExportToClipboardAction(JabRefFrame frame) { this.frame = Objects.requireNonNull(frame); } @Override public void run() { BasePanel panel = frame.getCurrentBasePanel(); if (panel == null) { return; } if (panel.getSelectedEntries().isEmpty()) { message = Localization.lang("This operation requires one or more entries to be selected."); getCallBack().update(); return; } List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values()); Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName())); String[] exportFormatDisplayNames = new String[exportFormats.size()]; for (int i = 0; i < exportFormats.size(); i++) { IExportFormat exportFormat = exportFormats.get(i); exportFormatDisplayNames[i] = exportFormat.getDisplayName(); } JList<String> list = new JList<>(exportFormatDisplayNames); list.setBorder(BorderFactory.createEtchedBorder()); list.setSelectionInterval(0, 0); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {Localization.lang("Export"), Localization.lang("Cancel")}, Localization.lang("Export")); if (answer == JOptionPane.NO_OPTION) { return; } IExportFormat format = exportFormats.get(list.getSelectedIndex()); // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext() .getFileDirectories(Globals.prefs.getFileDirectoryPreferences()); File tmp = null; try { // To simplify the exporter API we simply do a normal export to a temporary // file, and read the contents afterwards: tmp = File.createTempFile("jabrefCb", ".tmp"); tmp.deleteOnExit(); List<BibEntry> entries = panel.getSelectedEntries(); // Write to file: format.performExport(panel.getBibDatabaseContext(), tmp.getPath(), panel.getBibDatabaseContext().getMetaData().getEncoding() .orElse(Globals.prefs.getDefaultEncoding()), entries); // Read the file and put the contents on the clipboard: StringBuilder sb = new StringBuilder(); try (Reader reader = new InputStreamReader(new FileInputStream(tmp), panel.getBibDatabaseContext().getMetaData().getEncoding() .orElse(Globals.prefs.getDefaultEncoding()))) { int s; while ((s = reader.read()) != -1) { sb.append((char) s); } } ClipboardOwner owner = (clipboard, content) -> { // Do nothing }; RtfTransferable rs = new RtfTransferable(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(rs, owner); message = Localization.lang("Entries exported to clipboard") + ": " + entries.size(); } catch (Exception e) { LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates. message = Localization.lang("Error exporting to clipboard"); } finally { // Clean up: if ((tmp != null) && !tmp.delete()) { LOGGER.info("Cannot delete temporary clipboard file"); } } } @Override public void update() { frame.output(message); } }
mit
zellerdev/jabref
src/test/java/org/jabref/logic/importer/fileformat/BibTeXMLImporterTest.java
903
package org.jabref.logic.importer.fileformat; import org.jabref.logic.util.StandardFileType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BibTeXMLImporterTest { private BibTeXMLImporter importer; @BeforeEach public void setUp() throws Exception { importer = new BibTeXMLImporter(); } @Test public void testGetFormatName() { assertEquals("BibTeXML", importer.getName()); } @Test public void testGetCLIId() { assertEquals("bibtexml", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.BIBTEXML, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for the BibTeXML format.", importer.getDescription()); } }
mit
ahmedvc/umple
cruise.umple/test/cruise/umple/tracer/implementation/TracerMethodTest.java
1193
/* Copyright: All contributers to the Umple Project This file is made available subject to the open source license found at: http://umple.org/license Test class for code generation for state machines */ package cruise.umple.tracer.implementation; import org.junit.*; @Ignore public class TracerMethodTest extends TracerTraceCaseTest { @Test public void TraceMethodEntry() { AssertMethod("TraceMethodEntry.ump","TraceMethodEntry.","Tracer"); } @Test public void TraceMethodExit() { AssertMethod("TraceMethodExit.ump","TraceMethodExit.","Tracer"); } @Test public void TraceMethodEntryExit() { AssertMethod("TraceMethodEntryExit.ump","TraceMethodEntryExit.","Tracer"); } @Test public void TraceMethodConstraint() { AssertMethod("TraceMethodConstraint.ump","TraceMethodConstraint.","Tracer"); } //---------------------------------------- public void AssertMethod( String inputUmplefile, String expectedOutputFile, String testClassName) { assertUmpleTemplateFor( "methods/" + inputUmplefile, languagePath + tracerPath + expectedOutputFile + languagePath +".txt", testClassName, false); } }
mit
runqingz/umple
cruise.umplificator/test/cruise/umplificator/examples/AccessControl/FunctionalArea.java
8449
/*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE 1.21.0.4666 modeling language!*/ import java.util.*; /** * Functional_Area * Positioning */ // line 15 "AccessControl.ump" // line 71 "AccessControl.ump" public class FunctionalArea { //------------------------ // MEMBER VARIABLES //------------------------ //FunctionalArea Attributes private String code; //FunctionalArea State Machines enum Description { Hr, Finance } private Description description; //FunctionalArea Associations private List<FunctionalArea> child; private FunctionalArea parent; private List<Facility> facilities; //Helper Variables private int cachedHashCode; private boolean canSetCode; //------------------------ // CONSTRUCTOR //------------------------ public FunctionalArea(String aCode) { cachedHashCode = -1; canSetCode = true; code = aCode; child = new ArrayList<FunctionalArea>(); facilities = new ArrayList<Facility>(); setDescription(Description.Hr); } //------------------------ // INTERFACE //------------------------ public boolean setCode(String aCode) { boolean wasSet = false; if (!canSetCode) { return false; } code = aCode; wasSet = true; return wasSet; } public String getCode() { return code; } public String getDescriptionFullName() { String answer = description.toString(); return answer; } public Description getDescription() { return description; } public boolean setDescription(Description aDescription) { description = aDescription; return true; } public FunctionalArea getChild(int index) { FunctionalArea aChild = child.get(index); return aChild; } public List<FunctionalArea> getChild() { List<FunctionalArea> newChild = Collections.unmodifiableList(child); return newChild; } public int numberOfChild() { int number = child.size(); return number; } public boolean hasChild() { boolean has = child.size() > 0; return has; } public int indexOfChild(FunctionalArea aChild) { int index = child.indexOf(aChild); return index; } public FunctionalArea getParent() { return parent; } public boolean hasParent() { boolean has = parent != null; return has; } public Facility getFacility(int index) { Facility aFacility = facilities.get(index); return aFacility; } public List<Facility> getFacilities() { List<Facility> newFacilities = Collections.unmodifiableList(facilities); return newFacilities; } public int numberOfFacilities() { int number = facilities.size(); return number; } public boolean hasFacilities() { boolean has = facilities.size() > 0; return has; } public int indexOfFacility(Facility aFacility) { int index = facilities.indexOf(aFacility); return index; } public static int minimumNumberOfChild() { return 0; } public boolean addChild(FunctionalArea aChild) { boolean wasAdded = false; if (child.contains(aChild)) { return false; } FunctionalArea existingParent = aChild.getParent(); if (existingParent == null) { aChild.setParent(this); } else if (!this.equals(existingParent)) { existingParent.removeChild(aChild); addChild(aChild); } else { child.add(aChild); } wasAdded = true; return wasAdded; } public boolean removeChild(FunctionalArea aChild) { boolean wasRemoved = false; if (child.contains(aChild)) { child.remove(aChild); aChild.setParent(null); wasRemoved = true; } return wasRemoved; } public boolean addChildAt(FunctionalArea aChild, int index) { boolean wasAdded = false; if(addChild(aChild)) { if(index < 0 ) { index = 0; } if(index > numberOfChild()) { index = numberOfChild() - 1; } child.remove(aChild); child.add(index, aChild); wasAdded = true; } return wasAdded; } public boolean addOrMoveChildAt(FunctionalArea aChild, int index) { boolean wasAdded = false; if(child.contains(aChild)) { if(index < 0 ) { index = 0; } if(index > numberOfChild()) { index = numberOfChild() - 1; } child.remove(aChild); child.add(index, aChild); wasAdded = true; } else { wasAdded = addChildAt(aChild, index); } return wasAdded; } public boolean setParent(FunctionalArea aParent) { boolean wasSet = false; FunctionalArea existingParent = parent; parent = aParent; if (existingParent != null && !existingParent.equals(aParent)) { existingParent.removeChild(this); } if (aParent != null) { aParent.addChild(this); } wasSet = true; return wasSet; } public static int minimumNumberOfFacilities() { return 0; } public boolean addFacility(Facility aFacility) { boolean wasAdded = false; if (facilities.contains(aFacility)) { return false; } facilities.add(aFacility); if (aFacility.indexOfFunctionalArea(this) != -1) { wasAdded = true; } else { wasAdded = aFacility.addFunctionalArea(this); if (!wasAdded) { facilities.remove(aFacility); } } return wasAdded; } public boolean removeFacility(Facility aFacility) { boolean wasRemoved = false; if (!facilities.contains(aFacility)) { return wasRemoved; } int oldIndex = facilities.indexOf(aFacility); facilities.remove(oldIndex); if (aFacility.indexOfFunctionalArea(this) == -1) { wasRemoved = true; } else { wasRemoved = aFacility.removeFunctionalArea(this); if (!wasRemoved) { facilities.add(oldIndex,aFacility); } } return wasRemoved; } public boolean addFacilityAt(Facility aFacility, int index) { boolean wasAdded = false; if(addFacility(aFacility)) { if(index < 0 ) { index = 0; } if(index > numberOfFacilities()) { index = numberOfFacilities() - 1; } facilities.remove(aFacility); facilities.add(index, aFacility); wasAdded = true; } return wasAdded; } public boolean addOrMoveFacilityAt(Facility aFacility, int index) { boolean wasAdded = false; if(facilities.contains(aFacility)) { if(index < 0 ) { index = 0; } if(index > numberOfFacilities()) { index = numberOfFacilities() - 1; } facilities.remove(aFacility); facilities.add(index, aFacility); wasAdded = true; } else { wasAdded = addFacilityAt(aFacility, index); } return wasAdded; } public boolean equals(Object obj) { if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } FunctionalArea compareTo = (FunctionalArea)obj; if (code == null && compareTo.code != null) { return false; } else if (code != null && !code.equals(compareTo.code)) { return false; } return true; } public int hashCode() { if (cachedHashCode != -1) { return cachedHashCode; } cachedHashCode = 17; if (code != null) { cachedHashCode = cachedHashCode * 23 + code.hashCode(); } else { cachedHashCode = cachedHashCode * 23; } canSetCode = false; return cachedHashCode; } public void delete() { while( !child.isEmpty() ) { child.get(0).setParent(null); } if (parent != null) { FunctionalArea placeholderParent = parent; this.parent = null; placeholderParent.removeChild(this); } ArrayList<Facility> copyOfFacilities = new ArrayList<Facility>(facilities); facilities.clear(); for(Facility aFacility : copyOfFacilities) { aFacility.removeFunctionalArea(this); } } public String toString() { String outputString = ""; return super.toString() + "["+ "code" + ":" + getCode()+ "]" + outputString; } }
mit
pyokagan/CS2103AUG2016-T11-C4-main
src/main/java/seedu/address/logic/commands/HelpCommand.java
516
package seedu.address.logic.commands; import seedu.address.model.Model; /** * Requests the application to open its "help window". */ public class HelpCommand implements Command { @Override public CommandResult execute(Model model) { return new Result(); } private static class Result extends CommandResult implements HelpCommandResult { private static final String MSG_EXIT = "Opening help window..."; private Result() { super(MSG_EXIT); } } }
mit
stachon/XChange
xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/dto/CoinjarHeartbeat.java
641
package info.bitrich.xchangestream.coinjar.dto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.Maps; import java.util.Map; public class CoinjarHeartbeat { @JsonProperty("topic") public final String topic = "phoenix"; @JsonProperty("event") public final String event = "heartbeat"; @JsonProperty("payload") @JsonInclude(JsonInclude.Include.ALWAYS) public final Map<String, String> payload = Maps.newHashMap(); @JsonProperty("ref") public final Integer ref; public CoinjarHeartbeat(Integer ref) { this.ref = ref; } }
mit
bjhargrave/bndtools
bndtools.core/src/bndtools/wizards/project/NewBndProjectWizardPageTwo.java
4392
/******************************************************************************* * Copyright (c) 2010 Neil Bartlett. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Neil Bartlett - initial API and implementation *******************************************************************************/ package bndtools.wizards.project; import java.lang.reflect.InvocationTargetException; import org.bndtools.api.BndtoolsConstants; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageOne; import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageTwo; import org.eclipse.jface.operation.IRunnableWithProgress; import bndtools.Plugin; public class NewBndProjectWizardPageTwo extends NewJavaProjectWizardPageTwo { public NewBndProjectWizardPageTwo(NewJavaProjectWizardPageOne pageOne) { super(pageOne); } @Override public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { super.configureJavaProject(monitor); IProject project = getJavaProject().getProject(); IProjectDescription desc = project.getDescription(); String[] natures = desc.getNatureIds(); for (String nature : natures) { if (BndtoolsConstants.NATURE_ID.equals(nature)) return; } String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = BndtoolsConstants.NATURE_ID; desc.setNatureIds(newNatures); project.setDescription(desc, null); } void doSetProjectDesc(final IProject project, final IProjectDescription desc) throws CoreException { final IWorkspaceRunnable workspaceOp = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { project.setDescription(desc, monitor); } }; try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { project.getWorkspace().run(workspaceOp, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InvocationTargetException e) { throw (CoreException) e.getTargetException(); } catch (InterruptedException e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Interrupted while adding Bnd OSGi Project nature to project.", e)); } } @Override public boolean isPageComplete() { boolean resultFromSuperClass = super.isPageComplete(); int nr = 0; try { IClasspathEntry[] entries = getJavaProject().getResolvedClasspath(true); for (IClasspathEntry entry : entries) { if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { nr++; // here we could do more validation on the paths if we want to // for now we just count pages } } } catch (Exception e) { // if for some reason we cannot access the resolved classpath // we simply set an error message setErrorMessage("Could not access resolved classpaths: " + e); } // we're okay if we have exactly at most two valid source paths // most templates use 2 source sets (main + test) but some do not // have the test source set return resultFromSuperClass && (1 <= nr) && (nr <= 2); } }
epl-1.0
TypeFox/che
ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/partition/DocumentPartitioner.java
2443
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.api.editor.partition; import java.util.List; import org.eclipse.che.ide.api.editor.document.UseDocumentHandle; import org.eclipse.che.ide.api.editor.events.DocumentChangedHandler; import org.eclipse.che.ide.api.editor.text.TypedRegion; /** * Interface for document partitioner.<br> * Partitioners parse a document and splits it in partitions, which are contiguous zones of text of * a specific type (for example comment, literal string, code etc.). */ public interface DocumentPartitioner extends DocumentChangedHandler, UseDocumentHandle { /** The identifier of the default partition content type. */ String DEFAULT_CONTENT_TYPE = "__dftl_partition_content_type"; void initialize(); void release(); /** * Returns the set of all legal content types of this partitioner. I.e. any result delivered by * this partitioner may not contain a content type which would not be included in this method's * result. * * @return the set of legal content types */ List<String> getLegalContentTypes(); /** * Returns the content type of the partition containing the given offset in the connected * document. There must be a document connected to this partitioner. * * @param offset the offset in the connected document * @return the content type of the offset's partition */ String getContentType(int offset); /** * Returns the partitioning of the given range of the connected document. There must be a document * connected to this partitioner. * * @param offset the offset of the range of interest * @param length the length of the range of interest * @return the partitioning of the range */ List<TypedRegion> computePartitioning(int offset, int length); /** * Returns the partition containing the given offset of the connected document. There must be a * document connected to this partitioner. * * @param offset the offset for which to determine the partition * @return the partition containing the offset */ TypedRegion getPartition(int offset); }
epl-1.0
riuvshin/che-plugins
plugin-java/che-plugin-java-ext-java/src/main/java/org/eclipse/che/ide/ext/java/jdt/internal/text/correction/proposals/NewMethodCorrectionProposal.java
14574
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Benjamin Muskalla - [quick fix] Create Method in void context should 'box' void. - https://bugs.eclipse.org/bugs/show_bug * .cgi?id=107985 *******************************************************************************/ package org.eclipse.che.ide.ext.java.jdt.internal.text.correction.proposals; import org.eclipse.che.ide.ext.java.jdt.Images; import org.eclipse.che.ide.ext.java.jdt.core.NamingConventions; import org.eclipse.che.ide.ext.java.jdt.core.dom.AST; import org.eclipse.che.ide.ext.java.jdt.core.dom.ASTNode; import org.eclipse.che.ide.ext.java.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.che.ide.ext.java.jdt.core.dom.ClassInstanceCreation; import org.eclipse.che.ide.ext.java.jdt.core.dom.Expression; import org.eclipse.che.ide.ext.java.jdt.core.dom.ExpressionStatement; import org.eclipse.che.ide.ext.java.jdt.core.dom.IBinding; import org.eclipse.che.ide.ext.java.jdt.core.dom.IExtendedModifier; import org.eclipse.che.ide.ext.java.jdt.core.dom.ITypeBinding; import org.eclipse.che.ide.ext.java.jdt.core.dom.MethodDeclaration; import org.eclipse.che.ide.ext.java.jdt.core.dom.MethodInvocation; import org.eclipse.che.ide.ext.java.jdt.core.dom.Modifier; import org.eclipse.che.ide.ext.java.jdt.core.dom.Name; import org.eclipse.che.ide.ext.java.jdt.core.dom.ParameterizedType; import org.eclipse.che.ide.ext.java.jdt.core.dom.PrimitiveType; import org.eclipse.che.ide.ext.java.jdt.core.dom.SimpleName; import org.eclipse.che.ide.ext.java.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.che.ide.ext.java.jdt.core.dom.SuperMethodInvocation; import org.eclipse.che.ide.ext.java.jdt.core.dom.Type; import org.eclipse.che.ide.ext.java.jdt.core.dom.TypeDeclaration; import org.eclipse.che.ide.ext.java.jdt.core.dom.TypeParameter; import org.eclipse.che.ide.ext.java.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.che.ide.ext.java.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.che.ide.ext.java.jdt.internal.corext.codemanipulation.ASTResolving; import org.eclipse.che.ide.ext.java.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.che.ide.ext.java.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.che.ide.ext.java.jdt.internal.corext.dom.ASTNodes; import org.eclipse.che.ide.ext.java.jdt.internal.corext.dom.Bindings; import org.eclipse.che.ide.ext.java.jdt.text.Document; import org.eclipse.che.ide.runtime.CoreException; import java.util.List; public class NewMethodCorrectionProposal extends AbstractMethodCorrectionProposal { private static final String KEY_NAME = "name"; //$NON-NLS-1$ private static final String KEY_TYPE = "type"; //$NON-NLS-1$ private List<Expression> fArguments; // invocationNode is MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation public NewMethodCorrectionProposal(String label, ASTNode invocationNode, List<Expression> arguments, ITypeBinding binding, int relevance, Document document, Images image) { super(label, invocationNode, binding, relevance, document, image); fArguments = arguments; } private int evaluateModifiers(ASTNode targetTypeDecl) { if (getSenderBinding().isAnnotation()) { return 0; } if (getSenderBinding().isInterface()) { // for interface and annotation members copy the modifiers from an existing field MethodDeclaration[] methodDecls = ((TypeDeclaration)targetTypeDecl).getMethods(); if (methodDecls.length > 0) { return methodDecls[0].getModifiers(); } return 0; } ASTNode invocationNode = getInvocationNode(); if (invocationNode instanceof MethodInvocation) { int modifiers = 0; Expression expression = ((MethodInvocation)invocationNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name)expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(invocationNode)) { modifiers |= Modifier.STATIC; } ASTNode node = ASTResolving.findParentType(invocationNode); if (targetTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; } else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) { modifiers |= Modifier.PROTECTED; if (ASTResolving.isInStaticContext(node) && expression == null) { modifiers |= Modifier.STATIC; } } else { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewModifiers(org.eclipse.jdt.core * .dom.rewrite.ASTRewrite, org.eclipse.jdt.core.dom.ASTNode, java.util.List) */ @Override protected void addNewModifiers(ASTRewrite rewrite, ASTNode targetTypeDecl, List<IExtendedModifier> modifiers) { modifiers.addAll(rewrite.getAST().newModifiers(evaluateModifiers(targetTypeDecl))); // ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(rewrite, modifiers, // getSenderBinding().isInterface()); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#isConstructor() */ @Override protected boolean isConstructor() { ASTNode node = getInvocationNode(); return node.getNodeType() != ASTNode.METHOD_INVOCATION && node.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#getNewName(org.eclipse.jdt.core.dom * .rewrite.ASTRewrite) */ @Override protected SimpleName getNewName(ASTRewrite rewrite) { ASTNode invocationNode = getInvocationNode(); String name; if (invocationNode instanceof MethodInvocation) { name = ((MethodInvocation)invocationNode).getName().getIdentifier(); } else if (invocationNode instanceof SuperMethodInvocation) { name = ((SuperMethodInvocation)invocationNode).getName().getIdentifier(); } else { name = getSenderBinding().getName(); // name of the class } AST ast = rewrite.getAST(); SimpleName newNameNode = ast.newSimpleName(name); // addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME); ASTNode invocationName = getInvocationNameNode(); // if (invocationName != null && invocationName.getAST() == ast) // { // in the same CU // addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME); // } return newNameNode; } private ASTNode getInvocationNameNode() { ASTNode node = getInvocationNode(); if (node instanceof MethodInvocation) { return ((MethodInvocation)node).getName(); } else if (node instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)node).getName(); } else if (node instanceof ClassInstanceCreation) { Type type = ((ClassInstanceCreation)node).getType(); while (type instanceof ParameterizedType) { type = ((ParameterizedType)type).getType(); } return type; } return null; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#getNewMethodType(org.eclipse.jdt.core * .dom.rewrite.ASTRewrite) */ @Override protected Type getNewMethodType(ASTRewrite rewrite) throws CoreException { ASTNode node = getInvocationNode(); AST ast = rewrite.getAST(); Type newTypeNode = null; ITypeBinding[] otherProposals = null; ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, getImportRewrite()); if (node.getParent() instanceof MethodInvocation) { MethodInvocation parent = (MethodInvocation)node.getParent(); if (parent.getExpression() == node) { ITypeBinding[] bindings = ASTResolving.getQualifierGuess(node.getRoot(), parent.getName().getIdentifier(), parent.arguments(), getSenderBinding()); if (bindings.length > 0) { newTypeNode = getImportRewrite().addImport(bindings[0], ast, importRewriteContext); otherProposals = bindings; } } } if (newTypeNode == null) { ITypeBinding binding = ASTResolving.guessBindingForReference(node); if (binding != null && binding.isWildcardType()) { binding = ASTResolving.normalizeWildcardType(binding, false, ast); } if (binding != null) { newTypeNode = getImportRewrite().addImport(binding, ast, importRewriteContext); } else { ASTNode parent = node.getParent(); if (parent instanceof ExpressionStatement) { newTypeNode = ast.newPrimitiveType(PrimitiveType.VOID); } else { newTypeNode = ASTResolving.guessTypeForReference(ast, node); if (newTypeNode == null) { newTypeNode = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } } } } // addLinkedPosition(rewrite.track(newTypeNode), false, KEY_TYPE); // if (otherProposals != null) // { // for (int i = 0; i < otherProposals.length; i++) // { // addLinkedPositionProposal(KEY_TYPE, otherProposals[i]); // } // } return newTypeNode; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewParameters(org.eclipse.jdt.core * .dom.rewrite.ASTRewrite, java.util.List, java.util.List) */ @Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException { AST ast = rewrite.getAST(); List<Expression> arguments = fArguments; ImportRewriteContext context = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(getInvocationNode()), getImportRewrite()); for (int i = 0; i < arguments.size(); i++) { Expression elem = arguments.get(i); SingleVariableDeclaration param = ast.newSingleVariableDeclaration(); // argument type String argTypeKey = "arg_type_" + i; //$NON-NLS-1$ Type type = evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey = "arg_name_" + i; //$NON-NLS-1$ String name = evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); // // addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey); // addLinkedPosition(rewrite.track(param.getName()), false, argNameKey); } } private Type evaluateParameterType(AST ast, Expression elem, String key, ImportRewriteContext context) { ITypeBinding binding = Bindings.normalizeTypeBinding(elem.resolveTypeBinding()); if (binding != null && binding.isWildcardType()) { binding = ASTResolving.normalizeWildcardType(binding, true, ast); } if (binding != null) { // ITypeBinding[] typeProposals = ASTResolving.getRelaxingTypes(ast, binding); // for (int i = 0; i < typeProposals.length; i++) // { // addLinkedPositionProposal(key, typeProposals[i]); // } return getImportRewrite().addImport(binding, ast, context); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } private String evaluateParameterName(List<String> takenNames, Expression argNode, Type type, String key) { // IJavaProject project = getCompilationUnit().getJavaProject(); String[] names = StubUtility.getVariableNameSuggestions(NamingConventions.VK_PARAMETER, type, argNode, takenNames); // for (int i = 0; i < names.length; i++) // { // addLinkedPositionProposal(key, names[i], null); // } String favourite = names[0]; takenNames.add(favourite); return favourite; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewExceptions(org.eclipse.jdt.core * .dom.rewrite.ASTRewrite, java.util.List) */ @Override protected void addNewExceptions(ASTRewrite rewrite, List<Name> exceptions) throws CoreException { } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewTypeParameters(org.eclipse.jdt.core.dom.rewrite.ASTRewrite, java.util.List, java.util.List) */ @Override protected void addNewTypeParameters(ASTRewrite rewrite, List<String> takenNames, List<TypeParameter> params) throws CoreException { } }
epl-1.0
seddikouiss/pivo4j
pivot4j-core/src/main/java/org/pivot4j/ui/condition/AndCondition.java
4984
/* * ==================================================================== * This software is subject to the terms of the Common Public License * Agreement, available at the following URL: * http://www.opensource.org/licenses/cpl.html . * You must accept the terms of that agreement to use this software. * ==================================================================== */ package org.pivot4j.ui.condition; import java.io.Serializable; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.configuration.HierarchicalConfiguration; import org.pivot4j.ui.RenderContext; public class AndCondition extends AbstractCondition { public static final String NAME = "and"; private List<Condition> subConditions; /** * @param conditionFactory */ public AndCondition(ConditionFactory conditionFactory) { super(conditionFactory); } /** * @param conditionFactory * @param subConditions */ public AndCondition(ConditionFactory conditionFactory, Condition... subConditions) { super(conditionFactory); if (subConditions != null) { this.subConditions = new LinkedList<Condition>( Arrays.asList(subConditions)); } } /** * @param conditionFactory */ public AndCondition(ConditionFactory conditionFactory, List<Condition> subConditions) { super(conditionFactory); this.subConditions = subConditions; } /** * @see org.pivot4j.ui.condition.Condition#getName() */ public String getName() { return NAME; } /** * @return the subConditions */ public List<Condition> getSubConditions() { return subConditions; } /** * @param subConditions * the subConditions to set */ public void setSubConditions(List<Condition> subConditions) { this.subConditions = subConditions; } /** * @see org.pivot4j.ui.condition.Condition#matches(org.pivot4j.ui.RenderContext) */ public boolean matches(RenderContext context) { if (subConditions == null || subConditions.isEmpty()) { throw new IllegalStateException("Missing sub conditions."); } for (Condition condition : subConditions) { if (!condition.matches(context)) { return false; } } return true; } /** * @see org.pivot4j.state.Bookmarkable#saveState() */ @Override public Serializable saveState() { if (subConditions == null) { return null; } Serializable[] states = new Serializable[subConditions.size()]; int index = 0; for (Condition condition : subConditions) { states[index++] = new Serializable[] { condition.getName(), condition.saveState() }; } return states; } /** * @see org.pivot4j.state.Bookmarkable#restoreState(java.io.Serializable) */ @Override public void restoreState(Serializable state) { Serializable[] states = (Serializable[]) state; this.subConditions = new LinkedList<Condition>(); if (states != null) { for (Serializable subState : states) { Serializable[] subStates = (Serializable[]) subState; Condition condition = getConditionFactory().createCondition( (String) subStates[0]); condition.restoreState(subStates[1]); this.subConditions.add(condition); } } } /** * @see org.pivot4j.ui.condition.AbstractCondition#saveSettings(org.apache.commons.configuration.HierarchicalConfiguration) */ @Override public void saveSettings(HierarchicalConfiguration configuration) { super.saveSettings(configuration); if (subConditions == null) { return; } int index = 0; for (Condition condition : subConditions) { String name = String.format("condition(%s)", index++); configuration.setProperty(name, ""); HierarchicalConfiguration subConfig = configuration .configurationAt(name); condition.saveSettings(subConfig); } } /** * @see org.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration) */ @Override public void restoreSettings(HierarchicalConfiguration configuration) { this.subConditions = new LinkedList<Condition>(); try { List<HierarchicalConfiguration> subConfigs = configuration .configurationsAt("condition"); for (HierarchicalConfiguration subConfig : subConfigs) { String name = subConfig.getString("[@name]"); if (name != null) { Condition condition = getConditionFactory() .createCondition(name); condition.restoreSettings(subConfig); this.subConditions.add(condition); } } } catch (IllegalArgumentException e) { } } /** * @see org.pivot4j.ui.condition.AbstractCondition#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("("); if (subConditions != null) { boolean first = true; for (Condition condition : subConditions) { if (first) { first = false; } else { builder.append(" && "); } builder.append(condition.toString()); } } builder.append(")"); return builder.toString(); } }
epl-1.0
moocnobody/ilp9moocnobody
Java/src/com/paracamplus/ilp9/parser/AbstractExtensibleParser.java
3672
/* ***************************************************************** * ILP9 - Implantation d'un langage de programmation. * by Christian.Queinnec@paracamplus.com * See http://mooc.paracamplus.com/ilp9 * GPL version 3 ***************************************************************** */ package com.paracamplus.ilp9.parser; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.paracamplus.ilp9.interfaces.IAST; public abstract class AbstractExtensibleParser extends AbstractParser { public AbstractExtensibleParser(IParserFactory factory) { super(factory); this.parsers = new HashMap<>(); } private final HashMap<String, Method> parsers; public void addParser (String name, Method method) { this.parsers.put(name, method); } public void addMethod (String name, Class<?> clazz) { addParser(name, findMethod(name, clazz)); } public void addMethod (String name, Class<?> clazz, String tagName) { addParser(tagName, findMethod(name, clazz)); } public Method findMethod (String name, Class<?> clazz) { try { for ( Method m : clazz.getMethods() ) { if ( ! name.equals(m.getName()) ) { continue; } if ( Modifier.isStatic(m.getModifiers()) ) { continue; } Class<?>[] parameterTypes = m.getParameterTypes(); if ( parameterTypes.length != 1 ) { continue; } if ( ! Element.class.isAssignableFrom(parameterTypes[0]) ) { continue; } return m; } if ( Object.class == clazz ) { final String msg = "Cannot find suitable parsing method!"; throw new RuntimeException(msg); } else { return findMethod(name, clazz.getSuperclass()); } } catch (SecurityException e1) { final String msg = "Cannot access parsing method!"; throw new RuntimeException(msg); } } public IAST parse (final Node n) throws ParseException { switch ( n.getNodeType() ) { case Node.ELEMENT_NODE: { final Element e = (Element) n; final String name = e.getTagName(); if ( parsers.containsKey(name) ) { final Method method = parsers.get(name); try { Object result = method.invoke(this, new Object[]{e}); if ( result != null && result instanceof IAST ) { return (IAST) result; } else { final String msg = "Not an IAST " + result; throw new ParseException(msg); } } catch (IllegalArgumentException exc) { throw new ParseException(exc); } catch (IllegalAccessException exc) { throw new ParseException(exc); } catch (InvocationTargetException exc) { Throwable t = exc.getTargetException(); if ( t instanceof ParseException ) { throw (ParseException) t; } else { throw new ParseException(exc); } } } else { final String msg = "Unknown element name: " + name; throw new ParseException(msg); } } default: { final String msg = "Unknown node type: " + n.getNodeName(); throw new ParseException(msg); } } } }
gpl-2.0
malizadehq/MyTelegram
TMessagesProj/src/main/java/org/telegram/messenger/exoplayer/hls/Aes128DataSource.java
3677
/* * Copyright (C) 2014 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 org.telegram.messenger.exoplayer.hls; import org.telegram.messenger.exoplayer.C; import org.telegram.messenger.exoplayer.upstream.DataSource; import org.telegram.messenger.exoplayer.upstream.DataSourceInputStream; import org.telegram.messenger.exoplayer.upstream.DataSpec; import org.telegram.messenger.exoplayer.util.Assertions; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * A {@link DataSource} that decrypts data read from an upstream source, encrypted with AES-128 with * a 128-bit key and PKCS7 padding. * <p> * Note that this {@link DataSource} does not support being opened from arbitrary offsets. It is * designed specifically for reading whole files as defined in an HLS media playlist. For this * reason the implementation is private to the HLS package. */ /* package */ final class Aes128DataSource implements DataSource { private final DataSource upstream; private final byte[] encryptionKey; private final byte[] encryptionIv; private CipherInputStream cipherInputStream; /** * @param upstream The upstream {@link DataSource}. * @param encryptionKey The encryption key. * @param encryptionIv The encryption initialization vector. */ public Aes128DataSource(DataSource upstream, byte[] encryptionKey, byte[] encryptionIv) { this.upstream = upstream; this.encryptionKey = encryptionKey; this.encryptionIv = encryptionIv; } @Override public long open(DataSpec dataSpec) throws IOException { Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (NoSuchPaddingException e) { throw new RuntimeException(e); } Key cipherKey = new SecretKeySpec(encryptionKey, "AES"); AlgorithmParameterSpec cipherIV = new IvParameterSpec(encryptionIv); try { cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherIV); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } cipherInputStream = new CipherInputStream( new DataSourceInputStream(upstream, dataSpec), cipher); return C.LENGTH_UNBOUNDED; } @Override public void close() throws IOException { cipherInputStream = null; upstream.close(); } @Override public int read(byte[] buffer, int offset, int readLength) throws IOException { Assertions.checkState(cipherInputStream != null); int bytesRead = cipherInputStream.read(buffer, offset, readLength); if (bytesRead < 0) { return -1; } return bytesRead; } }
gpl-2.0
teamfx/openjfx-9-dev-rt
modules/javafx.graphics/src/jslc/java/com/sun/scenario/effect/compiler/tree/ForStmt.java
2228
/* * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.scenario.effect.compiler.tree; /** */ public class ForStmt extends Stmt { private final Stmt init; private final Expr cond; private final Expr expr; private final Stmt stmt; private final int unrollMax; private final int unrollCheck; ForStmt(Stmt init, Expr cond, Expr expr, Stmt stmt, int unrollMax, int unrollCheck) { this.init = init; this.cond = cond; this.expr = expr; this.stmt = stmt; this.unrollMax = unrollMax; this.unrollCheck = unrollCheck; } public Stmt getInit() { return init; } public Expr getCondition() { return cond; } public Expr getExpr() { return expr; } public Stmt getStmt() { return stmt; } public int getUnrollMax() { return unrollMax; } public int getUnrollCheck() { return unrollCheck; } public void accept(TreeVisitor tv) { tv.visitForStmt(this); } }
gpl-2.0
acm-uiuc/Tacchi
src/org/mt4j/components/visibleComponents/widgets/MTImage.java
11933
/*********************************************************************** * mt4j Copyright (c) 2008 - 2009, C.Ruff, Fraunhofer-Gesellschaft All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***********************************************************************/ package org.mt4j.components.visibleComponents.widgets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.mt4j.MTApplication; import org.mt4j.components.MTComponent; import org.mt4j.components.TransformSpace; import org.mt4j.components.visibleComponents.shapes.AbstractShape; import org.mt4j.components.visibleComponents.shapes.MTPolygon; import org.mt4j.components.visibleComponents.shapes.MTRectangle; import org.mt4j.components.visibleComponents.widgets.buttons.MTSvgButton; import org.mt4j.input.inputProcessors.componentProcessors.lassoProcessor.IdragClusterable; import org.mt4j.input.inputProcessors.componentProcessors.tapProcessor.TapEvent; import org.mt4j.util.MT4jSettings; import org.mt4j.util.MTColor; import org.mt4j.util.animation.Animation; import org.mt4j.util.animation.AnimationEvent; import org.mt4j.util.animation.IAnimationListener; import org.mt4j.util.animation.MultiPurposeInterpolator; import org.mt4j.util.math.Vector3D; import processing.core.PApplet; import processing.core.PImage; /** * The Class MTImage. A widget which can be used to display a image texture surrounded * by a frame. * The image itself is actually a child of this class, which acts as the frame. * * @author Christopher Ruff */ public class MTImage extends MTRectangle implements IdragClusterable{ /** The selected. */ private boolean selected; private MTRectangle image; /** * Instantiates a new framed image. * * @param texture the texture * @param pApplet the applet */ public MTImage(PImage texture, PApplet pApplet) { super(-7, -7, texture.width + 14, texture.height + 14, pApplet); image = new MTRectangle(texture, pApplet); image.setStrokeColor(new MTColor(255,255,255,255)); image.setPickable(false); //Set the image to use direct gl - thread safe if (MT4jSettings.getInstance().isOpenGlMode()){ if (pApplet instanceof MTApplication) { MTApplication app = (MTApplication) pApplet; app.invokeLater(new Runnable() { public void run() { image.setUseDirectGL(true); } }); } } this.addChild(image); //Draw this component and its children above //everything previously drawn and avoid z-fighting this.setDepthBufferDisabled(true); } public MTRectangle getImage(){ return this.image; } // /** // * Instantiates a new framed image. // * // * @param texture the texture // * @param pApplet the applet // */ // public MTImage(PImage texture, PApplet pApplet) { // super(texture, pApplet); // // int borderWidth = 7; // Vertex[] outerFrame = new Vertex[5]; // outerFrame[0] = new Vertex(-borderWidth, -borderWidth,0, 255,255,255,255); // outerFrame[1] = new Vertex(texture.width+borderWidth, -borderWidth, 0, 255,255,255,255); // outerFrame[2] = new Vertex(texture.width+borderWidth, texture.height+borderWidth, 0, 255,255,255,255); // outerFrame[3] = new Vertex(-borderWidth, texture.height+borderWidth, 0, 255,255,255,255); // outerFrame[4] = new Vertex(-borderWidth, -borderWidth, 0, 255,255,255,255); // // Vertex[] innerFrame = new Vertex[5]; // innerFrame[0] = new Vertex(0, 0, 0, 255,255,255,255); // innerFrame[1] = new Vertex(texture.width, 0, 0, 255,255,255,255); // innerFrame[2] = new Vertex(texture.width, texture.height, 0, 255,255,255,255); // innerFrame[3] = new Vertex(0, texture.height, 0, 255,255,255,255); // innerFrame[4] = new Vertex(0, 0, 0, 255,255,255,255); // // ArrayList<Vertex[]> frame = new ArrayList<Vertex[]>(); // frame.add(innerFrame); // frame.add(outerFrame); // GluTrianglulator glutri = new GluTrianglulator(pApplet); // List<Vertex> tris = glutri.tesselate(frame, GLU.GLU_TESS_WINDING_ODD); // glutri.deleteTess(); // MTTriangleMesh m = new MTTriangleMesh(pApplet, new GeometryInfo(pApplet, tris.toArray(new Vertex[tris.size()]))); // m.setOutlineContours(frame); // m.setDrawSmooth(true); //// MTRectangle m = new MTRectangle(-borderWidth,-borderWidth, texture.width + borderWidth, texture.height + borderWidth, pApplet); // m.setUseDirectGL(true); // // m.setNoStroke(false); // m.setStrokeWeight(1); // m.setStrokeColor(new MTColor(255, 255, 255, 255)); // // //If the frame is manipulated, manipulate the image instead // m.removeAllGestureEventListeners(DragProcessor.class); // m.removeAllGestureEventListeners(RotateProcessor.class); // m.removeAllGestureEventListeners(ScaleProcessor.class); // m.addGestureListener(DragProcessor.class, new DefaultDragAction(this)); // m.addGestureListener(RotateProcessor.class, new DefaultRotateAction(this)); // m.addGestureListener(ScaleProcessor.class, new DefaultScaleAction(this)); // // this.addChild(m); // // this.setNoStroke(true); // this.setStrokeWeight(1); // this.setStrokeColor(new MTColor(255, 255, 255, 255)); // // //FIXME if one finger is on frame and one on picture, they dont start a 2 finger gesture // //FIXME if image in cluster and dragging frame, the cluster should be dragged but the image is // // //Draw this component and its children above // //everything previously drawn and avoid z-fighting // this.setDepthBufferDisabled(true); // } /* (non-Javadoc) * @see com.jMT.input.inputAnalyzers.clusterInputAnalyzer.IdragClusterable#isSelected() */ public boolean isSelected() { return selected; } /* (non-Javadoc) * @see com.jMT.input.inputAnalyzers.clusterInputAnalyzer.IdragClusterable#setSelected(boolean) */ public void setSelected(boolean selected) { this.selected = selected; } /** * Sets the display close button. * * @param dispClose the new display close button */ public void setDisplayCloseButton(boolean dispClose){ if (dispClose){ MTSvgButton keybCloseSvg = new MTSvgButton(MT4jSettings.getInstance().getDefaultSVGPath() + "keybClose.svg", this.getRenderer()); //Transform keybCloseSvg.scale(0.5f, 0.5f, 1, new Vector3D(0,0,0)); keybCloseSvg.translate(new Vector3D(this.getWidthXY(TransformSpace.RELATIVE_TO_PARENT) - 45, 2,0)); keybCloseSvg.setBoundsPickingBehaviour(AbstractShape.BOUNDS_ONLY_CHECK); keybCloseSvg.addActionListener(new CloseActionListener(new MTComponent[]{this, keybCloseSvg}) ); // pic.addChild(keybCloseSvg); keybCloseSvg.setName("closeButton"); this.addChild(keybCloseSvg); }else{ //Remove svg button and destroy child display lists MTComponent[] childs = this.getChildren(); for (int i = 0; i < childs.length; i++) { MTComponent component = childs[i]; if (component.getName().equals("closeButton")) { MTSvgButton svgButton = (MTSvgButton) component; svgButton.destroy(); } } } } /** * The Class CloseActionListener. * * @author Cruff */ private class CloseActionListener implements ActionListener{ /** The comps. */ public MTComponent[] comps; /** The reference poly for resizing the button. */ private MTPolygon referencePoly; /** * Instantiates a new close action listener. * * @param comps the comps */ public CloseActionListener(MTComponent[] comps) { super(); this.comps = comps; } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { switch (arg0.getID()) { case TapEvent.BUTTON_CLICKED: //Get the first polygon type out of the array for (int i = 0; i < comps.length; i++) { //TODO this is stupid.. redo this whole thing MTComponent comp = comps[i]; if (comp instanceof MTPolygon) { MTPolygon poly = (MTPolygon) comp; if (referencePoly == null){//nur 1. occur zuweisen referencePoly = poly; } } } float width = referencePoly.getWidthXY(TransformSpace.RELATIVE_TO_PARENT); Animation closeAnim = new Animation("comp Fade", new MultiPurposeInterpolator(width, 1, 300, 0.5f, 0.8f, 1), referencePoly); closeAnim.addAnimationListener(new IAnimationListener(){ public void processAnimationEvent(AnimationEvent ae) { switch (ae.getId()) { case AnimationEvent.ANIMATION_STARTED: case AnimationEvent.ANIMATION_UPDATED: float currentVal = ae.getAnimation().getInterpolator().getCurrentValue(); resize(referencePoly, comps[0], currentVal, currentVal); break; case AnimationEvent.ANIMATION_ENDED: comps[0].setVisible(false); for (int i = comps.length-1; i >0 ; i--) { MTComponent currentComp = comps[i]; //Call destroy which fires a destroy state change event currentComp.destroy(); //System.out.println("destroyed: " + currentComp.getName()); } destroy(); //System.out.println("destroyed: " + getName()); break; default: destroy(); break; }//switch }//processanimation });//new IAnimationListener closeAnim.start(); break; default: break; }//switch aeID } /** * Resize. * * @param referenceComp the reference comp * @param compToResize the comp to resize * @param width the width * @param height the height */ protected void resize(MTPolygon referenceComp, MTComponent compToResize, float width, float height){ Vector3D centerPoint = getRefCompCenterRelParent(referenceComp); compToResize.scale(1/referenceComp.getWidthXY(TransformSpace.RELATIVE_TO_PARENT), (float)1/referenceComp.getWidthXY(TransformSpace.RELATIVE_TO_PARENT), 1, centerPoint, TransformSpace.RELATIVE_TO_PARENT); compToResize.scale(width, width, 1, centerPoint, TransformSpace.RELATIVE_TO_PARENT); } /** * Gets the ref comp center local. * * @param shape the shape * * @return the ref comp center local */ protected Vector3D getRefCompCenterRelParent(AbstractShape shape){ Vector3D centerPoint; if (shape.isBoundingShapeSet()){ centerPoint = shape.getBoundingShape().getCenterPointLocal(); centerPoint.transform(shape.getLocalMatrix()); //macht den punkt in self space }else{ Vector3D localObjCenter = shape.getCenterPointGlobal(); localObjCenter.transform(shape.getGlobalInverseMatrix()); //to localobj space localObjCenter.transform(shape.getLocalMatrix()); //to parent relative space centerPoint = localObjCenter; } return centerPoint; } }//Class closebutton actionlistener }
gpl-2.0
silid/project-x-cvs
src/net/sourceforge/dvb/projectx/gui/CheckBoxListener.java
1473
/* * @(#)CheckBoxListener * * Copyright (c) 2005 by dvb.matt, All Rights Reserved. * * This file is part of ProjectX, a free Java based demux utility. * By the authors, ProjectX is intended for educational purposes only, * as a non-commercial test project. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package net.sourceforge.dvb.projectx.gui; import javax.swing.JCheckBox; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import net.sourceforge.dvb.projectx.common.Common; /** * */ public class CheckBoxListener implements ActionListener { public void actionPerformed(ActionEvent e) { String actName = e.getActionCommand(); JCheckBox box = (JCheckBox)e.getSource(); Common.getSettings().setBooleanProperty(actName, box.isSelected()); } }
gpl-2.0
Taichi-SHINDO/jdk9-jdk
src/java.base/share/classes/com/sun/crypto/provider/TlsPrfGenerator.java
13678
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.crypto.provider; import java.util.Arrays; import java.security.*; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import sun.security.internal.spec.TlsPrfParameterSpec; /** * KeyGenerator implementation for the TLS PRF function. * <p> * This class duplicates the HMAC functionality (RFC 2104) with * performance optimizations (e.g. XOR'ing keys with padding doesn't * need to be redone for each HMAC operation). * * @author Andreas Sterbenz * @since 1.6 */ abstract class TlsPrfGenerator extends KeyGeneratorSpi { // magic constants and utility functions, also used by other files // in this package private final static byte[] B0 = new byte[0]; final static byte[] LABEL_MASTER_SECRET = // "master secret" { 109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 }; final static byte[] LABEL_KEY_EXPANSION = // "key expansion" { 107, 101, 121, 32, 101, 120, 112, 97, 110, 115, 105, 111, 110 }; final static byte[] LABEL_CLIENT_WRITE_KEY = // "client write key" { 99, 108, 105, 101, 110, 116, 32, 119, 114, 105, 116, 101, 32, 107, 101, 121 }; final static byte[] LABEL_SERVER_WRITE_KEY = // "server write key" { 115, 101, 114, 118, 101, 114, 32, 119, 114, 105, 116, 101, 32, 107, 101, 121 }; final static byte[] LABEL_IV_BLOCK = // "IV block" { 73, 86, 32, 98, 108, 111, 99, 107 }; /* * TLS HMAC "inner" and "outer" padding. This isn't a function * of the digest algorithm. */ private static final byte[] HMAC_ipad64 = genPad((byte)0x36, 64); private static final byte[] HMAC_ipad128 = genPad((byte)0x36, 128); private static final byte[] HMAC_opad64 = genPad((byte)0x5c, 64); private static final byte[] HMAC_opad128 = genPad((byte)0x5c, 128); // SSL3 magic mix constants ("A", "BB", "CCC", ...) final static byte[][] SSL3_CONST = genConst(); static byte[] genPad(byte b, int count) { byte[] padding = new byte[count]; Arrays.fill(padding, b); return padding; } static byte[] concat(byte[] b1, byte[] b2) { int n1 = b1.length; int n2 = b2.length; byte[] b = new byte[n1 + n2]; System.arraycopy(b1, 0, b, 0, n1); System.arraycopy(b2, 0, b, n1, n2); return b; } private static byte[][] genConst() { int n = 10; byte[][] arr = new byte[n][]; for (int i = 0; i < n; i++) { byte[] b = new byte[i + 1]; Arrays.fill(b, (byte)('A' + i)); arr[i] = b; } return arr; } // PRF implementation private final static String MSG = "TlsPrfGenerator must be " + "initialized using a TlsPrfParameterSpec"; @SuppressWarnings("deprecation") private TlsPrfParameterSpec spec; public TlsPrfGenerator() { } protected void engineInit(SecureRandom random) { throw new InvalidParameterException(MSG); } @SuppressWarnings("deprecation") protected void engineInit(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (params instanceof TlsPrfParameterSpec == false) { throw new InvalidAlgorithmParameterException(MSG); } this.spec = (TlsPrfParameterSpec)params; SecretKey key = spec.getSecret(); if ((key != null) && ("RAW".equals(key.getFormat()) == false)) { throw new InvalidAlgorithmParameterException( "Key encoding format must be RAW"); } } protected void engineInit(int keysize, SecureRandom random) { throw new InvalidParameterException(MSG); } SecretKey engineGenerateKey0(boolean tls12) { if (spec == null) { throw new IllegalStateException( "TlsPrfGenerator must be initialized"); } SecretKey key = spec.getSecret(); byte[] secret = (key == null) ? null : key.getEncoded(); try { byte[] labelBytes = spec.getLabel().getBytes("UTF8"); int n = spec.getOutputLength(); byte[] prfBytes = (tls12 ? doTLS12PRF(secret, labelBytes, spec.getSeed(), n, spec.getPRFHashAlg(), spec.getPRFHashLength(), spec.getPRFBlockSize()) : doTLS10PRF(secret, labelBytes, spec.getSeed(), n)); return new SecretKeySpec(prfBytes, "TlsPrf"); } catch (GeneralSecurityException e) { throw new ProviderException("Could not generate PRF", e); } catch (java.io.UnsupportedEncodingException e) { throw new ProviderException("Could not generate PRF", e); } } static byte[] doTLS12PRF(byte[] secret, byte[] labelBytes, byte[] seed, int outputLength, String prfHash, int prfHashLength, int prfBlockSize) throws NoSuchAlgorithmException, DigestException { if (prfHash == null) { throw new NoSuchAlgorithmException("Unspecified PRF algorithm"); } MessageDigest prfMD = MessageDigest.getInstance(prfHash); return doTLS12PRF(secret, labelBytes, seed, outputLength, prfMD, prfHashLength, prfBlockSize); } static byte[] doTLS12PRF(byte[] secret, byte[] labelBytes, byte[] seed, int outputLength, MessageDigest mdPRF, int mdPRFLen, int mdPRFBlockSize) throws DigestException { if (secret == null) { secret = B0; } // If we have a long secret, digest it first. if (secret.length > mdPRFBlockSize) { secret = mdPRF.digest(secret); } byte[] output = new byte[outputLength]; byte [] ipad; byte [] opad; switch (mdPRFBlockSize) { case 64: ipad = HMAC_ipad64.clone(); opad = HMAC_opad64.clone(); break; case 128: ipad = HMAC_ipad128.clone(); opad = HMAC_opad128.clone(); break; default: throw new DigestException("Unexpected block size."); } // P_HASH(Secret, label + seed) expand(mdPRF, mdPRFLen, secret, 0, secret.length, labelBytes, seed, output, ipad, opad); return output; } static byte[] doTLS10PRF(byte[] secret, byte[] labelBytes, byte[] seed, int outputLength) throws NoSuchAlgorithmException, DigestException { MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest sha = MessageDigest.getInstance("SHA1"); return doTLS10PRF(secret, labelBytes, seed, outputLength, md5, sha); } static byte[] doTLS10PRF(byte[] secret, byte[] labelBytes, byte[] seed, int outputLength, MessageDigest md5, MessageDigest sha) throws DigestException { /* * Split the secret into two halves S1 and S2 of same length. * S1 is taken from the first half of the secret, S2 from the * second half. * Their length is created by rounding up the length of the * overall secret divided by two; thus, if the original secret * is an odd number of bytes long, the last byte of S1 will be * the same as the first byte of S2. * * Note: Instead of creating S1 and S2, we determine the offset into * the overall secret where S2 starts. */ if (secret == null) { secret = B0; } int off = secret.length >> 1; int seclen = off + (secret.length & 1); byte[] secKey = secret; int keyLen = seclen; byte[] output = new byte[outputLength]; // P_MD5(S1, label + seed) // If we have a long secret, digest it first. if (seclen > 64) { // 64: block size of HMAC-MD5 md5.update(secret, 0, seclen); secKey = md5.digest(); keyLen = secKey.length; } expand(md5, 16, secKey, 0, keyLen, labelBytes, seed, output, HMAC_ipad64.clone(), HMAC_opad64.clone()); // P_SHA-1(S2, label + seed) // If we have a long secret, digest it first. if (seclen > 64) { // 64: block size of HMAC-SHA1 sha.update(secret, off, seclen); secKey = sha.digest(); keyLen = secKey.length; off = 0; } expand(sha, 20, secKey, off, keyLen, labelBytes, seed, output, HMAC_ipad64.clone(), HMAC_opad64.clone()); return output; } /* * @param digest the MessageDigest to produce the HMAC * @param hmacSize the HMAC size * @param secret the secret * @param secOff the offset into the secret * @param secLen the secret length * @param label the label * @param seed the seed * @param output the output array */ private static void expand(MessageDigest digest, int hmacSize, byte[] secret, int secOff, int secLen, byte[] label, byte[] seed, byte[] output, byte[] pad1, byte[] pad2) throws DigestException { /* * modify the padding used, by XORing the key into our copy of that * padding. That's to avoid doing that for each HMAC computation. */ for (int i = 0; i < secLen; i++) { pad1[i] ^= secret[i + secOff]; pad2[i] ^= secret[i + secOff]; } byte[] tmp = new byte[hmacSize]; byte[] aBytes = null; /* * compute: * * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + * HMAC_hash(secret, A(2) + seed) + * HMAC_hash(secret, A(3) + seed) + ... * A() is defined as: * * A(0) = seed * A(i) = HMAC_hash(secret, A(i-1)) */ int remaining = output.length; int ofs = 0; while (remaining > 0) { /* * compute A() ... */ // inner digest digest.update(pad1); if (aBytes == null) { digest.update(label); digest.update(seed); } else { digest.update(aBytes); } digest.digest(tmp, 0, hmacSize); // outer digest digest.update(pad2); digest.update(tmp); if (aBytes == null) { aBytes = new byte[hmacSize]; } digest.digest(aBytes, 0, hmacSize); /* * compute HMAC_hash() ... */ // inner digest digest.update(pad1); digest.update(aBytes); digest.update(label); digest.update(seed); digest.digest(tmp, 0, hmacSize); // outer digest digest.update(pad2); digest.update(tmp); digest.digest(tmp, 0, hmacSize); int k = Math.min(hmacSize, remaining); for (int i = 0; i < k; i++) { output[ofs++] ^= tmp[i]; } remaining -= k; } } /** * A KeyGenerator implementation that supports TLS 1.2. * <p> * TLS 1.2 uses a different hash algorithm than 1.0/1.1 for the PRF * calculations. As of 2010, there is no PKCS11-level support for TLS * 1.2 PRF calculations, and no known OS's have an internal variant * we could use. Therefore for TLS 1.2, we are updating JSSE to request * a different provider algorithm: "SunTls12Prf". If we reused the * name "SunTlsPrf", the PKCS11 provider would need be updated to * fail correctly when presented with the wrong version number * (via Provider.Service.supportsParameters()), and add the * appropriate supportsParamters() checks into KeyGenerators (not * currently there). */ static public class V12 extends TlsPrfGenerator { protected SecretKey engineGenerateKey() { return engineGenerateKey0(true); } } /** * A KeyGenerator implementation that supports TLS 1.0/1.1. */ static public class V10 extends TlsPrfGenerator { protected SecretKey engineGenerateKey() { return engineGenerateKey0(false); } } }
gpl-2.0
FauxFaux/jdk9-jdk
test/javax/management/loading/SystemClassLoaderTest.java
2872
/* * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4839389 * @summary Test that a class can load MBeans from its class loader * (at least if it is the system class loader) * @author Eamonn McManus * @modules java.management * @run clean SystemClassLoaderTest * @run build SystemClassLoaderTest * @run main SystemClassLoaderTest */ import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; /* Test that we can load an MBean using createMBean(className, objectName) even if the class of the MBean is not known to the JMX class loader. */ public class SystemClassLoaderTest { public static void main(String[] args) throws Exception { // Instantiate the MBean server // System.out.println("Create the MBean server"); MBeanServer mbs = MBeanServerFactory.createMBeanServer(); ClassLoader mbsClassLoader = mbs.getClass().getClassLoader(); String testClassName = Test.class.getName(); // Check that the MBeanServer class loader does not know our test class try { Class.forName(testClassName, true, mbsClassLoader); System.out.println("TEST IS INVALID: MBEANSERVER'S CLASS LOADER " + "KNOWS OUR TEST CLASS"); System.exit(1); } catch (ClassNotFoundException e) { // As required } // Register the MBean // System.out.println("Create MBean from this class"); ObjectName objectName = new ObjectName("whatever:type=whatever"); mbs.createMBean(testClassName, objectName); // Test OK! // System.out.println("Bye! Bye!"); } public static class Test implements TestMBean { public Test() {} } public static interface TestMBean {} }
gpl-2.0
chadouming/android_packages_apps_SnapdragonCamera
src/com/android/camera/util/AccessibilityUtils.java
1576
package com.android.camera.util; import android.content.Context; import android.support.v4.view.accessibility.AccessibilityRecordCompat; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; /** * AccessibilityUtils provides functions needed in accessibility mode. All the functions * in this class are made compatible with gingerbread and later API's */ public class AccessibilityUtils { public static void makeAnnouncement(View view, CharSequence announcement) { if (view == null) return; if (ApiHelper.HAS_ANNOUNCE_FOR_ACCESSIBILITY) { view.announceForAccessibility(announcement); } else { // For API 15 and earlier, we need to construct an accessibility event Context ctx = view.getContext(); AccessibilityManager am = (AccessibilityManager) ctx.getSystemService( Context.ACCESSIBILITY_SERVICE); if (!am.isEnabled()) return; AccessibilityEvent event = AccessibilityEvent.obtain( AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED); AccessibilityRecordCompat arc = new AccessibilityRecordCompat(event); arc.setSource(view); event.setClassName(view.getClass().getName()); event.setPackageName(view.getContext().getPackageName()); event.setEnabled(view.isEnabled()); event.getText().add(announcement); am.sendAccessibilityEvent(event); } } }
gpl-2.0
martingwhite/astor
examples/math_32/src/main/java/org/apache/commons/math3/ode/nonstiff/EmbeddedRungeKuttaIntegrator.java
13580
/* * 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.commons.math3.ode.nonstiff; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.ode.ExpandableStatefulODE; import org.apache.commons.math3.util.FastMath; /** * This class implements the common part of all embedded Runge-Kutta * integrators for Ordinary Differential Equations. * * <p>These methods are embedded explicit Runge-Kutta methods with two * sets of coefficients allowing to estimate the error, their Butcher * arrays are as follows : * <pre> * 0 | * c2 | a21 * c3 | a31 a32 * ... | ... * cs | as1 as2 ... ass-1 * |-------------------------- * | b1 b2 ... bs-1 bs * | b'1 b'2 ... b's-1 b's * </pre> * </p> * * <p>In fact, we rather use the array defined by ej = bj - b'j to * compute directly the error rather than computing two estimates and * then comparing them.</p> * * <p>Some methods are qualified as <i>fsal</i> (first same as last) * methods. This means the last evaluation of the derivatives in one * step is the same as the first in the next step. Then, this * evaluation can be reused from one step to the next one and the cost * of such a method is really s-1 evaluations despite the method still * has s stages. This behaviour is true only for successful steps, if * the step is rejected after the error estimation phase, no * evaluation is saved. For an <i>fsal</i> method, we have cs = 1 and * asi = bi for all i.</p> * * @version $Id$ * @since 1.2 */ public abstract class EmbeddedRungeKuttaIntegrator extends AdaptiveStepsizeIntegrator { /** Indicator for <i>fsal</i> methods. */ private final boolean fsal; /** Time steps from Butcher array (without the first zero). */ private final double[] c; /** Internal weights from Butcher array (without the first empty row). */ private final double[][] a; /** External weights for the high order method from Butcher array. */ private final double[] b; /** Prototype of the step interpolator. */ private final RungeKuttaStepInterpolator prototype; /** Stepsize control exponent. */ private final double exp; /** Safety factor for stepsize control. */ private double safety; /** Minimal reduction factor for stepsize control. */ private double minReduction; /** Maximal growth factor for stepsize control. */ private double maxGrowth; /** Build a Runge-Kutta integrator with the given Butcher array. * @param name name of the method * @param fsal indicate that the method is an <i>fsal</i> * @param c time steps from Butcher array (without the first zero) * @param a internal weights from Butcher array (without the first empty row) * @param b propagation weights for the high order method from Butcher array * @param prototype prototype of the step interpolator to use * @param minStep minimal step (sign is irrelevant, regardless of * integration direction, forward or backward), the last step can * be smaller than this * @param maxStep maximal step (sign is irrelevant, regardless of * integration direction, forward or backward), the last step can * be smaller than this * @param scalAbsoluteTolerance allowed absolute error * @param scalRelativeTolerance allowed relative error */ protected EmbeddedRungeKuttaIntegrator(final String name, final boolean fsal, final double[] c, final double[][] a, final double[] b, final RungeKuttaStepInterpolator prototype, final double minStep, final double maxStep, final double scalAbsoluteTolerance, final double scalRelativeTolerance) { super(name, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance); this.fsal = fsal; this.c = c; this.a = a; this.b = b; this.prototype = prototype; exp = -1.0 / getOrder(); // set the default values of the algorithm control parameters setSafety(0.9); setMinReduction(0.2); setMaxGrowth(10.0); } /** Build a Runge-Kutta integrator with the given Butcher array. * @param name name of the method * @param fsal indicate that the method is an <i>fsal</i> * @param c time steps from Butcher array (without the first zero) * @param a internal weights from Butcher array (without the first empty row) * @param b propagation weights for the high order method from Butcher array * @param prototype prototype of the step interpolator to use * @param minStep minimal step (must be positive even for backward * integration), the last step can be smaller than this * @param maxStep maximal step (must be positive even for backward * integration) * @param vecAbsoluteTolerance allowed absolute error * @param vecRelativeTolerance allowed relative error */ protected EmbeddedRungeKuttaIntegrator(final String name, final boolean fsal, final double[] c, final double[][] a, final double[] b, final RungeKuttaStepInterpolator prototype, final double minStep, final double maxStep, final double[] vecAbsoluteTolerance, final double[] vecRelativeTolerance) { super(name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance); this.fsal = fsal; this.c = c; this.a = a; this.b = b; this.prototype = prototype; exp = -1.0 / getOrder(); // set the default values of the algorithm control parameters setSafety(0.9); setMinReduction(0.2); setMaxGrowth(10.0); } /** Get the order of the method. * @return order of the method */ public abstract int getOrder(); /** Get the safety factor for stepsize control. * @return safety factor */ public double getSafety() { return safety; } /** Set the safety factor for stepsize control. * @param safety safety factor */ public void setSafety(final double safety) { this.safety = safety; } /** {@inheritDoc} */ @Override public void integrate(final ExpandableStatefulODE equations, final double t) throws MathIllegalStateException, MathIllegalArgumentException { sanityChecks(equations, t); setEquations(equations); final boolean forward = t > equations.getTime(); // create some internal working arrays final double[] y0 = equations.getCompleteState(); final double[] y = y0.clone(); final int stages = c.length + 1; final double[][] yDotK = new double[stages][y.length]; final double[] yTmp = y0.clone(); final double[] yDotTmp = new double[y.length]; // set up an interpolator sharing the integrator arrays final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy(); interpolator.reinitialize(this, yTmp, yDotK, forward, equations.getPrimaryMapper(), equations.getSecondaryMappers()); interpolator.storeTime(equations.getTime()); // set up integration control objects stepStart = equations.getTime(); double hNew = 0; boolean firstTime = true; initIntegration(equations.getTime(), y0, t); // main integration loop isLastStep = false; do { interpolator.shift(); // iterate over step size, ensuring local normalized error is smaller than 1 double error = 10; while (error >= 1.0) { if (firstTime || !fsal) { // first stage computeDerivatives(stepStart, y, yDotK[0]); } if (firstTime) { final double[] scale = new double[mainSetDimension]; if (vecAbsoluteTolerance == null) { for (int i = 0; i < scale.length; ++i) { scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]); } } else { for (int i = 0; i < scale.length; ++i) { scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]); } } hNew = initializeStep(forward, getOrder(), scale, stepStart, y, yDotK[0], yTmp, yDotK[1]); firstTime = false; } stepSize = hNew; if (forward) { if (stepStart + stepSize >= t) { stepSize = t - stepStart; } } else { if (stepStart + stepSize <= t) { stepSize = t - stepStart; } } // next stages for (int k = 1; k < stages; ++k) { for (int j = 0; j < y0.length; ++j) { double sum = a[k-1][0] * yDotK[0][j]; for (int l = 1; l < k; ++l) { sum += a[k-1][l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]); } // estimate the state at the end of the step for (int j = 0; j < y0.length; ++j) { double sum = b[0] * yDotK[0][j]; for (int l = 1; l < stages; ++l) { sum += b[l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } // estimate the error at the end of the step error = estimateError(yDotK, y, yTmp, stepSize); if (error >= 1.0) { // reject the step and attempt to reduce error by stepsize control final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp))); hNew = filterStep(stepSize * factor, forward, false); } } // local error is small enough: accept the step, trigger events and step handlers interpolator.storeTime(stepStart + stepSize); System.arraycopy(yTmp, 0, y, 0, y0.length); System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length); stepStart = acceptStep(interpolator, y, yDotTmp, t); System.arraycopy(y, 0, yTmp, 0, y.length); if (!isLastStep) { // prepare next step interpolator.storeTime(stepStart); if (fsal) { // save the last evaluation for the next step System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length); } // stepsize control for next step final double factor = FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp))); final double scaledH = stepSize * factor; final double nextT = stepStart + scaledH; final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t); hNew = filterStep(scaledH, forward, nextIsLast); final double filteredNextT = stepStart + hNew; final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t); if (filteredNextIsLast) { hNew = t - stepStart; } } } while (!isLastStep); // dispatch results equations.setTime(stepStart); equations.setCompleteState(y); resetInternalState(); } /** Get the minimal reduction factor for stepsize control. * @return minimal reduction factor */ public double getMinReduction() { return minReduction; } /** Set the minimal reduction factor for stepsize control. * @param minReduction minimal reduction factor */ public void setMinReduction(final double minReduction) { this.minReduction = minReduction; } /** Get the maximal growth factor for stepsize control. * @return maximal growth factor */ public double getMaxGrowth() { return maxGrowth; } /** Set the maximal growth factor for stepsize control. * @param maxGrowth maximal growth factor */ public void setMaxGrowth(final double maxGrowth) { this.maxGrowth = maxGrowth; } /** Compute the error ratio. * @param yDotK derivatives computed during the first stages * @param y0 estimate of the step at the start of the step * @param y1 estimate of the step at the end of the step * @param h current step * @return error ratio, greater than 1 if step should be rejected */ protected abstract double estimateError(double[][] yDotK, double[] y0, double[] y1, double h); }
gpl-2.0
aebert1/BigTransport
build/tmp/recompileMc/sources/net/minecraft/world/storage/loot/functions/EnchantRandomly.java
4925
package net.minecraft.world.storage.loot.functions; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSyntaxException; import java.util.List; import java.util.Random; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.world.storage.loot.LootContext; import net.minecraft.world.storage.loot.conditions.LootCondition; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class EnchantRandomly extends LootFunction { private static final Logger LOGGER = LogManager.getLogger(); private final List<Enchantment> enchantments; public EnchantRandomly(LootCondition[] conditionsIn, List<Enchantment> enchantmentsIn) { super(conditionsIn); this.enchantments = enchantmentsIn; } public ItemStack apply(ItemStack stack, Random rand, LootContext context) { Enchantment enchantment; if (this.enchantments != null && !this.enchantments.isEmpty()) { enchantment = (Enchantment)this.enchantments.get(rand.nextInt(this.enchantments.size())); } else { List<Enchantment> list = Lists.<Enchantment>newArrayList(); for (Enchantment enchantment1 : Enchantment.enchantmentRegistry) { if (stack.getItem() == Items.book || enchantment1.canApply(stack)) { list.add(enchantment1); } } if (list.isEmpty()) { LOGGER.warn("Couldn\'t find a compatible enchantment for " + stack); return stack; } enchantment = (Enchantment)list.get(rand.nextInt(list.size())); } int i = MathHelper.getRandomIntegerInRange(rand, enchantment.getMinLevel(), enchantment.getMaxLevel()); if (stack.getItem() == Items.book) { stack.setItem(Items.enchanted_book); Items.enchanted_book.addEnchantment(stack, new EnchantmentData(enchantment, i)); } else { stack.addEnchantment(enchantment, i); } return stack; } public static class Serializer extends LootFunction.Serializer<EnchantRandomly> { public Serializer() { super(new ResourceLocation("enchant_randomly"), EnchantRandomly.class); } public void serialize(JsonObject object, EnchantRandomly functionClazz, JsonSerializationContext serializationContext) { if (functionClazz.enchantments != null && !functionClazz.enchantments.isEmpty()) { JsonArray jsonarray = new JsonArray(); for (Enchantment enchantment : functionClazz.enchantments) { ResourceLocation resourcelocation = (ResourceLocation)Enchantment.enchantmentRegistry.getNameForObject(enchantment); if (resourcelocation == null) { throw new IllegalArgumentException("Don\'t know how to serialize enchantment " + enchantment); } jsonarray.add(new JsonPrimitive(resourcelocation.toString())); } object.add("enchantments", jsonarray); } } public EnchantRandomly deserialize(JsonObject object, JsonDeserializationContext deserializationContext, LootCondition[] conditionsIn) { List<Enchantment> list = null; if (object.has("enchantments")) { list = Lists.<Enchantment>newArrayList(); for (JsonElement jsonelement : JsonUtils.getJsonArray(object, "enchantments")) { String s = JsonUtils.getString(jsonelement, "enchantment"); Enchantment enchantment = (Enchantment)Enchantment.enchantmentRegistry.getObject(new ResourceLocation(s)); if (enchantment == null) { throw new JsonSyntaxException("Unknown enchantment \'" + s + "\'"); } list.add(enchantment); } } return new EnchantRandomly(conditionsIn, list); } } }
gpl-3.0
AICP/packages_apps_OmniSwitch
src/org/omnirom/omniswitch/PackageManager.java
9615
/* * Copyright (C) 2014-2016 The OmniROM Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.omnirom.omniswitch; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.omnirom.omniswitch.ui.BitmapCache; import org.omnirom.omniswitch.ui.BitmapUtils; import org.omnirom.omniswitch.ui.IconPackHelper; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.graphics.drawable.BitmapDrawable; import android.preference.PreferenceManager; import android.util.Log; public class PackageManager { private static final boolean DEBUG = false; private static final String TAG = "PackageManager"; private Map<String, PackageItem> mInstalledPackages; private List<PackageItem> mInstalledPackagesList; private Context mContext; private boolean mInitDone; private static PackageManager sInstance; public static final String PACKAGES_UPDATED_TAG = "PACKAGES_UPDATED"; public static class PackageItem implements Comparable<PackageItem> { private CharSequence title; private String packageName; private Intent intent; private ActivityInfo activity; public Intent getIntentRaw() { return intent; } public String getIntent() { return intent.toUri(0); } public CharSequence getTitle() { return title; } public ActivityInfo getActivityInfo() { return activity; } @Override public int compareTo(PackageItem another) { int result = title.toString().compareToIgnoreCase( another.title.toString()); return result != 0 ? result : packageName .compareTo(another.packageName); } @Override public String toString() { return getTitle().toString(); } } public static PackageManager getInstance(Context context) { if (sInstance == null){ sInstance = new PackageManager(); } sInstance.setContext(context); return sInstance; } private PackageManager() { mInstalledPackages = new HashMap<String, PackageItem>(); mInstalledPackagesList = new ArrayList<PackageItem>(); } private void setContext(Context context) { mContext = context; } public synchronized List<PackageItem> getPackageList() { if(!mInitDone){ updatePackageList(); } return mInstalledPackagesList; } public synchronized Map<String, PackageItem> getPackageMap() { if(!mInitDone){ updatePackageList(); } return mInstalledPackages; } public synchronized void clearPackageList() { mInstalledPackages.clear(); mInstalledPackagesList.clear(); mInitDone = false; } public Drawable getPackageIcon(PackageItem item) { final android.content.pm.PackageManager pm = mContext.getPackageManager(); Drawable icon = null; if (IconPackHelper.getInstance(mContext).isIconPackLoaded()){ int iconId = IconPackHelper.getInstance(mContext).getResourceIdForActivityIcon(item.activity); if (iconId != 0) { icon = IconPackHelper.getInstance(mContext).getIconPackResources().getDrawable(iconId); } } if (icon == null || !IconPackHelper.getInstance(mContext).isIconPackLoaded()){ try { icon = pm.getActivityIcon(item.intent); } catch (NameNotFoundException e) { } } if (icon == null) { icon = BitmapUtils.getDefaultActivityIcon(mContext); } return icon; } public synchronized void reloadPackageList() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean old = prefs.getBoolean(PackageManager.PACKAGES_UPDATED_TAG, false); updatePackageList(); prefs.edit().putBoolean(PackageManager.PACKAGES_UPDATED_TAG, !old).commit(); } public synchronized void updatePackageList() { if (DEBUG) Log.d(TAG, "updatePackageList"); final android.content.pm.PackageManager pm = mContext.getPackageManager(); mInstalledPackages.clear(); mInstalledPackagesList.clear(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> installedAppsInfo = pm.queryIntentActivities( mainIntent, 0); for (ResolveInfo info : installedAppsInfo) { ApplicationInfo appInfo = info.activityInfo.applicationInfo; final PackageItem item = new PackageItem(); item.packageName = appInfo.packageName; ActivityInfo activity = info.activityInfo; item.activity = activity; ComponentName name = new ComponentName( activity.applicationInfo.packageName, activity.name); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.setComponent(name); item.intent = intent; item.title = Utils.getActivityLabel(pm, intent); if (item.title == null) { item.title = appInfo.loadLabel(pm); } mInstalledPackages.put(item.getIntent(), item); mInstalledPackagesList.add(item); } updateFavorites(); Collections.sort(mInstalledPackagesList); mInitDone = true; } public synchronized void updatePackageIcons() { BitmapCache.getInstance(mContext).clear(); } public synchronized CharSequence getTitle(String intent) { return getPackageMap().get(intent).getTitle(); } public synchronized PackageItem getPackageItem(String intent) { return getPackageMap().get(intent); } public synchronized PackageItem getPackageItemByComponent(Intent intent) { String pkgName = intent.getComponent().getPackageName(); Iterator<PackageItem> nextPackage = mInstalledPackagesList.iterator(); while(nextPackage.hasNext()){ PackageItem item = nextPackage.next(); ComponentName name = item.getIntentRaw().getComponent(); String pPkgName = name.getPackageName(); if (pkgName.equals(pPkgName)){ return item; } } return null; } public synchronized List<String> getPackageListForPackageName(String pkgName) { List<String> pkgList = new ArrayList<String>(); Iterator<PackageItem> nextPackage = mInstalledPackagesList.iterator(); while(nextPackage.hasNext()){ PackageItem item = nextPackage.next(); ComponentName name = item.getIntentRaw().getComponent(); String pPkgName = name.getPackageName(); if (pkgName.equals(pPkgName)){ pkgList.add(item.getIntent()); } } return pkgList; } public synchronized boolean contains(String intent) { return getPackageMap().containsKey(intent); } public void removePackageIconCache(String packageName) { BitmapCache.getInstance(mContext).removeBitmapToMemoryCache(packageName); } private synchronized void updateFavorites() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String favoriteListString = prefs.getString(SettingsActivity.PREF_FAVORITE_APPS, ""); List<String> favoriteList = new ArrayList<String>(); Utils.parseFavorites(favoriteListString, favoriteList); boolean changed = false; List<String> newFavoriteList = new ArrayList<String>(); Iterator<String> nextFavorite = favoriteList.iterator(); while (nextFavorite.hasNext()) { String favorite = nextFavorite.next(); // DONT USE getPackageMap() here! if (!mInstalledPackages.containsKey(favorite)){ changed = true; continue; } newFavoriteList.add(favorite); } if (changed) { prefs.edit() .putString(SettingsActivity.PREF_FAVORITE_APPS, Utils.flattenFavorites(newFavoriteList)) .commit(); } } }
gpl-3.0
aebert1/BigTransport
build/tmp/recompileMc/sources/net/minecraft/item/ItemElytra.java
2274
package net.minecraft.item; import net.minecraft.block.BlockDispenser; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemElytra extends Item { public ItemElytra() { this.maxStackSize = 1; this.setMaxDamage(432); this.setCreativeTab(CreativeTabs.tabTransport); this.addPropertyOverride(new ResourceLocation("broken"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) public float apply(ItemStack stack, World worldIn, EntityLivingBase entityIn) { return ItemElytra.isBroken(stack) ? 0.0F : 1.0F; } }); BlockDispenser.dispenseBehaviorRegistry.putObject(this, ItemArmor.dispenserBehavior); } public static boolean isBroken(ItemStack stack) { return stack.getItemDamage() < stack.getMaxDamage() - 1; } /** * Return whether this item is repairable in an anvil. */ public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) { return repair.getItem() == Items.leather; } public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { EntityEquipmentSlot entityequipmentslot = EntityLiving.getSlotForItemStack(itemStackIn); ItemStack itemstack = playerIn.getItemStackFromSlot(entityequipmentslot); if (itemstack == null) { playerIn.setItemStackToSlot(entityequipmentslot, itemStackIn.copy()); itemStackIn.stackSize = 0; return new ActionResult(EnumActionResult.SUCCESS, itemStackIn); } else { return new ActionResult(EnumActionResult.FAIL, itemStackIn); } } }
gpl-3.0
srnsw/xena
plugins/project/ext/src/poi-3.2-FINAL/src/java/org/apache/poi/hssf/record/formula/functions/Choose.java
935
/* * 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. */ /* * Created on May 15, 2005 * */ package org.apache.poi.hssf.record.formula.functions; public class Choose extends NotImplementedFunction { }
gpl-3.0
ssoloff/triplea-game-triplea
game-core/src/main/java/games/strategy/engine/data/ProductionRuleList.java
935
package games.strategy.engine.data; import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** A collection of {@link ProductionRule}s keyed on the production rule name. */ public class ProductionRuleList extends GameDataComponent { private static final long serialVersionUID = -5313215563006788188L; private final Map<String, ProductionRule> productionRules = new HashMap<>(); public ProductionRuleList(final GameData data) { super(data); } @VisibleForTesting public void addProductionRule(final ProductionRule pf) { productionRules.put(pf.getName(), pf); } public int size() { return productionRules.size(); } public ProductionRule getProductionRule(final String name) { return productionRules.get(name); } public Collection<ProductionRule> getProductionRules() { return productionRules.values(); } }
gpl-3.0
oswin06082/SwgAnh1.0a
documents/SWGCombined/src/FactoryCrate.java
1799
import java.util.TreeSet; public class FactoryCrate extends TangibleItem{ public final static long serialVersionUID = 1l; private TreeSet<SOEObject> vObjectsInCrate; private byte iCrateCapacity = 25; // Variable, depending on the type of object being manufactured. TODO: Find info on. private byte iNumObjectsInCrate = 0; public FactoryCrate() { super(); vObjectsInCrate = new TreeSet<SOEObject>(); } /** * Returns and removes the first (least) object in the crate, or null if the crate is empty. * @return */ public SOEObject getObjectFromCrate() { return vObjectsInCrate.pollFirst(); } /** * Adds the given SOEObject to the factory crate. Sets the serial number to be the same as any objects already in the crate (game prerequisite) * @param o -- The object to be added to the crate * @return True, if the object was in fact added. Otherwise returns false. */ public boolean addToCrate(TangibleItem o) { if (iNumObjectsInCrate < iCrateCapacity) { if (!vObjectsInCrate.isEmpty()) { SOEObject baseObjectInCrate = vObjectsInCrate.first(); o.setSerialNumber(baseObjectInCrate.getSerialNumber(), true); } vObjectsInCrate.add(o); iNumObjectsInCrate ++; return true; } return false; } /** * Factory crates are not, in fact, experimentable. */ public void experiment() { return; } public byte getQuantity() { return iNumObjectsInCrate; } public long getSerialNumber() { if (!vObjectsInCrate.isEmpty()) { return vObjectsInCrate.first().getSerialNumber(); } return 0; } public String getContainedItemSTFFilename() { if (!vObjectsInCrate.isEmpty()) { return vObjectsInCrate.first().getSTFFileName(); } return null; } public boolean isEmpty() { return vObjectsInCrate.isEmpty(); } }
gpl-3.0
gubatron/frostwire-android
src/com/frostwire/frostclick/TorrentPromotionSearchResult.java
2596
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2015, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frostwire.frostclick; import com.frostwire.licences.License; import com.frostwire.search.torrent.TorrentSearchResult; import org.apache.commons.io.FilenameUtils; /** * @author gubatron * @author aldenml * */ public class TorrentPromotionSearchResult implements TorrentSearchResult { private static final String FROSTCLICK_VENDOR = "FrostClick"; private int uid = -1; private final Slide slide; private final long creationTime; public TorrentPromotionSearchResult(Slide slide) { this.slide = slide; this.creationTime = System.currentTimeMillis(); } public String getDisplayName() { return slide.title; } @Override public long getSize() { return slide.size; } @Override public String getFilename() { return FilenameUtils.getName(slide.url); } @Override public long getCreationTime() { return creationTime; } @Override public String getHash() { return null; } @Override public String getDetailsUrl() { return slide.url; } @Override public String getTorrentUrl() { return slide.torrent; } @Override public String getReferrerUrl() { return slide.url; } @Override public String getSource() { return FROSTCLICK_VENDOR; } @Override public int getSeeds() { return -1; } @Override public License getLicense() { return License.UNKNOWN; } @Override public String getThumbnailUrl() { return null; } @Override public int uid() { if (uid == -1) { String key = getDisplayName() + getDetailsUrl() + getSource() + getHash(); uid = key.hashCode(); } return uid; } }
gpl-3.0
HossainKhademian/Studio3
tests/org.eclipse.test.performance/src/org/eclipse/test/internal/performance/tests/AllTests.java
1020
/******************************************************************************* * Copyright (c) 2004, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.test.internal.performance.tests; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite= new TestSuite("Performance Test plugin tests"); //$NON-NLS-1$ //suite.addTestSuite(SimplePerformanceMeterTest.class); suite.addTestSuite(VariationsTests.class); suite.addTestSuite(DBTests.class); suite.addTestSuite(PerformanceMeterFactoryTest.class); return suite; } }
gpl-3.0
neophob/PixelController
pixelcontroller-core/src/test/java/com/neophob/sematrix/core/glue/FileUtilsTest.java
1762
/** * Copyright (C) 2011-2013 Michael Vogt <michu@neophob.com> * * This file is part of PixelController. * * PixelController 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 * (at your option) any later version. * * PixelController 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 PixelController. If not, see <http://www.gnu.org/licenses/>. */ package com.neophob.sematrix.core.glue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import com.neophob.sematrix.core.glue.FileUtils; import com.neophob.sematrix.core.glue.PresetSettings; /** * test internal buffer size * * @author michu * */ public class FileUtilsTest { @Test public void findFilesTest() throws Exception { FileUtils fu = new FileUtilsJunit(); String[] bmlFiles = fu.findBlinkenFiles(); assertNotNull(bmlFiles); assertTrue(bmlFiles.length>2); String[] imgFiles = fu.findImagesFiles(); assertNotNull(imgFiles); assertTrue(imgFiles.length>2); assertFalse(fu.getRootDirectory().isEmpty()); List<PresetSettings> presets = fu.loadPresents(128); assertNotNull(presets); assertTrue(presets.size()>2); fu.savePresents(presets); } }
gpl-3.0
openelisglobal/openelisglobal-core
app/src/us/mn/state/health/lims/common/servlet/autocomplete/AjaxXMLServlet.java
2055
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. */ package us.mn.state.health.lims.common.servlet.autocomplete; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ajaxtags.helpers.AjaxXmlBuilder; import org.ajaxtags.servlets.BaseAjaxServlet; import us.mn.state.health.lims.common.provider.autocomplete.AutocompleteProviderFactory; import us.mn.state.health.lims.common.provider.autocomplete.BaseAutocompleteProvider; import us.mn.state.health.lims.login.dao.UserModuleDAO; import us.mn.state.health.lims.login.daoimpl.UserModuleDAOImpl; public class AjaxXMLServlet extends BaseAjaxServlet { public String getXmlContent(HttpServletRequest request, HttpServletResponse response) throws Exception { //check for authentication UserModuleDAO userModuleDAO = new UserModuleDAOImpl(); if (userModuleDAO.isSessionExpired(request)) { return new AjaxXmlBuilder().toString(); } String autocompleteProvider = request.getParameter("provider"); String autocompleteFieldName = request.getParameter("fieldName"); String autocompleteId = request.getParameter("idName"); BaseAutocompleteProvider provider = (BaseAutocompleteProvider) AutocompleteProviderFactory .getInstance().getAutocompleteProvider(autocompleteProvider); provider.setServlet(this); List list = provider.processRequest(request, response); return new AjaxXmlBuilder().addItems(list, autocompleteFieldName, autocompleteId).toString(); } }
mpl-2.0
roselleebarle04/AIDR
aidr-db-manager/src/main/java/qa/qcri/aidr/dbmanager/dto/NominalLabelEvaluationDataDTO.java
1534
package qa.qcri.aidr.dbmanager.dto; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import qa.qcri.aidr.common.exception.PropertyNotSetException; import qa.qcri.aidr.dbmanager.entities.model.NominalLabelEvaluationData; import qa.qcri.aidr.dbmanager.entities.model.NominalLabelEvaluationDataId; @XmlRootElement @JsonIgnoreProperties(ignoreUnknown=true) public class NominalLabelEvaluationDataDTO implements Serializable { /** * */ private static final long serialVersionUID = 8978010233097606501L; @XmlElement private NominalLabelEvaluationDataIdDTO idDTO; public NominalLabelEvaluationDataDTO() { } public NominalLabelEvaluationDataDTO(NominalLabelEvaluationDataIdDTO idDTO) { this.idDTO = idDTO; } public NominalLabelEvaluationDataDTO(NominalLabelEvaluationDataId id) throws PropertyNotSetException { this.setIdDTO(new NominalLabelEvaluationDataIdDTO(id)); } public NominalLabelEvaluationDataDTO(NominalLabelEvaluationData data) throws PropertyNotSetException { this.setIdDTO(new NominalLabelEvaluationDataIdDTO(data.getId())); } public NominalLabelEvaluationDataIdDTO getIdDTO() { return this.idDTO; } public void setIdDTO(NominalLabelEvaluationDataIdDTO idDTO) { this.idDTO = idDTO; } public NominalLabelEvaluationData toEntity() { NominalLabelEvaluationData entity = new NominalLabelEvaluationData(idDTO.toEntity()); return entity; } }
agpl-3.0
aihua/opennms
opennms-dao/src/test/java/org/opennms/netmgt/dao/support/ResourceTreeWalkerTest.java
6171
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao.support; import static org.easymock.EasyMock.expect; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import junit.framework.TestCase; import org.opennms.netmgt.dao.api.ResourceDao; import org.opennms.netmgt.mock.MockResourceType; import org.opennms.netmgt.model.OnmsAttribute; import org.opennms.netmgt.model.OnmsResource; import org.opennms.netmgt.model.ResourcePath; import org.opennms.netmgt.model.ResourceVisitor; import org.opennms.test.ThrowableAnticipator; import org.opennms.test.mock.EasyMockUtils; /** * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> */ public class ResourceTreeWalkerTest extends TestCase { private EasyMockUtils m_mocks = new EasyMockUtils(); private ResourceDao m_resourceDao = m_mocks.createMock(ResourceDao.class); private ResourceVisitor m_visitor = m_mocks.createMock(ResourceVisitor.class); @Override public void setUp() throws Exception { super.setUp(); } public void testAfterPropertiesSet() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(m_resourceDao); walker.setVisitor(m_visitor); m_mocks.replayAll(); walker.afterPropertiesSet(); m_mocks.verifyAll(); } public void testAfterPropertiesSetNoResourceDao() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(null); walker.setVisitor(m_visitor); ThrowableAnticipator ta = new ThrowableAnticipator(); ta.anticipate(new IllegalStateException("property resourceDao must be set to a non-null value")); m_mocks.replayAll(); try { walker.afterPropertiesSet(); } catch (Throwable t) { ta.throwableReceived(t); } ta.verifyAnticipated(); m_mocks.verifyAll(); } public void testAfterPropertiesSetNoVisitor() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(m_resourceDao); walker.setVisitor(null); ThrowableAnticipator ta = new ThrowableAnticipator(); ta.anticipate(new IllegalStateException("property visitor must be set to a non-null value")); m_mocks.replayAll(); try { walker.afterPropertiesSet(); } catch (Throwable t) { ta.throwableReceived(t); } ta.verifyAnticipated(); m_mocks.verifyAll(); } public void testWalkEmptyList() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(m_resourceDao); walker.setVisitor(m_visitor); m_mocks.replayAll(); walker.afterPropertiesSet(); m_mocks.verifyAll(); expect(m_resourceDao.findTopLevelResources()).andReturn(new ArrayList<OnmsResource>(0)); m_mocks.replayAll(); walker.walk(); m_mocks.verifyAll(); } public void testWalkTopLevel() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(m_resourceDao); walker.setVisitor(m_visitor); m_mocks.replayAll(); walker.afterPropertiesSet(); m_mocks.verifyAll(); MockResourceType resourceType = new MockResourceType(); List<OnmsResource> resources = new ArrayList<OnmsResource>(2); resources.add(new OnmsResource("1", "Node One", resourceType, new HashSet<OnmsAttribute>(0), new ResourcePath("foo"))); resources.add(new OnmsResource("2", "Node Two", resourceType, new HashSet<OnmsAttribute>(0), new ResourcePath("foo"))); expect(m_resourceDao.findTopLevelResources()).andReturn(resources); for (OnmsResource resource : resources) { m_visitor.visit(resource); } m_mocks.replayAll(); walker.walk(); m_mocks.verifyAll(); } public void testWalkChildren() { ResourceTreeWalker walker = new ResourceTreeWalker(); walker.setResourceDao(m_resourceDao); walker.setVisitor(m_visitor); m_mocks.replayAll(); walker.afterPropertiesSet(); m_mocks.verifyAll(); MockResourceType resourceType = new MockResourceType(); OnmsResource childResource = new OnmsResource("eth0", "Interface eth0", resourceType, new HashSet<OnmsAttribute>(0), new ResourcePath("foo")); OnmsResource topResource = new OnmsResource("1", "Node One", resourceType, new HashSet<OnmsAttribute>(0), Collections.singletonList(childResource), new ResourcePath("foo")); expect(m_resourceDao.findTopLevelResources()).andReturn(Collections.singletonList(topResource)); m_visitor.visit(topResource); m_visitor.visit(childResource); m_mocks.replayAll(); walker.walk(); m_mocks.verifyAll(); } }
agpl-3.0
roselleebarle04/AIDR
aidr-manager/src/main/java/qa/qcri/aidr/manager/util/ManagerConfigurator.java
1045
package qa.qcri.aidr.manager.util; import org.apache.log4j.Logger; import qa.qcri.aidr.common.code.impl.BaseConfigurator; import qa.qcri.aidr.common.exception.ConfigurationPropertyFileException; import qa.qcri.aidr.common.exception.ConfigurationPropertyNotRecognizedException; import qa.qcri.aidr.common.exception.ConfigurationPropertyNotSetException; public class ManagerConfigurator extends BaseConfigurator { private static final Logger LOGGER = Logger .getLogger(ManagerConfigurator.class); public static final String configLoadFileName = "system.properties"; private static final ManagerConfigurator instance = new ManagerConfigurator(); private ManagerConfigurator() { LOGGER.info("Initializing Properties for aidr-manager."); this.initProperties(configLoadFileName, ManagerConfigurationProperty.values()); } public static ManagerConfigurator getInstance() throws ConfigurationPropertyNotSetException, ConfigurationPropertyNotRecognizedException, ConfigurationPropertyFileException { return instance; } }
agpl-3.0
olivermay/geomajas
backend/impl/src/main/java/org/geomajas/internal/rendering/writer/svg/geometry/MultiPolygonWriter.java
2050
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.internal.rendering.writer.svg.geometry; import org.geomajas.internal.rendering.writer.GraphicsWriter; import org.geomajas.rendering.GraphicsDocument; import org.geomajas.rendering.RenderException; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Polygon; /** * <p> * SVG writer for <code>MultiPolygon</code> objects. * </p> * * @author Pieter De Graef * @author Jan De Moerloose */ public class MultiPolygonWriter implements GraphicsWriter { /** * Writes the body for a <code>MultiPolygon</code> object. MultiPolygons are * encoded into SVG path elements. This function writes the different * polygons in one d-attribute of an SVG path element, separated by an 'M' * character. (in other words, it calls the super.writeBody for each * polygon). * * @param o The <code>MultiPolygon</code> to be encoded. */ public void writeObject(Object o, GraphicsDocument document, boolean asChild) throws RenderException { document.writeElement("path", asChild); document.writeAttribute("fill-rule", "evenodd"); document.writeAttributeStart("d"); MultiPolygon mpoly = (MultiPolygon) o; for (int i = 0; i < mpoly.getNumGeometries(); i++) { Polygon poly = (Polygon) mpoly.getGeometryN(i); LineString shell = poly.getExteriorRing(); int nHoles = poly.getNumInteriorRing(); document.writeClosedPathContent(shell.getCoordinates()); for (int j = 0; j < nHoles; j++) { document.writeClosedPathContent(poly.getInteriorRingN(j).getCoordinates()); } } document.writeAttributeEnd(); } }
agpl-3.0
olivermay/geomajas
plugin/geomajas-plugin-geocoder/geocoder/src/test/java/org/geomajas/plugin/geocoder/service/YahooPlaceFinderGeocoderService2Test.java
2332
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.plugin.geocoder.service; import junit.framework.Assert; import org.geomajas.plugin.geocoder.api.GetLocationResult; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.List; /** * Test for the GeonamesGeocoderService, verifies that setting the appId using a property also works. * The property is set in the pom, in the surefire plugin section. * * @author Joachim Van der Auwera */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/org/geomajas/spring/geomajasContext.xml", "/ypf2Context.xml"}) public class YahooPlaceFinderGeocoderService2Test { @Autowired private YahooPlaceFinderGeocoderService geocoder; @Test public void testGeocoder() { List<String> list = new ArrayList<String>(); GetLocationResult[] result; list.clear(); list.add("booischot"); result = geocoder.getLocation(list, 50, null); Assert.assertNotNull(result); Assert.assertEquals(1,result.length); Assert.assertNotNull(result[0].getCoordinate()); Assert.assertEquals(4.77397, result[0].getCoordinate().x, .00001); Assert.assertEquals(51.05125, result[0].getCoordinate().y, .00001); Assert.assertEquals(2, result[0].getCanonicalStrings().size()); Assert.assertEquals("Belgium", result[0].getCanonicalStrings().get(0)); Assert.assertEquals("2221 Boisschot", result[0].getCanonicalStrings().get(1)); Assert.assertEquals(4.75513, result[0].getEnvelope().getMinX(), .00001); Assert.assertEquals(4.79043, result[0].getEnvelope().getMaxX(), .00001); Assert.assertEquals(51.031898, result[0].getEnvelope().getMinY(), .00001); Assert.assertEquals(51.05677, result[0].getEnvelope().getMaxY(), .00001); } }
agpl-3.0
rhusar/wildfly
messaging-activemq/subsystem/src/main/java/org/wildfly/extension/messaging/activemq/jms/ConnectionFactoryRemove.java
2718
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.messaging.activemq.jms; import static org.wildfly.extension.messaging.activemq.MessagingServices.isSubsystemResource; import org.jboss.as.controller.AbstractRemoveStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.messaging.activemq.MessagingServices; /** * Update handler removing a connection factory from the Jakarta Messaging subsystem. The * runtime action will remove the corresponding {@link ConnectionFactoryService}. * * @author Emanuel Muckenhuber * @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a> */ public class ConnectionFactoryRemove extends AbstractRemoveStepHandler { public static final ConnectionFactoryRemove INSTANCE = new ConnectionFactoryRemove(); @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { ServiceName serviceName; if(isSubsystemResource(context)) { serviceName = MessagingServices.getActiveMQServiceName(); } else { serviceName = MessagingServices.getActiveMQServiceName(context.getCurrentAddress()); } context.removeService(JMSServices.getConnectionFactoryBaseServiceName(serviceName).append(context.getCurrentAddressValue())); } @Override protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { ConnectionFactoryAdd.INSTANCE.performRuntime(context, operation, model); } }
lgpl-2.1
HomescuLiviu/OmegaDeveloper-shopizer
sm-search/src/main/java/com/shopizer/search/services/worker/ObjectIndexerImpl.java
3529
package com.shopizer.search.services.worker; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import com.shopizer.search.services.impl.SearchDelegate; import com.shopizer.search.utils.FileUtil; import com.shopizer.search.utils.IndexConfiguration; import com.shopizer.search.utils.SearchClient; public class ObjectIndexerImpl implements IndexWorker { private static boolean init = false; @Inject private SearchDelegate searchDelegate; private List<IndexConfiguration> indexConfigurations; public List<IndexConfiguration> getIndexConfigurations() { return indexConfigurations; } public void setIndexConfigurations(List<IndexConfiguration> indexConfigurations) { this.indexConfigurations = indexConfigurations; } private static Logger log = Logger.getLogger(ObjectIndexerImpl.class); public synchronized void init(SearchClient client) { //get the list of configuration //get the collection name and index name //get the mapping file if(init) { return; } init = true; if(getIndexConfigurations()!=null && getIndexConfigurations().size()>0) { for(Object o : indexConfigurations) { IndexConfiguration config = (IndexConfiguration)o; String mappingFile = null; String settingsFile = null; if(!StringUtils.isBlank(config.getMappingFileName())) { mappingFile = config.getMappingFileName(); } if(!StringUtils.isBlank(config.getSettingsFileName())) { settingsFile = config.getSettingsFileName(); } if(mappingFile!=null || settingsFile!=null) { String metadata = null; String settingsdata = null; try { if(mappingFile!=null) { metadata = FileUtil.readFileAsString(mappingFile); } if(settingsFile!=null) { settingsdata = FileUtil.readFileAsString(settingsFile); } if(!StringUtils.isBlank(config.getIndexName())) { if(!searchDelegate.indexExist(config.getCollectionName())) { searchDelegate.createIndice(metadata, settingsdata, config.getCollectionName(), config.getIndexName()); } } } catch (Exception e) { log.error(e); log.error("*********************************************"); log.error(e); log.error("*********************************************"); init=false; } } } } } @SuppressWarnings({ "unchecked", "unused" }) public void execute(SearchClient client, String json, String collection, String object, String id, ExecutionContext context) throws Exception { try { if(!init) { init(client); } //get json object Map<String,Object> indexData = (Map<String,Object>)context.getObject("indexData"); if(indexData==null) { ObjectMapper mapper = new ObjectMapper(); indexData = mapper.readValue(json, Map.class); } if(context==null) { context = new ExecutionContext(); } context.setObject("indexData", indexData); com.shopizer.search.services.GetResponse r = searchDelegate.getObject(collection, object, id); if(r!=null) { searchDelegate.delete(collection, object, id); } searchDelegate.index(json, collection, object, id); } catch (Exception e) { log.error("Exception while indexing a product, maybe a timing ussue for no shards available",e); } } }
lgpl-2.1
raedle/univis
lib/jfreechart-1.0.1/src/org/jfree/chart/labels/PieSectionLabelGenerator.java
4457
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * PieSectionLabelGenerator.java * ----------------------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PieSectionLabelGenerator.java,v 1.3.2.2 2005/10/25 20:49:02 mungady Exp $ * * Changes * ------- * 13-Dec-2001 : Version 1 (DG); * 16-Jan-2002 : Completed Javadocs (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 30-Oct-2002 : Category is now a Comparable instance (DG); * 07-Mar-2003 : Changed to KeyedValuesDataset and added pieIndex * parameter (DG); * 21-Mar-2003 : Updated Javadocs (DG); * 24-Apr-2003 : Switched around PieDataset and KeyedValuesDataset (DG); * 13-Aug-2003 : Added clone() method (DG); * 19-Aug-2003 : Renamed PieToolTipGenerator --> PieItemLabelGenerator (DG); * 11-Nov-2003 : Removed clone() method (DG); * 30-Jan-2004 : Added generateSectionLabel() method (DG); * 15-Apr-2004 : Moved generateToolTip() method into separate interface and * renamed this interface PieSectionLabelGenerator (DG); * */ package org.jfree.chart.labels; import java.awt.Font; import java.awt.Paint; import java.awt.font.TextAttribute; import java.text.AttributedString; import org.jfree.data.general.PieDataset; /** * Interface for a label generator for plots that use data from * a {@link PieDataset}. */ public interface PieSectionLabelGenerator { /** * Generates a label for a pie section. * * @param dataset the dataset (<code>null</code> not permitted). * @param key the section key (<code>null</code> not permitted). * * @return The label (possibly <code>null</code>). */ public String generateSectionLabel(PieDataset dataset, Comparable key); /** * Generates an attributed label for the specified series, or * <code>null</code> if no attributed label is available (in which case, * the string returned by * {@link #generateSectionLabel(PieDataset, Comparable)} will * provide the fallback). Only certain attributes are recognised by the * code that ultimately displays the labels: * <ul> * <li>{@link TextAttribute#FONT}: will set the font;</li> * <li>{@link TextAttribute#POSTURE}: a value of * {@link TextAttribute#POSTURE_OBLIQUE} will add {@link Font#ITALIC} to * the current font;</li> * <li>{@link TextAttribute#WEIGHT}: a value of * {@link TextAttribute#WEIGHT_BOLD} will add {@link Font#BOLD} to the * current font;</li> * <li>{@link TextAttribute#FOREGROUND}: this will set the {@link Paint} * for the current</li> * <li>{@link TextAttribute#SUPERSCRIPT}: the values * {@link TextAttribute#SUPERSCRIPT_SUB} and * {@link TextAttribute#SUPERSCRIPT_SUPER} are recognised.</li> * </ul> * * @param dataset the dataset. * @param key the key. * * @return An attributed label (possibly <code>null</code>). */ public AttributedString generateAttributedSectionLabel(PieDataset dataset, Comparable key); }
lgpl-2.1
xph906/SootNew
src/soot/jimple/spark/pag/AllocNode.java
3177
/* Soot - a J*va Optimization Framework * Copyright (C) 2002 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.spark.pag; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import soot.Context; import soot.PhaseOptions; import soot.RefType; import soot.SootMethod; import soot.Type; import soot.options.CGOptions; /** * Represents an allocation site node (Blue) in the pointer assignment graph. * * @author Ondrej Lhotak */ public class AllocNode extends Node implements Context { /** Returns the new expression of this allocation site. */ public Object getNewExpr() { return newExpr; } /** Returns all field ref nodes having this node as their base. */ public Collection<AllocDotField> getAllFieldRefs() { if (fields == null) return Collections.emptySet(); return fields.values(); } /** * Returns the field ref node having this node as its base, and field as its * field; null if nonexistent. */ public AllocDotField dot(SparkField field) { return fields == null ? null : fields.get(field); } public String toString() { return "AllocNode " + getNumber() + " " + newExpr + " in method " + method; } /* End of public methods. */ AllocNode(PAG pag, Object newExpr, Type t, SootMethod m) { super(pag, t); this.method = m; if (t instanceof RefType) { RefType rt = (RefType) t; if (rt.getSootClass().isAbstract()) { boolean usesReflectionLog = new CGOptions(PhaseOptions.v().getPhaseOptions("cg")) .reflection_log() != null; if (!usesReflectionLog) { throw new RuntimeException("Attempt to create allocnode with abstract type " + t); } } } this.newExpr = newExpr; if (newExpr instanceof ContextVarNode) throw new RuntimeException(); pag.getAllocNodeNumberer().add(this); } /** Registers a AllocDotField as having this node as its base. */ void addField(AllocDotField adf, SparkField field) { if (fields == null) fields = new HashMap<SparkField, AllocDotField>(); fields.put(field, adf); } public Set<AllocDotField> getFields() { if (fields == null) return Collections.emptySet(); return new HashSet<AllocDotField>(fields.values()); } /* End of package methods. */ protected Object newExpr; protected Map<SparkField, AllocDotField> fields; private SootMethod method; public SootMethod getMethod() { return method; } }
lgpl-2.1
marclaporte/jitsi
src/net/java/sip/communicator/impl/osdependent/OsDependentActivator.java
6387
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.osdependent; import net.java.sip.communicator.impl.osdependent.jdic.*; import net.java.sip.communicator.impl.osdependent.macosx.*; import net.java.sip.communicator.service.desktop.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.protocol.globalstatus.*; import net.java.sip.communicator.service.resources.*; import net.java.sip.communicator.service.shutdown.*; import net.java.sip.communicator.service.systray.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import org.jitsi.service.configuration.*; import org.jitsi.service.resources.*; import org.jitsi.util.*; import org.osgi.framework.*; /** * Registers the <tt>Systray</tt> in the UI Service. * * @author Nicolas Chamouard * @author Lyubomir Marinov */ public class OsDependentActivator implements BundleActivator { /** * A currently valid bundle context. */ public static BundleContext bundleContext; private static ConfigurationService configService; private static GlobalStatusService globalStatusService; /** * The <tt>Logger</tt> used by the <tt>OsDependentActivator</tt> class and * its instances for logging output. */ private static final Logger logger = Logger.getLogger(OsDependentActivator.class); private static ResourceManagementService resourcesService; public static UIService uiService; /** * Returns the <tt>ConfigurationService</tt> obtained from the bundle * context. * @return the <tt>ConfigurationService</tt> obtained from the bundle * context */ public static ConfigurationService getConfigurationService() { if(configService == null) { configService = ServiceUtils.getService( bundleContext, ConfigurationService.class); } return configService; } /** * Returns the <tt>GlobalStatusService</tt> obtained from the bundle * context. * @return the <tt>GlobalStatusService</tt> obtained from the bundle * context */ public static GlobalStatusService getGlobalStatusService() { if (globalStatusService == null) { globalStatusService = ServiceUtils.getService( bundleContext, GlobalStatusService.class); } return globalStatusService; } /** * Returns the <tt>ResourceManagementService</tt>, through which we will * access all resources. * * @return the <tt>ResourceManagementService</tt>, through which we will * access all resources. */ public static ResourceManagementService getResources() { if (resourcesService == null) { resourcesService = ResourceManagementServiceUtils.getService(bundleContext); } return resourcesService; } /** * Gets a reference to a <tt>ShutdownService</tt> implementation currently * registered in the <tt>BundleContext</tt> of the active * <tt>OsDependentActivator</tt> instance. * <p> * The returned reference to <tt>ShutdownService</tt> is not cached. * </p> * * @return reference to a <tt>ShutdownService</tt> implementation currently * registered in the <tt>BundleContext</tt> of the active * <tt>OsDependentActivator</tt> instance */ public static ShutdownService getShutdownService() { return ServiceUtils.getService(bundleContext, ShutdownService.class); } /** * Returns the <tt>UIService</tt> obtained from the bundle context. * @return the <tt>UIService</tt> obtained from the bundle context */ public static UIService getUIService() { if(uiService == null) uiService = ServiceUtils.getService(bundleContext, UIService.class); return uiService; } /** * Called when this bundle is started. * * @param bc The execution context of the bundle being started. * @throws Exception */ @Override public void start(BundleContext bc) throws Exception { bundleContext = bc; try { // Adds a MacOSX specific dock icon listener in order to show main // contact list window on dock icon click. if (OSUtils.IS_MAC) MacOSXDockIcon.addDockIconListener(); // Create the notification service implementation SystrayService systrayService = new SystrayServiceJdicImpl(); if (logger.isInfoEnabled()) logger.info("Systray Service...[ STARTED ]"); bundleContext.registerService( SystrayService.class.getName(), systrayService, null); if (logger.isInfoEnabled()) logger.info("Systray Service ...[REGISTERED]"); // Create the desktop service implementation DesktopService desktopService = new DesktopServiceImpl(); if (logger.isInfoEnabled()) logger.info("Desktop Service...[ STARTED ]"); bundleContext.registerService( DesktopService.class.getName(), desktopService, null); if (logger.isInfoEnabled()) logger.info("Desktop Service ...[REGISTERED]"); logger.logEntry(); } finally { logger.logExit(); } } /** * Called when this bundle is stopped so the Framework can perform the * bundle-specific activities necessary to stop the bundle. * * @param bc The execution context of the bundle being stopped. * @throws Exception If this method throws an exception, the bundle is still * marked as stopped, and the Framework will remove the bundle's listeners, * unregister all services registered by the bundle, and release all * services used by the bundle. */ @Override public void stop(BundleContext bc) throws Exception { } }
lgpl-2.1
adamallo/beast-mcmc
src/dr/inference/model/WeightedMixtureModel.java
9797
/* * WeightedMixtureModel.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.inference.model; import dr.inference.loggers.LogColumn; import dr.math.LogTricks; import dr.util.Citable; import dr.util.Citation; import dr.util.CommonCitations; import dr.xml.*; import java.util.*; import java.util.logging.Logger; /** * @author Marc A. Suchard * @author Andrew Rambaut */ public class WeightedMixtureModel extends AbstractModelLikelihood implements Citable { public static final String MIXTURE_MODEL = "mixtureModel"; // public static final String MIXTURE_WEIGHTS = "weights"; public static final String NORMALIZE = "normalize"; public WeightedMixtureModel(List<AbstractModelLikelihood> likelihoodList, Parameter mixtureWeights) { super(MIXTURE_MODEL); this.likelihoodList = likelihoodList; this.mixtureWeights = mixtureWeights; for (AbstractModelLikelihood model : likelihoodList) { addModel(model); } addVariable(mixtureWeights); StringBuilder sb = new StringBuilder(); sb.append("Constructing a finite mixture model\n"); sb.append("\tComponents:\n"); for (AbstractModelLikelihood model : likelihoodList) { sb.append("\t\t\t").append(model.getId()).append("\n"); } sb.append("\tMixing parameter: ").append(mixtureWeights.getId()).append("\n"); sb.append("\tPlease cite:\n"); sb.append(Citable.Utils.getCitationString((this))); Logger.getLogger("dr.inference.model").info(sb.toString()); } protected void handleModelChangedEvent(Model model, Object object, int index) { } protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { } protected void storeState() { } protected void restoreState() { } protected void acceptState() { } public Model getModel() { return this; } public double getLogLikelihood() { double logSum = Double.NEGATIVE_INFINITY; for (int i = 0; i < likelihoodList.size(); ++i) { double pi = mixtureWeights.getParameterValue(i); if (pi > 0.0) { logSum = LogTricks.logSum(logSum, Math.log(pi) + likelihoodList.get(i).getLogLikelihood()); } } return logSum; } public void makeDirty() { } public LogColumn[] getColumns() { return new LogColumn[0]; } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return MIXTURE_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { Parameter weights = (Parameter) xo.getChild(Parameter.class); List<AbstractModelLikelihood> likelihoodList = new ArrayList<AbstractModelLikelihood>(); for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof Likelihood) likelihoodList.add((AbstractModelLikelihood) xo.getChild(i)); } if (weights.getDimension() != likelihoodList.size()) { throw new XMLParseException("Dim of " + weights.getId() + " does not match the number of likelihoods"); } if (xo.hasAttribute(NORMALIZE)) { if (xo.getBooleanAttribute(NORMALIZE)) { double sum = 0; for (int i = 0; i < weights.getDimension(); i++) sum += weights.getParameterValue(i); for (int i = 0; i < weights.getDimension(); i++) weights.setParameterValue(i, weights.getParameterValue(i) / sum); } } if (!normalized(weights)) throw new XMLParseException("Parameter +" + weights.getId() + " must lie on the simplex"); return new WeightedMixtureModel(likelihoodList, weights); } private boolean normalized(Parameter p) { double sum = 0; for (int i = 0; i < p.getDimension(); i++) sum += p.getParameterValue(i); return (sum == 1.0); } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public String getParserDescription() { return "This element represents a finite mixture of likelihood models."; } public Class getReturnType() { return CompoundModel.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newBooleanRule(NORMALIZE, true), new ElementRule(Likelihood.class,2,Integer.MAX_VALUE), new ElementRule(Parameter.class) }; }; private final Parameter mixtureWeights; List<AbstractModelLikelihood> likelihoodList; public static void main(String[] args) { final double l1 = -10; final double l2 = -2; AbstractModelLikelihood like1 = new AbstractModelLikelihood("dummy") { public Model getModel() { return null; } public double getLogLikelihood() { return l1; } public void makeDirty() { } public String prettyName() { return null; } public boolean isUsed() { return false; } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { } @Override protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { } @Override protected void storeState() { } @Override protected void restoreState() { } @Override protected void acceptState() { } public void setUsed() { } public LogColumn[] getColumns() { return new LogColumn[0]; } public String getId() { return null; } public void setId(String id) { } }; AbstractModelLikelihood like2 = new AbstractModelLikelihood("dummy") { public Model getModel() { return null; } public double getLogLikelihood() { return l2; } public void makeDirty() { } public String prettyName() { return null; } public boolean isUsed() { return false; } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { } @Override protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) { } @Override protected void storeState() { } @Override protected void restoreState() { } @Override protected void acceptState() { } public void setUsed() { } public LogColumn[] getColumns() { return new LogColumn[0]; } public String getId() { return null; } public void setId(String id) { } }; List<AbstractModelLikelihood> likelihoodList = new ArrayList<AbstractModelLikelihood>(); likelihoodList.add(like1); likelihoodList.add(like2); Parameter weights = new Parameter.Default(2); double p1 = 0.05; weights.setParameterValue(0, p1); weights.setParameterValue(1, 1.0 - p1); WeightedMixtureModel mixture = new WeightedMixtureModel(likelihoodList, weights); System.err.println("getLogLikelihood() = " + mixture.getLogLikelihood()); double test = Math.log(p1 * Math.exp(l1) + (1.0 - p1) * Math.exp(l2)); System.err.println("correct = " + test); } @Override public Citation.Category getCategory() { return Citation.Category.MISC; } @Override public String getDescription() { return "Weighted mixture model"; } @Override public List<Citation> getCitations() { return Collections.singletonList(CommonCitations.LEMEY_MIXTURE_2012); } }
lgpl-2.1
sidohaakma/molgenis
molgenis-beacon/src/main/java/org/molgenis/beacon/controller/model/BeaconError.java
672
package org.molgenis.beacon.controller.model; import com.google.auto.value.AutoValue; import org.molgenis.gson.AutoGson; /** BeaconResponse-specific error representing an unexpected problem. */ @AutoValue @AutoGson(autoValueClass = AutoValue_BeaconError.class) @SuppressWarnings("java:S1610") // Abstract classes without fields should be converted to interfaces public abstract class BeaconError { /** Numeric error code. */ public abstract Integer getErrorCode(); /** Error message. */ public abstract String getMessage(); public static BeaconError create(Integer errorCode, String message) { return new AutoValue_BeaconError(errorCode, message); } }
lgpl-3.0
gauravpuri/MDP_Repp
src/burlap/behavior/singleagent/learning/lspi/SARSData.java
2742
package burlap.behavior.singleagent.learning.lspi; import java.util.ArrayList; import java.util.List; import burlap.oomdp.core.states.State; import burlap.oomdp.singleagent.GroundedAction; /** * Class that provides a wrapper for a List holding a bunch of state-action-reward-state ({@link SARS}) tuples. The dataset is backed by an {@link ArrayList}. * @author James MacGlashan * */ public class SARSData { /** * The underlying list of {@link SARS} tuples. */ public List<SARS> dataset; /** * Initializes with an empty dataset */ public SARSData(){ this.dataset = new ArrayList<SARSData.SARS>(); } /** * Initializes with an empty dataset with initial capacity for the given parameter available. * @param initialCapacity the initial capacity of the dataset. */ public SARSData(int initialCapacity){ this.dataset = new ArrayList<SARSData.SARS>(initialCapacity); } /** * The number of SARS tuples stored. * @return number of SARS tuples stored. */ public int size(){ return this.dataset.size(); } /** * Returns the {@link SARS} tuple for the ith dataset element. * @param i the index of the dataset * @return the ith {@link SARS} tuple. */ public SARS get(int i){ return this.dataset.get(i); } /** * Adds the given {@link SARS} tuple. * @param sars {@link SARS} tuple to add. */ public void add(SARS sars){ this.dataset.add(sars); } /** * Adds a {@link SARS} tuple with the given component. * @param s the previous state * @param a the action taken in the previous state * @param r the resulting reward received * @param sp the next state */ public void add(State s, GroundedAction a, double r, State sp){ this.dataset.add(new SARS(s, a, r, sp)); } /** * Removes the {@link SARS} tuple at the ith index * @param i the index of {@link SARS} tuple to remove. */ public void remove(int i){ this.dataset.remove(i); } /** * Clears this dataset of all elements. */ public void clear(){ this.dataset.clear(); } /** * State-action-reward-state tuple. * @author James MacGlashan * */ public static class SARS{ /** * The previou state */ public State s; /** * The action taken inthe previous state */ public GroundedAction a; /** * The resulting reward received */ public double r; /** * The next state */ public State sp; /** * Initializes. * @param s the previous state * @param a the action taken in the previous state * @param r the resulting reward received * @param sp the next state */ public SARS(State s, GroundedAction a, double r, State sp){ this.s = s; this.a = a; this.r = r; this.sp = sp; } } }
lgpl-3.0
Alfresco/community-edition
projects/repository/source/test-java/org/alfresco/repo/rendition/executer/AbstractRenderingEngineTest.java
13400
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.rendition.executer; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.Serializable; import java.util.Map; import junit.framework.TestCase; import org.alfresco.model.ContentModel; import org.alfresco.model.RenditionModel; import org.alfresco.repo.action.executer.ActionExecuter; import org.alfresco.repo.policy.BehaviourFilter; import org.alfresco.repo.rendition.RenditionDefinitionImpl; import org.alfresco.repo.rendition.executer.AbstractRenderingEngine.RenderingContext; import org.alfresco.service.cmr.rendition.RenditionDefinition; import org.alfresco.service.cmr.rendition.RenditionService; import org.alfresco.service.cmr.rendition.RenditionServiceException; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.namespace.QName; import org.mockito.ArgumentCaptor; /** * @author Nick Smith */ public class AbstractRenderingEngineTest extends TestCase { private final NodeRef source = new NodeRef("http://test/sourceId"); private ContentService contentService; private NodeService nodeService; private TestRenderingEngine engine; @Override protected void setUp() throws Exception { super.setUp(); this.contentService = mock(ContentService.class); this.nodeService = mock(NodeService.class); engine = new TestRenderingEngine(); engine.setContentService(contentService); engine.setNodeService(nodeService); engine.setBehaviourFilter(mock(BehaviourFilter.class)); } @SuppressWarnings({"unchecked" , "rawtypes"}) public void testCreateRenditionNodeAssoc() throws Exception { QName assocType = RenditionModel.ASSOC_RENDITION; when(nodeService.exists(source)).thenReturn(true); QName nodeType = ContentModel.TYPE_CONTENT; ChildAssociationRef renditionAssoc = makeRenditionAssoc(); RenditionDefinition definition = makeRenditionDefinition(renditionAssoc); // Stub the createNode() method to return renditionAssoc. when(nodeService.createNode(eq(source), eq(assocType), any(QName.class), any(QName.class), anyMap())) .thenReturn(renditionAssoc); engine.execute(definition, source); // Check the createNode method was called with the correct parameters. // Check the nodeType defaults to cm:content. ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class); verify(nodeService).createNode(eq(source), eq(assocType), any(QName.class), eq(nodeType), captor.capture()); Map<String, Serializable> props = captor.getValue(); // Check the node name is set to match teh rendition name local name. assertEquals(renditionAssoc.getQName().getLocalName(), props.get(ContentModel.PROP_NAME)); // Check content property name defaults to cm:content assertEquals(ContentModel.PROP_CONTENT, props.get(ContentModel.PROP_CONTENT_PROPERTY_NAME)); // Check the returned result is the association created by the call to // nodeServcie.createNode(). Serializable result = definition.getParameterValue(ActionExecuter.PARAM_RESULT); assertEquals("The returned rendition association is not the one created by the node service!", renditionAssoc, result); // Check that setting the default content property and default node type // on the rendition engine works. nodeType = QName.createQName("url", "someNodeType"); QName contentPropName = QName.createQName("url", "someContentProp"); engine.setDefaultRenditionContentProp(contentPropName.toString()); engine.setDefaultRenditionNodeType(nodeType.toString()); engine.execute(definition, source); verify(nodeService).createNode(eq(source), eq(assocType), any(QName.class), eq(nodeType), captor.capture()); props = captor.getValue(); assertEquals(contentPropName, props.get(ContentModel.PROP_CONTENT_PROPERTY_NAME)); // Check that setting the rendition node type param works. nodeType = ContentModel.TYPE_THUMBNAIL; contentPropName = ContentModel.PROP_CONTENT; definition.setParameterValue(RenditionService.PARAM_RENDITION_NODETYPE, nodeType); definition.setParameterValue(AbstractRenderingEngine.PARAM_TARGET_CONTENT_PROPERTY, contentPropName); engine.execute(definition, source); verify(nodeService).createNode(eq(source), eq(assocType), any(QName.class), eq(nodeType), captor.capture()); props = captor.getValue(); assertEquals(contentPropName, props.get(ContentModel.PROP_CONTENT_PROPERTY_NAME)); } public void testCheckSourceNodeExists() { when(nodeService.exists(any(NodeRef.class))).thenReturn(false); RenditionDefinitionImpl definition = new RenditionDefinitionImpl("id", null, TestRenderingEngine.NAME); try { engine.executeImpl(definition, source); fail("Should have thrown an exception here!"); } catch(RenditionServiceException e) { assertTrue(e.getMessage().endsWith("Cannot execute action as node does not exist: http://test/sourceId")); } } @SuppressWarnings("unchecked") public void testRenderingContext() { when(nodeService.exists(source)).thenReturn(true); ChildAssociationRef renditionAssoc = makeRenditionAssoc(); RenditionDefinition definition = makeRenditionDefinition(renditionAssoc); // Stub the createNode() method to return renditionAssoc. when(nodeService.createNode(eq(source), eq(renditionAssoc.getTypeQName()), any(QName.class), any(QName.class), anyMap())) .thenReturn(renditionAssoc); engine.execute(definition, source); RenderingContext context = engine.getContext(); assertEquals(definition, context.getDefinition()); assertEquals(renditionAssoc.getChildRef(), context.getDestinationNode()); assertEquals(source, context.getSourceNode()); } @SuppressWarnings("unchecked") public void testGetParameterWithDefault() { when(nodeService.exists(source)).thenReturn(true); ChildAssociationRef renditionAssoc = makeRenditionAssoc(); RenditionDefinition definition = makeRenditionDefinition(renditionAssoc); // Stub the createNode() method to return renditionAssoc. when(nodeService.createNode(eq(source), eq(renditionAssoc.getTypeQName()), any(QName.class), any(QName.class), anyMap())) .thenReturn(renditionAssoc); engine.executeImpl(definition, source); RenderingContext context = engine.getContext(); // Check default value works. String paramName = "Some-param"; String defaultValue = "default"; Object result = context.getParamWithDefault(paramName, defaultValue); assertEquals(defaultValue, result); // Check specific value overrides default. String value = "value"; definition.setParameterValue(paramName, value); engine.executeImpl(definition, source); context = engine.getContext(); result = context.getParamWithDefault(paramName, defaultValue); assertEquals(value, result); // Check null default value throws exception. try { result = context.getParamWithDefault(paramName, null); fail("Should throw an Exception if default value is null!"); } catch(RenditionServiceException e) { assertTrue(e.getMessage().endsWith("The defaultValue cannot be null!")); } // Check wrong type of default value throws exception. try { result = context.getParamWithDefault(paramName, Boolean.TRUE); fail("Should throw an exception if default value is of incoorect type!"); } catch (RenditionServiceException e) { assertTrue(e.getMessage().endsWith("The parameter: Some-param must be of type: java.lang.Booleanbut was of type: java.lang.String")); } } @SuppressWarnings("unchecked") public void testGetCheckedParameter() { when(nodeService.exists(source)).thenReturn(true); ChildAssociationRef renditionAssoc = makeRenditionAssoc(); RenditionDefinition definition = makeRenditionDefinition(renditionAssoc); // Stub the createNode() method to return renditionAssoc. when(nodeService.createNode(eq(source), eq(renditionAssoc.getTypeQName()), any(QName.class), any(QName.class), anyMap())) .thenReturn(renditionAssoc); engine.executeImpl(definition, source); RenderingContext context = engine.getContext(); String paramName = "Some param"; // Check returns null by default. String result = context.getCheckedParam(paramName, String.class); assertNull(result); // Check can set a value to return. String value = "value"; definition.setParameterValue(paramName, value); engine.executeImpl(definition, source); context = engine.getContext(); result = context.getCheckedParam(paramName, String.class); assertEquals(value, result); // Check throws an exception if value is of wrong type. try { context.getCheckedParam(paramName, Boolean.class); fail("Should throw an exception if type is wrong!"); } catch(RenditionServiceException e) { assertTrue(e.getMessage().endsWith("The parameter: Some param must be of type: java.lang.Booleanbut was of type: java.lang.String")); } // Check throws an exception if value is of wrong type. try { context.getCheckedParam(paramName, null); fail("Should throw an exception if type is wrong!"); } catch(RenditionServiceException e) { assertTrue(e.getMessage().endsWith("The class must not be null!")); } } /** * Set up the rendition definition. * @param renditionAssoc ChildAssociationRef * @return RenditionDefinition */ private RenditionDefinition makeRenditionDefinition(ChildAssociationRef renditionAssoc) { String id = "definitionId"; RenditionDefinition definition = new RenditionDefinitionImpl(id, renditionAssoc.getQName(), TestRenderingEngine.NAME); definition.setRenditionAssociationType(renditionAssoc.getTypeQName()); definition.setRenditionParent(source); return definition; } /** * Create the rendition association and destination node. */ private ChildAssociationRef makeRenditionAssoc() { QName assocType = RenditionModel.ASSOC_RENDITION; QName assocName = QName.createQName("url", "renditionName"); NodeRef destination = new NodeRef("http://test/destinationId"); return new ChildAssociationRef(assocType, source, assocName, destination); } private static class TestRenderingEngine extends AbstractRenderingEngine { public static String NAME = "Test"; private RenderingContext context; @Override protected void render(RenderingContext context1) { this.context = context1; } public RenderingContext getContext() { return context; } @Override protected void switchToFinalRenditionNode(RenditionDefinition renditionDef, NodeRef actionedUponNodeRef) { // Do nothing! } } }
lgpl-3.0
gauravpuri/MDP_Repp
src/burlap/behavior/singleagent/planning/Planner.java
1118
package burlap.behavior.singleagent.planning; import burlap.behavior.policy.Policy; import burlap.behavior.singleagent.MDPSolverInterface; import burlap.oomdp.core.states.State; /** * @author James MacGlashan. */ public interface Planner extends MDPSolverInterface{ /** * This method will cause the {@link burlap.behavior.singleagent.planning.Planner} to begin planning from the specified initial {@link burlap.oomdp.core.states.State}. * It will then return an appropriate {@link burlap.behavior.policy.Policy} object that captured the planning results. * Note that typically you can use a variety of different {@link burlap.behavior.policy.Policy} objects * in conjunction with this {@link burlap.behavior.singleagent.planning.Planner} to get varying behavior and * the returned {@link burlap.behavior.policy.Policy} is not required to be used. * @param initialState the initial state of the planning problem * @return a {@link burlap.behavior.policy.Policy} that captures the planning results from input {@link burlap.oomdp.core.states.State}. */ Policy planFromState(State initialState); }
lgpl-3.0
MaxNad/find-sec-bugs
plugin-deps/src/main/java/javax/ws/rs/core/CacheControl.java
57
package javax.ws.rs.core; public class CacheControl { }
lgpl-3.0
claudiu-stanciu/kylo
metadata/metadata-modeshape/src/main/java/com/thinkbiganalytics/metadata/modeshape/category/security/JcrCategoryAllowedActions.java
6683
package com.thinkbiganalytics.metadata.modeshape.category.security; /*- * #%L * kylo-metadata-modeshape * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.metadata.api.category.security.CategoryAccessControl; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.modeshape.category.JcrCategory; import com.thinkbiganalytics.metadata.modeshape.security.JcrAccessControlUtil; import com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions; import com.thinkbiganalytics.metadata.modeshape.support.JcrUtil; import com.thinkbiganalytics.security.action.Action; import com.thinkbiganalytics.security.action.AllowedActions; import java.security.Principal; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.jcr.Node; import javax.jcr.security.Privilege; /** * A type of allowed actions that applies to category. It intercepts certain action enable/disable * calls related to visibility to update the underlying JCR node structure's ACL lists. */ public class JcrCategoryAllowedActions extends JcrAllowedActions { private JcrCategory category; /** * @param allowedActionsNode */ public JcrCategoryAllowedActions(Node allowedActionsNode) { super(allowedActionsNode); this.category = JcrUtil.getJcrObject(JcrUtil.getParent(allowedActionsNode), JcrCategory.class); } @Override public boolean enable(Principal principal, Set<Action> actions) { boolean changed = super.enable(principal, actions); updateEntityAccess(principal, getEnabledActions(principal)); return changed; } @Override public boolean enableOnly(Principal principal, Set<Action> actions) { // Never replace permissions of the owner if (! principal.equals(this.category.getOwner())) { boolean changed = super.enableOnly(principal, actions); updateEntityAccess(principal, getEnabledActions(principal)); return changed; } else { return false; } } @Override public boolean enableOnly(Principal principal, AllowedActions actions) { // Never replace permissions of the owner if (! principal.equals(this.category.getOwner())) { boolean changed = super.enableOnly(principal, actions); updateEntityAccess(principal, getEnabledActions(principal)); return changed; } else { return false; } } @Override public boolean disable(Principal principal, Set<Action> actions) { // Never disable permissions of the owner if (! principal.equals(this.category.getOwner())) { boolean changed = super.disable(principal, actions); updateEntityAccess(principal, getEnabledActions(principal)); return changed; } else { return false; } } @Override public void setupAccessControl(Principal owner) { enable(JcrMetadataAccess.getActiveUser(), CategoryAccessControl.EDIT_DETAILS); enable(JcrMetadataAccess.ADMIN, CategoryAccessControl.EDIT_DETAILS); super.setupAccessControl(owner); } @Override public void removeAccessControl(Principal owner) { super.removeAccessControl(owner); this.category.getDetails().ifPresent(d -> JcrAccessControlUtil.clearHierarchyPermissions(d.getNode(), category.getNode())); } protected void updateEntityAccess(Principal principal, Set<? extends Action> actions) { Set<String> detailPrivs = new HashSet<>(); Set<String> summaryPrivs = new HashSet<>(); actions.forEach(action -> { //When Change Perms comes through the user needs write access to the allowed actions tree to grant additional access if (action.implies(CategoryAccessControl.CHANGE_PERMS)) { Collections.addAll(detailPrivs, Privilege.JCR_READ_ACCESS_CONTROL, Privilege.JCR_MODIFY_ACCESS_CONTROL); Collections.addAll(summaryPrivs, Privilege.JCR_READ_ACCESS_CONTROL, Privilege.JCR_MODIFY_ACCESS_CONTROL); } else if (action.implies(CategoryAccessControl.EDIT_DETAILS)) { detailPrivs.add(Privilege.JCR_ALL); } else if (action.implies(CategoryAccessControl.EDIT_SUMMARY)) { summaryPrivs.add(Privilege.JCR_ALL); } else if (action.implies(CategoryAccessControl.CREATE_FEED)) { // Privilege.JCR_MODIFY_ACCESS_CONTROL is needed here since anyone creating a new feed will inherit the ACL access from this parent // category details node before the access control is update in the new feed node, and the new feed owner needs rights to change // the access control of the feed it is creating. TODO: Perhaps we should refactor in a future release to create a simple child node // that the feed nodes attach to so that that node only can have Privilege.JCR_MODIFY_ACCESS_CONTROL for the user Collections.addAll(detailPrivs, Privilege.JCR_ADD_CHILD_NODES, Privilege.JCR_REMOVE_CHILD_NODES, Privilege.JCR_MODIFY_PROPERTIES, Privilege.JCR_READ_ACCESS_CONTROL, Privilege.JCR_MODIFY_ACCESS_CONTROL); Collections.addAll(summaryPrivs, Privilege.JCR_MODIFY_PROPERTIES); } else if (action.implies(CategoryAccessControl.ACCESS_DETAILS)) { detailPrivs.add(Privilege.JCR_READ); } else if (action.implies(CategoryAccessControl.ACCESS_CATEGORY)) { summaryPrivs.add(Privilege.JCR_READ); } }); JcrAccessControlUtil.setPermissions(this.category.getNode(), principal, summaryPrivs); this.category.getDetails().ifPresent(d -> JcrAccessControlUtil.setPermissions(d.getNode(), principal, detailPrivs)); } @Override protected boolean isAdminAction(Action action) { return action.implies(CategoryAccessControl.CHANGE_PERMS); } }
apache-2.0
xiaoleiPENG/my-project
spring-boot-samples/spring-boot-sample-websocket-jetty/src/test/java/samples/websocket/jetty/snake/SnakeTimerTests.java
1234
/* * Copyright 2012-2016 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 samples.websocket.jetty.snake; import java.io.IOException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; public class SnakeTimerTests { @Test public void removeDysfunctionalSnakes() throws Exception { Snake snake = mock(Snake.class); willThrow(new IOException()).given(snake).sendMessage(anyString()); SnakeTimer.addSnake(snake); SnakeTimer.broadcast(""); assertThat(SnakeTimer.getSnakes()).hasSize(0); } }
apache-2.0
s-gheldd/netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java
8776
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.http.websocketx; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.AttributeKey; import java.util.List; import static io.netty.handler.codec.http.HttpVersion.*; /** * This handler does all the heavy lifting for you to run a websocket server. * * It takes care of websocket handshaking as well as processing of control frames (Close, Ping, Pong). Text and Binary * data frames are passed to the next handler in the pipeline (implemented by you) for processing. * * See <tt>io.netty.example.http.websocketx.html5.WebSocketServer</tt> for usage. * * The implementation of this handler assumes that you just want to run a websocket server and not process other types * HTTP requests (like GET and POST). If you wish to support both HTTP requests and websockets in the one server, refer * to the <tt>io.netty.example.http.websocketx.server.WebSocketServer</tt> example. * * To know once a handshake was done you can intercept the * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} and check if the event was instance * of {@link HandshakeComplete}, the event will contain extra information about the handshake such as the request and * selected subprotocol. */ public class WebSocketServerProtocolHandler extends WebSocketProtocolHandler { /** * Events that are fired to notify about handshake status */ public enum ServerHandshakeStateEvent { /** * The Handshake was completed successfully and the channel was upgraded to websockets. * * @deprecated in favor of {@link HandshakeComplete} class, * it provides extra information about the handshake */ @Deprecated HANDSHAKE_COMPLETE } /** * The Handshake was completed successfully and the channel was upgraded to websockets. */ public static final class HandshakeComplete { private final String requestUri; private final HttpHeaders requestHeaders; private final String selectedSubprotocol; HandshakeComplete(String requestUri, HttpHeaders requestHeaders, String selectedSubprotocol) { this.requestUri = requestUri; this.requestHeaders = requestHeaders; this.selectedSubprotocol = selectedSubprotocol; } public String requestUri() { return requestUri; } public HttpHeaders requestHeaders() { return requestHeaders; } public String selectedSubprotocol() { return selectedSubprotocol; } } private static final AttributeKey<WebSocketServerHandshaker> HANDSHAKER_ATTR_KEY = AttributeKey.valueOf(WebSocketServerHandshaker.class, "HANDSHAKER"); private final String websocketPath; private final String subprotocols; private final boolean allowExtensions; private final int maxFramePayloadLength; private final boolean allowMaskMismatch; private final boolean checkStartsWith; public WebSocketServerProtocolHandler(String websocketPath) { this(websocketPath, null, false); } public WebSocketServerProtocolHandler(String websocketPath, boolean checkStartsWith) { this(websocketPath, null, false, 65536, false, checkStartsWith); } public WebSocketServerProtocolHandler(String websocketPath, String subprotocols) { this(websocketPath, subprotocols, false); } public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions) { this(websocketPath, subprotocols, allowExtensions, 65536); } public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions, int maxFrameSize) { this(websocketPath, subprotocols, allowExtensions, maxFrameSize, false); } public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch) { this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, false); } public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch, boolean checkStartsWith) { this.websocketPath = websocketPath; this.subprotocols = subprotocols; this.allowExtensions = allowExtensions; maxFramePayloadLength = maxFrameSize; this.allowMaskMismatch = allowMaskMismatch; this.checkStartsWith = checkStartsWith; } @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline cp = ctx.pipeline(); if (cp.get(WebSocketServerProtocolHandshakeHandler.class) == null) { // Add the WebSocketHandshakeHandler before this one. ctx.pipeline().addBefore(ctx.name(), WebSocketServerProtocolHandshakeHandler.class.getName(), new WebSocketServerProtocolHandshakeHandler(websocketPath, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch, checkStartsWith)); } if (cp.get(Utf8FrameValidator.class) == null) { // Add the UFT8 checking before this one. ctx.pipeline().addBefore(ctx.name(), Utf8FrameValidator.class.getName(), new Utf8FrameValidator()); } } @Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof CloseWebSocketFrame) { WebSocketServerHandshaker handshaker = getHandshaker(ctx.channel()); if (handshaker != null) { frame.retain(); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } return; } super.decode(ctx, frame, out); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof WebSocketHandshakeException) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer(cause.getMessage().getBytes())); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { ctx.close(); } } static WebSocketServerHandshaker getHandshaker(Channel channel) { return channel.attr(HANDSHAKER_ATTR_KEY).get(); } static void setHandshaker(Channel channel, WebSocketServerHandshaker handshaker) { channel.attr(HANDSHAKER_ATTR_KEY).set(handshaker); } static ChannelHandler forbiddenHttpRequestResponder() { return new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).release(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN); ctx.channel().writeAndFlush(response); } else { ctx.fireChannelRead(msg); } } }; } }
apache-2.0
walteryang47/ovirt-engine
frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/view/tab/cluster/SubTabClusterNetworkView.java
8585
package org.ovirt.engine.ui.webadmin.section.main.view.tab.cluster; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.NetworkCluster; import org.ovirt.engine.core.common.businessentities.network.NetworkStatus; import org.ovirt.engine.ui.common.idhandler.ElementIdHandler; import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider; import org.ovirt.engine.ui.common.widget.table.column.AbstractEnumColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractSafeHtmlColumn; import org.ovirt.engine.ui.common.widget.table.column.AbstractTextColumn; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterListModel; import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterNetworkListModel; import org.ovirt.engine.ui.webadmin.ApplicationConstants; import org.ovirt.engine.ui.webadmin.ApplicationResources; import org.ovirt.engine.ui.webadmin.gin.AssetProvider; import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.cluster.SubTabClusterNetworkPresenter; import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabTableView; import org.ovirt.engine.ui.webadmin.widget.action.WebAdminButtonDefinition; import org.ovirt.engine.ui.webadmin.widget.table.column.MultiImageColumnHelper; import org.ovirt.engine.ui.webadmin.widget.table.column.NetworkStatusColumn; import com.google.gwt.core.client.GWT; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.inject.Inject; public class SubTabClusterNetworkView extends AbstractSubTabTableView<VDSGroup, Network, ClusterListModel<Void>, ClusterNetworkListModel> implements SubTabClusterNetworkPresenter.ViewDef { interface ViewIdHandler extends ElementIdHandler<SubTabClusterNetworkView> { ViewIdHandler idHandler = GWT.create(ViewIdHandler.class); } private final SafeHtml displayImage; private final SafeHtml migrationImage; private final SafeHtml glusterNwImage; private final SafeHtml emptyImage; private final SafeHtml managementImage; private final static ApplicationResources resources = AssetProvider.getResources(); private final static ApplicationConstants constants = AssetProvider.getConstants(); @Inject public SubTabClusterNetworkView(SearchableDetailModelProvider<Network, ClusterListModel<Void>, ClusterNetworkListModel> modelProvider) { super(modelProvider); displayImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.networkMonitor()).getHTML()); migrationImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.migrationNetwork()).getHTML()); glusterNwImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.glusterNetwork()).getHTML()); emptyImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.networkEmpty()).getHTML()); managementImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.mgmtNetwork()).getHTML()); initTable(); initWidget(getTable()); } @Override protected void generateIds() { ViewIdHandler.idHandler.generateAndSetIds(this); } void initTable() { getTable().enableColumnResizing(); getTable().addColumn(new NetworkStatusColumn(), "", "20px"); //$NON-NLS-1$ //$NON-NLS-2$ AbstractTextColumn<Network> nameColumn = new AbstractTextColumn<Network>() { @Override public String getValue(Network object) { return object.getName(); } }; nameColumn.makeSortable(); getTable().addColumn(nameColumn, constants.nameNetwork(), "400px"); //$NON-NLS-1$ AbstractTextColumn<Network> statusColumn = new AbstractEnumColumn<Network, NetworkStatus>() { @Override public NetworkStatus getRawValue(Network object) { return object.getCluster().getStatus(); } }; statusColumn.makeSortable(); getTable().addColumn(statusColumn, constants.statusNetwork(), "100px"); //$NON-NLS-1$ AbstractSafeHtmlColumn<Network> roleColumn = new AbstractSafeHtmlColumn<Network>() { @Override public SafeHtml getValue(Network network) { List<SafeHtml> images = new LinkedList<>(); final NetworkCluster networkCluster = network.getCluster(); if (networkCluster != null) { if (networkCluster.isManagement()) { images.add(managementImage); } else { images.add(emptyImage); } if (networkCluster.isDisplay()) { images.add(displayImage); } else { images.add(emptyImage); } if (networkCluster.isMigration()) { images.add(migrationImage); } else { images.add(emptyImage); } if (network.getCluster().isGluster()) { images.add(glusterNwImage); } else { images.add(emptyImage); } } return MultiImageColumnHelper.getValue(images); } @Override public String getTooltip(Network network) { Map<SafeHtml, String> imagesToText = new LinkedHashMap<>(); final NetworkCluster networkCluster = network.getCluster(); if (networkCluster != null) { if (networkCluster.isManagement()) { imagesToText.put(managementImage, constants.managementItemInfo()); } if (networkCluster.isDisplay()) { imagesToText.put(displayImage, constants.displayItemInfo()); } if (networkCluster.isMigration()) { imagesToText.put(migrationImage, constants.migrationItemInfo()); } if (network.getCluster().isGluster()) { imagesToText.put(glusterNwImage, constants.glusterNwItemInfo()); } } return MultiImageColumnHelper.getTooltip(imagesToText); } }; getTable().addColumn(roleColumn, constants.roleNetwork(), "90px"); //$NON-NLS-1$ AbstractTextColumn<Network> descColumn = new AbstractTextColumn<Network>() { @Override public String getValue(Network object) { return object.getDescription(); } }; descColumn.makeSortable(); getTable().addColumn(descColumn, constants.descriptionNetwork(), "400px"); //$NON-NLS-1$ getTable().addActionButton(new WebAdminButtonDefinition<Network>(constants.addNetworkNetwork()) { @Override protected UICommand resolveCommand() { return getDetailModel().getNewNetworkCommand(); } }); getTable().addActionButton(new WebAdminButtonDefinition<Network>(constants.assignDetatchNetworksNework()) { @Override protected UICommand resolveCommand() { return getDetailModel().getManageCommand(); } }); getTable().addActionButton(new WebAdminButtonDefinition<Network>(constants.setAsDisplayNetwork()) { @Override protected UICommand resolveCommand() { return getDetailModel().getSetAsDisplayCommand(); } }); } }
apache-2.0
os890/wink_patches
wink-server/src/test/java/org/apache/wink/server/internal/jaxrs/ApplicationInjectionTest.java
2441
/* * 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.wink.server.internal.jaxrs; import java.util.HashSet; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import org.apache.wink.server.internal.servlet.MockServletInvocationTest; import org.apache.wink.test.mock.MockRequestConstructor; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; public class ApplicationInjectionTest extends MockServletInvocationTest { @Override protected String getApplicationClassName() { return MyApplication.class.getName(); } public static class MyApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(TestResource.class); return classes; } } @Path("/test") public static class TestResource { @Context Application app; @GET public String get() { assertNotNull(app); assertTrue(app instanceof MyApplication); return "hello"; } } @Test public void testHttpHeaderContext() throws Exception { MockHttpServletRequest servletRequest = MockRequestConstructor.constructMockRequest("GET", "/test", "*/*"); MockHttpServletResponse response = invoke(servletRequest); assertEquals(200, response.getStatus()); assertEquals("hello", response.getContentAsString()); } }
apache-2.0
RanjithKumar5550/RanMifos
fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/exceptionmapper/PlatformDataIntegrityExceptionMapper.java
2246
/** * 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.fineract.infrastructure.core.exceptionmapper; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.apache.fineract.infrastructure.core.data.ApiGlobalErrorResponse; import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * An {@link ExceptionMapper} to map {@link PlatformDataIntegrityException} * thrown by platform into a HTTP API friendly format. * * The {@link PlatformDataIntegrityException} is thrown when modifying api call * result in data integrity checks to be fired. */ @Provider @Component @Scope("singleton") public class PlatformDataIntegrityExceptionMapper implements ExceptionMapper<PlatformDataIntegrityException> { @Override public Response toResponse(final PlatformDataIntegrityException exception) { final ApiGlobalErrorResponse dataIntegrityError = ApiGlobalErrorResponse.dataIntegrityError( exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getParameterName(), exception.getDefaultUserMessageArgs()); return Response.status(Status.FORBIDDEN).entity(dataIntegrityError).type(MediaType.APPLICATION_JSON).build(); } }
apache-2.0
shun634501730/java_source_cn
src_en/javax/swing/plaf/basic/BasicBorders.java
23515
/* * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.JTextComponent; import java.awt.Component; import java.awt.Insets; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Color; import java.awt.Graphics; import sun.swing.SwingUtilities2; /** * Factory object that can vend Borders appropriate for the basic L &amp; F. * @author Georges Saab * @author Amy Fowler */ public class BasicBorders { public static Border getButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border buttonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.ButtonBorder( table.getColor("Button.shadow"), table.getColor("Button.darkShadow"), table.getColor("Button.light"), table.getColor("Button.highlight")), new MarginBorder()); return buttonBorder; } public static Border getRadioButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border radioButtonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.RadioButtonBorder( table.getColor("RadioButton.shadow"), table.getColor("RadioButton.darkShadow"), table.getColor("RadioButton.light"), table.getColor("RadioButton.highlight")), new MarginBorder()); return radioButtonBorder; } public static Border getToggleButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border toggleButtonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.ToggleButtonBorder( table.getColor("ToggleButton.shadow"), table.getColor("ToggleButton.darkShadow"), table.getColor("ToggleButton.light"), table.getColor("ToggleButton.highlight")), new MarginBorder()); return toggleButtonBorder; } public static Border getMenuBarBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border menuBarBorder = new BasicBorders.MenuBarBorder( table.getColor("MenuBar.shadow"), table.getColor("MenuBar.highlight") ); return menuBarBorder; } public static Border getSplitPaneBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border splitPaneBorder = new BasicBorders.SplitPaneBorder( table.getColor("SplitPane.highlight"), table.getColor("SplitPane.darkShadow")); return splitPaneBorder; } /** * Returns a border instance for a JSplitPane divider * @since 1.3 */ public static Border getSplitPaneDividerBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border splitPaneBorder = new BasicBorders.SplitPaneDividerBorder( table.getColor("SplitPane.highlight"), table.getColor("SplitPane.darkShadow")); return splitPaneBorder; } public static Border getTextFieldBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border textFieldBorder = new BasicBorders.FieldBorder( table.getColor("TextField.shadow"), table.getColor("TextField.darkShadow"), table.getColor("TextField.light"), table.getColor("TextField.highlight")); return textFieldBorder; } public static Border getProgressBarBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border progressBarBorder = new BorderUIResource.LineBorderUIResource(Color.green, 2); return progressBarBorder; } public static Border getInternalFrameBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border internalFrameBorder = new BorderUIResource.CompoundBorderUIResource( new BevelBorder(BevelBorder.RAISED, table.getColor("InternalFrame.borderLight"), table.getColor("InternalFrame.borderHighlight"), table.getColor("InternalFrame.borderDarkShadow"), table.getColor("InternalFrame.borderShadow")), BorderFactory.createLineBorder( table.getColor("InternalFrame.borderColor"), 1)); return internalFrameBorder; } /** * Special thin border for rollover toolbar buttons. * @since 1.4 */ public static class RolloverButtonBorder extends ButtonBorder { public RolloverButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); Color shade = shadow; Component p = b.getParent(); if (p != null && p.getBackground().equals(shadow)) { shade = darkShadow; } if ((model.isRollover() && !(model.isPressed() && !model.isArmed())) || model.isSelected()) { Color oldColor = g.getColor(); g.translate(x, y); if (model.isPressed() && model.isArmed() || model.isSelected()) { // Draw the pressd button g.setColor(shade); g.drawRect(0, 0, w-1, h-1); g.setColor(lightHighlight); g.drawLine(w-1, 0, w-1, h-1); g.drawLine(0, h-1, w-1, h-1); } else { // Draw a rollover button g.setColor(lightHighlight); g.drawRect(0, 0, w-1, h-1); g.setColor(shade); g.drawLine(w-1, 0, w-1, h-1); g.drawLine(0, h-1, w-1, h-1); } g.translate(-x, -y); g.setColor(oldColor); } } } /** * A border which is like a Margin border but it will only honor the margin * if the margin has been explicitly set by the developer. * * Note: This is identical to the package private class * MetalBorders.RolloverMarginBorder and should probably be consolidated. */ static class RolloverMarginBorder extends EmptyBorder { public RolloverMarginBorder() { super(3,3,3,3); // hardcoded margin for JLF requirements. } public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; if (c instanceof AbstractButton) { margin = ((AbstractButton)c).getMargin(); } if (margin == null || margin instanceof UIResource) { // default margin so replace insets.left = left; insets.top = top; insets.right = right; insets.bottom = bottom; } else { // Margin which has been explicitly set by the user. insets.left = margin.left; insets.top = margin.top; insets.right = margin.right; insets.bottom = margin.bottom; } return insets; } } public static class ButtonBorder extends AbstractBorder implements UIResource { protected Color shadow; protected Color darkShadow; protected Color highlight; protected Color lightHighlight; public ButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { this.shadow = shadow; this.darkShadow = darkShadow; this.highlight = highlight; this.lightHighlight = lightHighlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { boolean isPressed = false; boolean isDefault = false; if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; ButtonModel model = b.getModel(); isPressed = model.isPressed() && model.isArmed(); if (c instanceof JButton) { isDefault = ((JButton)c).isDefaultButton(); } } BasicGraphicsUtils.drawBezel(g, x, y, width, height, isPressed, isDefault, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c, Insets insets) { // leave room for default visual insets.set(2, 3, 3, 3); return insets; } } public static class ToggleButtonBorder extends ButtonBorder { public ToggleButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, false, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c, Insets insets) { insets.set(2, 2, 2, 2); return insets; } } public static class RadioButtonBorder extends ButtonBorder { public RadioButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; ButtonModel model = b.getModel(); if (model.isArmed() && model.isPressed() || model.isSelected()) { BasicGraphicsUtils.drawLoweredBezel(g, x, y, width, height, shadow, darkShadow, highlight, lightHighlight); } else { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, b.isFocusPainted() && b.hasFocus(), shadow, darkShadow, highlight, lightHighlight); } } else { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, false, shadow, darkShadow, highlight, lightHighlight); } } public Insets getBorderInsets(Component c, Insets insets) { insets.set(2, 2, 2, 2); return insets; } } public static class MenuBarBorder extends AbstractBorder implements UIResource { private Color shadow; private Color highlight; public MenuBarBorder(Color shadow, Color highlight) { this.shadow = shadow; this.highlight = highlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); g.translate(x, y); g.setColor(shadow); SwingUtilities2.drawHLine(g, 0, width - 1, height - 2); g.setColor(highlight); SwingUtilities2.drawHLine(g, 0, width - 1, height - 1); g.translate(-x, -y); g.setColor(oldColor); } public Insets getBorderInsets(Component c, Insets insets) { insets.set(0, 0, 2, 0); return insets; } } public static class MarginBorder extends AbstractBorder implements UIResource { public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; // // Ideally we'd have an interface defined for classes which // support margins (to avoid this hackery), but we've // decided against it for simplicity // if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; margin = b.getMargin(); } else if (c instanceof JToolBar) { JToolBar t = (JToolBar)c; margin = t.getMargin(); } else if (c instanceof JTextComponent) { JTextComponent t = (JTextComponent)c; margin = t.getMargin(); } insets.top = margin != null? margin.top : 0; insets.left = margin != null? margin.left : 0; insets.bottom = margin != null? margin.bottom : 0; insets.right = margin != null? margin.right : 0; return insets; } } public static class FieldBorder extends AbstractBorder implements UIResource { protected Color shadow; protected Color darkShadow; protected Color highlight; protected Color lightHighlight; public FieldBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { this.shadow = shadow; this.highlight = highlight; this.darkShadow = darkShadow; this.lightHighlight = lightHighlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { BasicGraphicsUtils.drawEtchedRect(g, x, y, width, height, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; if (c instanceof JTextComponent) { margin = ((JTextComponent)c).getMargin(); } insets.top = margin != null? 2+margin.top : 2; insets.left = margin != null? 2+margin.left : 2; insets.bottom = margin != null? 2+margin.bottom : 2; insets.right = margin != null? 2+margin.right : 2; return insets; } } /** * Draws the border around the divider in a splitpane * (when BasicSplitPaneUI is used). To get the appropriate effect, this * needs to be used with a SplitPaneBorder. */ static class SplitPaneDividerBorder implements Border, UIResource { Color highlight; Color shadow; SplitPaneDividerBorder(Color highlight, Color shadow) { this.highlight = highlight; this.shadow = shadow; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (!(c instanceof BasicSplitPaneDivider)) { return; } Component child; Rectangle cBounds; JSplitPane splitPane = ((BasicSplitPaneDivider)c). getBasicSplitPaneUI().getSplitPane(); Dimension size = c.getSize(); child = splitPane.getLeftComponent(); // This is needed for the space between the divider and end of // splitpane. g.setColor(c.getBackground()); g.drawRect(x, y, width - 1, height - 1); if(splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { if(child != null) { g.setColor(highlight); g.drawLine(0, 0, 0, size.height); } child = splitPane.getRightComponent(); if(child != null) { g.setColor(shadow); g.drawLine(size.width - 1, 0, size.width - 1, size.height); } } else { if(child != null) { g.setColor(highlight); g.drawLine(0, 0, size.width, 0); } child = splitPane.getRightComponent(); if(child != null) { g.setColor(shadow); g.drawLine(0, size.height - 1, size.width, size.height - 1); } } } public Insets getBorderInsets(Component c) { Insets insets = new Insets(0,0,0,0); if (c instanceof BasicSplitPaneDivider) { BasicSplitPaneUI bspui = ((BasicSplitPaneDivider)c). getBasicSplitPaneUI(); if (bspui != null) { JSplitPane splitPane = bspui.getSplitPane(); if (splitPane != null) { if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { insets.top = insets.bottom = 0; insets.left = insets.right = 1; return insets; } // VERTICAL_SPLIT insets.top = insets.bottom = 1; insets.left = insets.right = 0; return insets; } } } insets.top = insets.bottom = insets.left = insets.right = 1; return insets; } public boolean isBorderOpaque() { return true; } } /** * Draws the border around the splitpane. To work correctly you should * also install a border on the divider (property SplitPaneDivider.border). */ public static class SplitPaneBorder implements Border, UIResource { protected Color highlight; protected Color shadow; public SplitPaneBorder(Color highlight, Color shadow) { this.highlight = highlight; this.shadow = shadow; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (!(c instanceof JSplitPane)) { return; } // The only tricky part with this border is that the divider is // not positioned at the top (for horizontal) or left (for vert), // so this border draws to where the divider is: // ----------------- // |xxxxxxx xxxxxxx| // |x --- x| // |x | | x| // |x |D| x| // |x | | x| // |x --- x| // |xxxxxxx xxxxxxx| // ----------------- // The above shows (rather excessively) what this looks like for // a horizontal orientation. This border then draws the x's, with // the SplitPaneDividerBorder drawing its own border. Component child; Rectangle cBounds; JSplitPane splitPane = (JSplitPane)c; child = splitPane.getLeftComponent(); // This is needed for the space between the divider and end of // splitpane. g.setColor(c.getBackground()); g.drawRect(x, y, width - 1, height - 1); if(splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { if(child != null) { cBounds = child.getBounds(); g.setColor(shadow); g.drawLine(0, 0, cBounds.width + 1, 0); g.drawLine(0, 1, 0, cBounds.height + 1); g.setColor(highlight); g.drawLine(0, cBounds.height + 1, cBounds.width + 1, cBounds.height + 1); } child = splitPane.getRightComponent(); if(child != null) { cBounds = child.getBounds(); int maxX = cBounds.x + cBounds.width; int maxY = cBounds.y + cBounds.height; g.setColor(shadow); g.drawLine(cBounds.x - 1, 0, maxX, 0); g.setColor(highlight); g.drawLine(cBounds.x - 1, maxY, maxX, maxY); g.drawLine(maxX, 0, maxX, maxY + 1); } } else { if(child != null) { cBounds = child.getBounds(); g.setColor(shadow); g.drawLine(0, 0, cBounds.width + 1, 0); g.drawLine(0, 1, 0, cBounds.height); g.setColor(highlight); g.drawLine(1 + cBounds.width, 0, 1 + cBounds.width, cBounds.height + 1); g.drawLine(0, cBounds.height + 1, 0, cBounds.height + 1); } child = splitPane.getRightComponent(); if(child != null) { cBounds = child.getBounds(); int maxX = cBounds.x + cBounds.width; int maxY = cBounds.y + cBounds.height; g.setColor(shadow); g.drawLine(0, cBounds.y - 1, 0, maxY); g.drawLine(maxX, cBounds.y - 1, maxX, cBounds.y - 1); g.setColor(highlight); g.drawLine(0, maxY, cBounds.width + 1, maxY); g.drawLine(maxX, cBounds.y, maxX, maxY); } } } public Insets getBorderInsets(Component c) { return new Insets(1, 1, 1, 1); } public boolean isBorderOpaque() { return true; } } }
apache-2.0
alex-dorokhov/libgdx
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplicationLogger.java
2933
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.backends.gwt; import com.badlogic.gdx.ApplicationLogger; import com.badlogic.gdx.Gdx; import com.google.gwt.user.client.ui.TextArea; /** * Default implementation of {@link ApplicationLogger} for gwt */ public class GwtApplicationLogger implements ApplicationLogger { private TextArea log; public GwtApplicationLogger (TextArea log) { this.log = log; } @Override public void log (String tag, String message) { logText(tag + ": " + message, false); } private void logText(String message, boolean error) { if (log != null) { log.setText(log.getText() + "\n" + message + "\n"); log.setCursorPos(log.getText().length() - 1); } else if (error) { consoleError(message); } else { consoleLog(message); } } native static public void consoleLog(String message) /*-{ console.log( message ); }-*/; native static public void consoleError(String message) /*-{ console.error( message ); }-*/; @Override public void log (String tag, String message, Throwable exception) { logText(tag + ": " + message + "\n" + getMessages(exception), false); logText(getStackTrace(exception), false); } @Override public void error (String tag, String message) { logText(tag + ": " + message, true); } @Override public void error (String tag, String message, Throwable exception) { logText(tag + ": " + message + "\n" + getMessages(exception), true); logText(getStackTrace(exception), false); } @Override public void debug (String tag, String message) { logText(tag + ": " + message, false); } @Override public void debug (String tag, String message, Throwable exception) { logText(tag + ": " + message + "\n" + getMessages(exception), false); logText(getStackTrace(exception), false); } private String getMessages (Throwable e) { StringBuilder sb = new StringBuilder(); while (e != null) { sb.append(e.getMessage() + "\n"); e = e.getCause(); } return sb.toString(); } private String getStackTrace (Throwable e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement trace : e.getStackTrace()) { sb.append(trace.toString() + "\n"); } return sb.toString(); } }
apache-2.0
dsukhoroslov/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/fd/PingFailureDetector.java
2216
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.cluster.fd; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; /** * Ping based failure detector. (OSI Layer 3) * This failure detector uses an absolute number of missing ping attempts. * After that many attempts, an endpoint is considered as dead/unavailable. */ public class PingFailureDetector<E> { private final int maxPingAttempts; private final ConcurrentMap<E, AtomicInteger> pingAttempts = new ConcurrentHashMap<E, AtomicInteger>(); public PingFailureDetector(int maxPingAttempts) { this.maxPingAttempts = maxPingAttempts; } public int heartbeat(E endpoint) { return getAttempts(endpoint).getAndSet(0); } public void logAttempt(E endpoint) { getAttempts(endpoint).incrementAndGet(); } public boolean isAlive(E endpoint) { AtomicInteger attempts = pingAttempts.get(endpoint); return attempts != null && attempts.get() < maxPingAttempts; } public void remove(E endpoint) { pingAttempts.remove(endpoint); } public void reset() { pingAttempts.clear(); } private AtomicInteger getAttempts(E endpoint) { AtomicInteger existing = pingAttempts.get(endpoint); AtomicInteger newAttempts = null; if (existing == null) { newAttempts = new AtomicInteger(); existing = pingAttempts.putIfAbsent(endpoint, newAttempts); } return existing != null ? existing : newAttempts; } }
apache-2.0
karreiro/uberfire
uberfire-extensions/uberfire-commons-editor/uberfire-commons-editor-client/src/main/java/org/uberfire/ext/editor/commons/client/event/ConcurrentDeleteIgnoredEvent.java
911
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.editor.commons.client.event; import org.uberfire.backend.vfs.ObservablePath; public class ConcurrentDeleteIgnoredEvent extends AbstractConcurrentOperationEvent { public ConcurrentDeleteIgnoredEvent(final ObservablePath path) { super(path); } }
apache-2.0
joroKr21/incubator-zeppelin
zeppelin-interpreter-integration/src/test/java/org/apache/zeppelin/integration/SparkIntegrationTest20.java
1347
/* * 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.zeppelin.integration; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.List; @RunWith(value = Parameterized.class) public class SparkIntegrationTest20 extends SparkIntegrationTest{ public SparkIntegrationTest20(String sparkVersion, String hadoopVersion) { super(sparkVersion, hadoopVersion); } @Parameterized.Parameters public static List<Object[]> data() { return Arrays.asList(new Object[][]{ {"2.0.2", "2.7"} }); } }
apache-2.0
google/guava
guava/src/com/google/common/base/FunctionalEquivalence.java
2370
/* * 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.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Equivalence applied on functional result. * * @author Bob Lee * @since 10.0 */ @Beta @GwtCompatible @ElementTypesAreNonnullByDefault final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable { private static final long serialVersionUID = 0; private final Function<? super F, ? extends @Nullable T> function; private final Equivalence<T> resultEquivalence; FunctionalEquivalence( Function<? super F, ? extends @Nullable T> function, Equivalence<T> resultEquivalence) { this.function = checkNotNull(function); this.resultEquivalence = checkNotNull(resultEquivalence); } @Override protected boolean doEquivalent(F a, F b) { return resultEquivalence.equivalent(function.apply(a), function.apply(b)); } @Override protected int doHash(F a) { return resultEquivalence.hash(function.apply(a)); } @Override public boolean equals(@CheckForNull Object obj) { if (obj == this) { return true; } if (obj instanceof FunctionalEquivalence) { FunctionalEquivalence<?, ?> that = (FunctionalEquivalence<?, ?>) obj; return function.equals(that.function) && resultEquivalence.equals(that.resultEquivalence); } return false; } @Override public int hashCode() { return Objects.hashCode(function, resultEquivalence); } @Override public String toString() { return resultEquivalence + ".onResultOf(" + function + ")"; } }
apache-2.0
RNDITS/geonetworking
uppertester/src/main/java/net/gcdc/uppertester/BtpTriggerA.java
138
package net.gcdc.uppertester; public class BtpTriggerA { byte messageType = 0x70; short destinationPort; short sourcePort; }
apache-2.0
AlexMinsk/camunda-bpm-platform
engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceQueryTest.java
14636
package org.camunda.bpm.engine.rest; import static com.jayway.restassured.RestAssured.expect; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.path.json.JsonPath.from; import static org.fest.assertions.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.Response.Status; import org.camunda.bpm.engine.repository.Deployment; import org.camunda.bpm.engine.repository.DeploymentQuery; import org.camunda.bpm.engine.rest.exception.InvalidRequestException; import org.camunda.bpm.engine.rest.helper.MockProvider; import org.camunda.bpm.engine.rest.util.container.TestContainerRule; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.Response; public class DeploymentRestServiceQueryTest extends AbstractRestServiceTest { @ClassRule public static TestContainerRule rule = new TestContainerRule(); protected static final String DEPLOYMENT_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/deployment"; protected static final String DEPLOYMENT_COUNT_QUERY_URL = DEPLOYMENT_QUERY_URL + "/count"; private DeploymentQuery mockedQuery; @Before public void setUpRuntimeData() { mockedQuery = setUpMockDeploymentQuery(MockProvider.createMockDeployments()); } private DeploymentQuery setUpMockDeploymentQuery(List<Deployment> mockedDeployments) { DeploymentQuery sampleDeploymentQuery = mock(DeploymentQuery.class); when(sampleDeploymentQuery.list()).thenReturn(mockedDeployments); when(sampleDeploymentQuery.count()).thenReturn((long) mockedDeployments.size()); when(processEngine.getRepositoryService().createDeploymentQuery()).thenReturn(sampleDeploymentQuery); return sampleDeploymentQuery; } @Test public void testEmptyQuery() { given() .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); } @Test public void testInvalidSortingOptions() { executeAndVerifyFailingSorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST, InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortBy' to value 'anInvalidSortByOption'"); executeAndVerifyFailingSorting("name", "anInvalidSortOrderOption", Status.BAD_REQUEST, InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortOrder' to value 'anInvalidSortOrderOption'"); } protected void executeAndVerifySuccessfulSorting(String sortBy, String sortOrder, Status expectedStatus) { given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) .then().expect().statusCode(expectedStatus.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); } protected void executeAndVerifyFailingSorting(String sortBy, String sortOrder, Status expectedStatus, String expectedErrorType, String expectedErrorMessage) { given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) .then().expect().statusCode(expectedStatus.getStatusCode()).contentType(ContentType.JSON) .body("type", equalTo(expectedErrorType)) .body("message", equalTo(expectedErrorMessage)) .when().get(DEPLOYMENT_QUERY_URL); } @Test public void testSortByParameterOnly() { given().queryParam("sortBy", "name") .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) .body("type", equalTo(InvalidRequestException.class.getSimpleName())) .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) .when().get(DEPLOYMENT_QUERY_URL); } @Test public void testSortOrderParameterOnly() { given().queryParam("sortOrder", "asc") .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) .body("type", equalTo(InvalidRequestException.class.getSimpleName())) .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) .when().get(DEPLOYMENT_QUERY_URL); } @Test public void testDeploymentRetrieval() { InOrder inOrder = Mockito.inOrder(mockedQuery); String queryKey = "Name"; Response response = given().queryParam("nameLike", queryKey) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); // assert query invocation inOrder.verify(mockedQuery).deploymentNameLike(queryKey); inOrder.verify(mockedQuery).list(); String content = response.asString(); List<String> deployments = from(content).getList(""); Assert.assertEquals("There should be one deployment returned.", 1, deployments.size()); Assert.assertNotNull("There should be one deployment returned", deployments.get(0)); String returnedId = from(content).getString("[0].id"); String returnedName = from(content).getString("[0].name"); String returnedSource = from(content).getString("[0].source"); String returnedDeploymentTime = from(content).getString("[0].deploymentTime"); Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, returnedId); Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_NAME, returnedName); Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_SOURCE, returnedSource); Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_TIME, returnedDeploymentTime); } @Test public void testNoParametersQuery() { expect().statusCode(Status.OK.getStatusCode()).when().get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).list(); verifyNoMoreInteractions(mockedQuery); } @Test public void testAdditionalParameters() { Map<String, String> queryParameters = getCompleteQueryParameters(); given().queryParams(queryParameters) .expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); // assert query invocation verify(mockedQuery).deploymentName(queryParameters.get("name")); verify(mockedQuery).deploymentNameLike(queryParameters.get("nameLike")); verify(mockedQuery).deploymentId(queryParameters.get("id")); verify(mockedQuery).deploymentSource(queryParameters.get("source")); verify(mockedQuery).list(); } @Test public void testWithoutSourceParameter() { given() .queryParam("withoutSource", true) .expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); // assert query invocation verify(mockedQuery).deploymentSource(null); verify(mockedQuery).list(); } @Test public void testSourceAndWithoutSource() { given() .queryParam("withoutSource", true) .queryParam("source", "source") .expect() .statusCode(Status.BAD_REQUEST.getStatusCode()) .contentType(ContentType.JSON) .body("type", equalTo(InvalidRequestException.class.getSimpleName())) .body("message", equalTo("The query parameters \"withoutSource\" and \"source\" cannot be used in combination.")) .when() .get(DEPLOYMENT_QUERY_URL); } @Test public void testDeploymentBefore() { given() .queryParam("before", MockProvider.EXAMPLE_DEPLOYMENT_TIME_BEFORE) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).deploymentBefore(any(Date.class)); verify(mockedQuery).list(); } @Test public void testDeploymentAfter() { given() .queryParam("after", MockProvider.EXAMPLE_DEPLOYMENT_TIME_AFTER) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).deploymentAfter(any(Date.class)); verify(mockedQuery).list(); } @Test public void testDeploymentTenantIdList() { List<Deployment> deployments = Arrays.asList( MockProvider.createMockDeployment(MockProvider.EXAMPLE_TENANT_ID), MockProvider.createMockDeployment(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); mockedQuery = setUpMockDeploymentQuery(deployments); Response response = given() .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(2); String returnedTenantId1 = from(content).getString("[0].tenantId"); String returnedTenantId2 = from(content).getString("[1].tenantId"); assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); } @Test public void testDeploymentWithoutTenantId() { Deployment mockDeployment = MockProvider.createMockDeployment(null); mockedQuery = setUpMockDeploymentQuery(Collections.singletonList(mockDeployment)); Response response = given() .queryParam("withoutTenantId", true) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).withoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(1); String returnedTenantId1 = from(content).getString("[0].tenantId"); assertThat(returnedTenantId1).isEqualTo(null); } @Test public void testDeploymentTenantIdIncludeDefinitionsWithoutTenantid() { List<Deployment> mockDeployments = Arrays.asList( MockProvider.createMockDeployment(null), MockProvider.createMockDeployment(MockProvider.EXAMPLE_TENANT_ID)); mockedQuery = setUpMockDeploymentQuery(mockDeployments); Response response = given() .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) .queryParam("includeDeploymentsWithoutTenantId", true) .then().expect() .statusCode(Status.OK.getStatusCode()) .when() .get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); verify(mockedQuery).includeDeploymentsWithoutTenantId(); verify(mockedQuery).list(); String content = response.asString(); List<String> definitions = from(content).getList(""); assertThat(definitions).hasSize(2); String returnedTenantId1 = from(content).getString("[0].tenantId"); String returnedTenantId2 = from(content).getString("[1].tenantId"); assertThat(returnedTenantId1).isEqualTo(null); assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); } private Map<String, String> getCompleteQueryParameters() { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("id", "depId"); parameters.put("name", "name"); parameters.put("nameLike", "nameLike"); parameters.put("source", "source"); return parameters; } @Test public void testSortingParameters() { InOrder inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("id", "asc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentId(); inOrder.verify(mockedQuery).asc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("id", "desc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentId(); inOrder.verify(mockedQuery).desc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("deploymentTime", "asc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentTime(); inOrder.verify(mockedQuery).asc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("deploymentTime", "desc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentTime(); inOrder.verify(mockedQuery).desc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("name", "asc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentName(); inOrder.verify(mockedQuery).asc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("name", "desc", Status.OK); inOrder.verify(mockedQuery).orderByDeploymentName(); inOrder.verify(mockedQuery).desc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("tenantId", "asc", Status.OK); inOrder.verify(mockedQuery).orderByTenantId(); inOrder.verify(mockedQuery).asc(); inOrder = Mockito.inOrder(mockedQuery); executeAndVerifySuccessfulSorting("tenantId", "desc", Status.OK); inOrder.verify(mockedQuery).orderByTenantId(); inOrder.verify(mockedQuery).desc(); } @Test public void testSuccessfulPagination() { int firstResult = 0; int maxResults = 10; given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).listPage(firstResult, maxResults); } /** * If parameter "firstResult" is missing, we expect 0 as default. */ @Test public void testMissingFirstResultParameter() { int maxResults = 10; given().queryParam("maxResults", maxResults) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).listPage(0, maxResults); } /** * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. */ @Test public void testMissingMaxResultsParameter() { int firstResult = 10; given().queryParam("firstResult", firstResult) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(DEPLOYMENT_QUERY_URL); verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); } @Test public void testQueryCount() { expect().statusCode(Status.OK.getStatusCode()) .body("count", equalTo(1)) .when().get(DEPLOYMENT_COUNT_QUERY_URL); verify(mockedQuery).count(); } }
apache-2.0
smarthi/nd4j
nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/linalg/jcublas/JCublasBackend.java
2294
/*- * * * Copyright 2015 Skymind,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.nd4j.linalg.jcublas; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.cublas; import org.bytedeco.javacpp.cuda; import org.nd4j.linalg.factory.Nd4jBackend; import org.nd4j.linalg.io.ClassPathResource; import org.nd4j.linalg.io.Resource; import org.nd4j.linalg.jcublas.complex.JCublasComplexNDArray; /** * */ public class JCublasBackend extends Nd4jBackend { private final static String LINALG_PROPS = "/nd4j-jcublas.properties"; @Override public boolean isAvailable() { try { if (!canRun()) return false; } catch (Throwable e) { while (e.getCause() != null) { e = e.getCause(); } throw new RuntimeException(e); } return true; } @Override public boolean canRun() { int[] count = { 0 }; cuda.cudaGetDeviceCount(count); if (count[0] <= 0) { throw new RuntimeException("No CUDA devices were found in system"); } Loader.load(cublas.class); return true; } @Override public boolean allowsOrder() { return false; } @Override public int getPriority() { return BACKEND_PRIORITY_GPU; } @Override public Resource getConfigurationResource() { return new ClassPathResource(LINALG_PROPS, JCublasBackend.class.getClassLoader()); } @Override public Class getNDArrayClass() { return JCublasNDArray.class; } @Override public Class getComplexNDArrayClass() { return JCublasComplexNDArray.class; } }
apache-2.0
shun634501730/java_source_cn
src_en/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java
4962
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * 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 com.sun.org.apache.xml.internal.security.utils; import javax.xml.XMLConstants; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactoryConfigurationException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * An implementation for XPath evaluation that uses the JDK API. */ public class JDKXPathAPI implements XPathAPI { private XPathFactory xpf; private String xpathStr; private XPathExpression xpathExpression; /** * Use an XPath string to select a nodelist. * XPath namespace prefixes are resolved from the namespaceNode. * * @param contextNode The node to start searching from. * @param xpathnode * @param str * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. * @return A NodeIterator, should never be null. * * @throws TransformerException */ public NodeList selectNodeList( Node contextNode, Node xpathnode, String str, Node namespaceNode ) throws TransformerException { if (!str.equals(xpathStr) || xpathExpression == null) { if (xpf == null) { xpf = XPathFactory.newInstance(); try { xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (XPathFactoryConfigurationException ex) { throw new TransformerException("empty", ex); } } XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); xpathStr = str; try { xpathExpression = xpath.compile(xpathStr); } catch (XPathExpressionException ex) { throw new TransformerException("empty", ex); } } try { return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET); } catch (XPathExpressionException ex) { throw new TransformerException("empty", ex); } } /** * Evaluate an XPath string and return true if the output is to be included or not. * @param contextNode The node to start searching from. * @param xpathnode The XPath node * @param str The XPath expression * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. */ public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) throws TransformerException { if (!str.equals(xpathStr) || xpathExpression == null) { if (xpf == null) { xpf = XPathFactory.newInstance(); try { xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (XPathFactoryConfigurationException ex) { throw new TransformerException("empty", ex); } } XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); xpathStr = str; try { xpathExpression = xpath.compile(xpathStr); } catch (XPathExpressionException ex) { throw new TransformerException("empty", ex); } } try { Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); return result.booleanValue(); } catch (XPathExpressionException ex) { throw new TransformerException("empty", ex); } } /** * Clear any context information from this object */ public void clear() { xpathStr = null; xpathExpression = null; xpf = null; } }
apache-2.0
jorgemoralespou/rtgov
modules/event-processor-network/epn-core/src/main/java/org/overlord/rtgov/epn/Channel.java
978
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.epn; /** * This interface provides the channel through which a * set of events will be sent to another destination. * */ public interface Channel { /** * This method closes the channel. * * @throws Exception Failed to close the channel */ public void close() throws Exception; }
apache-2.0
dbmalkovsky/flowable-engine
modules/flowable-form-engine/src/main/java/org/flowable/form/engine/FlowableFormValidationException.java
1151
/* 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.flowable.form.engine; import org.flowable.common.engine.api.FlowableIllegalArgumentException; /** * An exception indicating that a validation of a form field value resulted in an error. * * @author Tijs Rademakers */ public class FlowableFormValidationException extends FlowableIllegalArgumentException { private static final long serialVersionUID = 1L; public FlowableFormValidationException(String message) { super(message); } public FlowableFormValidationException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
stoksey69/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201405/DateTime.java
8327
/** * DateTime.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201405; /** * Represents a date combined with the time of day. */ public class DateTime implements java.io.Serializable { private com.google.api.ads.dfp.axis.v201405.Date date; private java.lang.Integer hour; private java.lang.Integer minute; private java.lang.Integer second; private java.lang.String timeZoneID; public DateTime() { } public DateTime( com.google.api.ads.dfp.axis.v201405.Date date, java.lang.Integer hour, java.lang.Integer minute, java.lang.Integer second, java.lang.String timeZoneID) { this.date = date; this.hour = hour; this.minute = minute; this.second = second; this.timeZoneID = timeZoneID; } /** * Gets the date value for this DateTime. * * @return date */ public com.google.api.ads.dfp.axis.v201405.Date getDate() { return date; } /** * Sets the date value for this DateTime. * * @param date */ public void setDate(com.google.api.ads.dfp.axis.v201405.Date date) { this.date = date; } /** * Gets the hour value for this DateTime. * * @return hour */ public java.lang.Integer getHour() { return hour; } /** * Sets the hour value for this DateTime. * * @param hour */ public void setHour(java.lang.Integer hour) { this.hour = hour; } /** * Gets the minute value for this DateTime. * * @return minute */ public java.lang.Integer getMinute() { return minute; } /** * Sets the minute value for this DateTime. * * @param minute */ public void setMinute(java.lang.Integer minute) { this.minute = minute; } /** * Gets the second value for this DateTime. * * @return second */ public java.lang.Integer getSecond() { return second; } /** * Sets the second value for this DateTime. * * @param second */ public void setSecond(java.lang.Integer second) { this.second = second; } /** * Gets the timeZoneID value for this DateTime. * * @return timeZoneID */ public java.lang.String getTimeZoneID() { return timeZoneID; } /** * Sets the timeZoneID value for this DateTime. * * @param timeZoneID */ public void setTimeZoneID(java.lang.String timeZoneID) { this.timeZoneID = timeZoneID; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof DateTime)) return false; DateTime other = (DateTime) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.date==null && other.getDate()==null) || (this.date!=null && this.date.equals(other.getDate()))) && ((this.hour==null && other.getHour()==null) || (this.hour!=null && this.hour.equals(other.getHour()))) && ((this.minute==null && other.getMinute()==null) || (this.minute!=null && this.minute.equals(other.getMinute()))) && ((this.second==null && other.getSecond()==null) || (this.second!=null && this.second.equals(other.getSecond()))) && ((this.timeZoneID==null && other.getTimeZoneID()==null) || (this.timeZoneID!=null && this.timeZoneID.equals(other.getTimeZoneID()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getDate() != null) { _hashCode += getDate().hashCode(); } if (getHour() != null) { _hashCode += getHour().hashCode(); } if (getMinute() != null) { _hashCode += getMinute().hashCode(); } if (getSecond() != null) { _hashCode += getSecond().hashCode(); } if (getTimeZoneID() != null) { _hashCode += getTimeZoneID().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(DateTime.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "DateTime")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("date"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "date")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "Date")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("hour"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "hour")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("minute"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "minute")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("second"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "second")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("timeZoneID"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201405", "timeZoneID")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
awislowski/elasticsearch
modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/MustacheScriptEngineService.java
6955
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.script.mustache; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.SpecialPermission; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.io.FastStringReader; import org.elasticsearch.common.io.UTF8StreamWriter; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.GeneralScriptException; import org.elasticsearch.script.ScriptEngineService; import org.elasticsearch.script.SearchScript; import org.elasticsearch.search.lookup.SearchLookup; import java.io.Reader; import java.lang.ref.SoftReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.Map; /** * Main entry point handling template registration, compilation and * execution. * * Template handling is based on Mustache. Template handling is a two step * process: First compile the string representing the template, the resulting * {@link Mustache} object can then be re-used for subsequent executions. */ public final class MustacheScriptEngineService extends AbstractComponent implements ScriptEngineService { public static final String NAME = "mustache"; static final String CONTENT_TYPE_PARAM = "content_type"; static final String JSON_CONTENT_TYPE = "application/json"; static final String PLAIN_TEXT_CONTENT_TYPE = "text/plain"; /** Thread local UTF8StreamWriter to store template execution results in, thread local to save object creation.*/ private static ThreadLocal<SoftReference<UTF8StreamWriter>> utf8StreamWriter = new ThreadLocal<>(); /** If exists, reset and return, otherwise create, reset and return a writer.*/ private static UTF8StreamWriter utf8StreamWriter() { SoftReference<UTF8StreamWriter> ref = utf8StreamWriter.get(); UTF8StreamWriter writer = (ref == null) ? null : ref.get(); if (writer == null) { writer = new UTF8StreamWriter(1024 * 4); utf8StreamWriter.set(new SoftReference<>(writer)); } writer.reset(); return writer; } /** * @param settings automatically wired by Guice. * */ public MustacheScriptEngineService(Settings settings) { super(settings); } /** * Compile a template string to (in this case) a Mustache object than can * later be re-used for execution to fill in missing parameter values. * * @param templateSource * a string representing the template to compile. * @return a compiled template object for later execution. * */ @Override public Object compile(String templateName, String templateSource, Map<String, String> params) { final MustacheFactory factory = new CustomMustacheFactory(isJsonEscapingEnabled(params)); Reader reader = new FastStringReader(templateSource); return factory.compile(reader, "query-template"); } private boolean isJsonEscapingEnabled(Map<String, String> params) { return JSON_CONTENT_TYPE.equals(params.getOrDefault(CONTENT_TYPE_PARAM, JSON_CONTENT_TYPE)); } @Override public String getType() { return NAME; } @Override public String getExtension() { return NAME; } @Override public ExecutableScript executable(CompiledScript compiledScript, @Nullable Map<String, Object> vars) { return new MustacheExecutableScript(compiledScript, vars); } @Override public SearchScript search(CompiledScript compiledScript, SearchLookup lookup, @Nullable Map<String, Object> vars) { throw new UnsupportedOperationException(); } @Override public void close() { // Nothing to do here } // permission checked before doing crazy reflection static final SpecialPermission SPECIAL_PERMISSION = new SpecialPermission(); /** * Used at query execution time by script service in order to execute a query template. * */ private class MustacheExecutableScript implements ExecutableScript { /** Compiled template object wrapper. */ private CompiledScript template; /** Parameters to fill above object with. */ private Map<String, Object> vars; /** * @param template the compiled template object wrapper * @param vars the parameters to fill above object with **/ public MustacheExecutableScript(CompiledScript template, Map<String, Object> vars) { this.template = template; this.vars = vars == null ? Collections.<String, Object>emptyMap() : vars; } @Override public void setNextVar(String name, Object value) { this.vars.put(name, value); } @Override public Object run() { final BytesStreamOutput result = new BytesStreamOutput(); try (UTF8StreamWriter writer = utf8StreamWriter().setOutput(result)) { // crazy reflection here SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(SPECIAL_PERMISSION); } AccessController.doPrivileged((PrivilegedAction<Void>) () -> { ((Mustache) template.compiled()).execute(writer, vars); return null; }); } catch (Exception e) { logger.error((Supplier<?>) () -> new ParameterizedMessage("Error running {}", template), e); throw new GeneralScriptException("Error running " + template, e); } return result.bytes(); } } @Override public boolean isInlineScriptEnabled() { return true; } }
apache-2.0
Apelon-VA/va-isaac-gui
import-export/src/main/java/org/w3/_1999/xhtml/Scope.java
1583
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.09.30 at 06:15:10 PM PDT // package org.w3._1999.xhtml; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Scope. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="Scope"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}token"> * &lt;enumeration value="row"/> * &lt;enumeration value="col"/> * &lt;enumeration value="rowgroup"/> * &lt;enumeration value="colgroup"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "Scope") @XmlEnum public enum Scope { @XmlEnumValue("row") ROW("row"), @XmlEnumValue("col") COL("col"), @XmlEnumValue("rowgroup") ROWGROUP("rowgroup"), @XmlEnumValue("colgroup") COLGROUP("colgroup"); private final String value; Scope(String v) { value = v; } public String value() { return value; } public static Scope fromValue(String v) { for (Scope c: Scope.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
apache-2.0
mirkosertic/Bytecoder
classlib/java.base/src/main/resources/META-INF/modules/java.base/classes/java/lang/LayerInstantiationException.java
2546
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; /** * Thrown when creating a {@linkplain ModuleLayer module layer} fails. * * @see ModuleLayer * @since 9 */ public class LayerInstantiationException extends RuntimeException { @java.io.Serial private static final long serialVersionUID = -906239691613568347L; /** * Constructs a {@code LayerInstantiationException} with no detail message. */ public LayerInstantiationException() { } /** * Constructs a {@code LayerInstantiationException} with the given detail * message. * * @param msg * The detail message; can be {@code null} */ public LayerInstantiationException(String msg) { super(msg); } /** * Constructs a {@code LayerInstantiationException} with the given cause. * * @param cause * The cause; can be {@code null} */ public LayerInstantiationException(Throwable cause) { super(cause); } /** * Constructs a {@code LayerInstantiationException} with the given detail * message and cause. * * @param msg * The detail message; can be {@code null} * @param cause * The cause; can be {@code null} */ public LayerInstantiationException(String msg, Throwable cause) { super(msg, cause); } }
apache-2.0
apache/jmeter
src/protocol/jms/src/main/java/org/apache/jmeter/protocol/jms/sampler/PublisherSampler.java
19666
/* * 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.jmeter.protocol.jms.sampler; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.lang.reflect.Modifier; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import javax.jms.DeliveryMode; import javax.jms.JMSException; import javax.jms.Message; import javax.naming.NamingException; import org.apache.commons.io.IOUtils; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.protocol.jms.Utils; import org.apache.jmeter.protocol.jms.client.ClientPool; import org.apache.jmeter.protocol.jms.client.InitialContextFactory; import org.apache.jmeter.protocol.jms.client.Publisher; import org.apache.jmeter.protocol.jms.control.gui.JMSPublisherGui; import org.apache.jmeter.protocol.jms.sampler.render.MessageRenderer; import org.apache.jmeter.protocol.jms.sampler.render.Renderers; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.TestStateListener; import org.apache.jmeter.testelement.property.TestElementProperty; import org.apache.jmeter.util.JMeterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * This class implements the JMS Publisher sampler. */ public class PublisherSampler extends BaseJMSSampler implements TestStateListener { /** Encoding value to sent data as is (no variabilisation) **/ public static final String RAW_DATA = "<RAW>"; /** * Encoding value to sent parsed data but read with default system encoding **/ public static final String DEFAULT_ENCODING = "<DEFAULT>"; /** Constant for system default encodings **/ public static final Set<String> NO_ENCODING = Collections .unmodifiableSet(new LinkedHashSet<>(Arrays.asList(RAW_DATA, DEFAULT_ENCODING))); /** * Init available encoding using constants, then JVM standard ones * @return Array of String containing supported encodings */ public static String[] getSupportedEncodings() { // Only get JVM standard charsets return Stream.concat( NO_ENCODING.stream(), Arrays.stream(StandardCharsets.class.getDeclaredFields()) .filter(f -> Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) && f.getType() == Charset.class) .map(f -> { try { return (Charset) f.get(null); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } }) .map(Charset::displayName) .sorted()) .toArray(String[]::new); } private static final long serialVersionUID = 233L; private static final Logger log = LoggerFactory.getLogger(PublisherSampler.class); // ++ These are JMX file names and must not be changed private static final String INPUT_FILE = "jms.input_file"; //$NON-NLS-1$ private static final String RANDOM_PATH = "jms.random_path"; //$NON-NLS-1$ private static final String TEXT_MSG = "jms.text_message"; //$NON-NLS-1$ private static final String CONFIG_CHOICE = "jms.config_choice"; //$NON-NLS-1$ private static final String MESSAGE_CHOICE = "jms.config_msg_type"; //$NON-NLS-1$ private static final String NON_PERSISTENT_DELIVERY = "jms.non_persistent"; //$NON-NLS-1$ private static final String JMS_PROPERTIES = "jms.jmsProperties"; // $NON-NLS-1$ private static final String JMS_PRIORITY = "jms.priority"; // $NON-NLS-1$ private static final String JMS_EXPIRATION = "jms.expiration"; // $NON-NLS-1$ private static final String JMS_FILE_ENCODING = "jms.file_encoding"; // $NON-NLS-1$ /** File extensions for text files **/ private static final String[] TEXT_FILE_EXTS = { ".txt", ".obj" }; /** File extensions for binary files **/ private static final String[] BIN_FILE_EXTS = { ".dat" }; // -- // Does not need to be synch. because it is only accessed from the sampler // thread // The ClientPool does access it in a different thread, but ClientPool is // fully synch. private transient Publisher publisher = null; private static final FileServer FSERVER = FileServer.getFileServer(); /** File cache handler **/ private Cache<Object, Object> fileCache = null; /** * the implementation calls testStarted() without any parameters. */ @Override public void testStarted(String test) { testStarted(); } /** * the implementation calls testEnded() without any parameters. */ @Override public void testEnded(String host) { testEnded(); } /** * endTest cleans up the client */ @Override public void testEnded() { log.debug("PublisherSampler.testEnded called"); ClientPool.clearClient(); InitialContextFactory.close(); } @Override public void testStarted() { } /** * initialize the Publisher client. * * @throws JMSException * @throws NamingException * */ private void initClient() throws JMSException, NamingException { configureIsReconnectErrorCode(); publisher = new Publisher(getUseJNDIPropertiesAsBoolean(), getJNDIInitialContextFactory(), getProviderUrl(), getConnectionFactory(), getDestination(), isUseAuth(), getUsername(), getPassword(), isDestinationStatic()); ClientPool.addClient(publisher); log.debug("PublisherSampler.initClient called"); } /** * The implementation will publish n messages within a for loop. Once n * messages are published, it sets the attributes of SampleResult. * * @return the populated sample result */ @Override public SampleResult sample() { String configChoice = getConfigChoice(); if (fileCache == null) { fileCache = buildCache(configChoice); } SampleResult result = new SampleResult(); result.setSampleLabel(getName()); result.setSuccessful(false); // Assume it will fail result.setResponseCode("000"); // ditto $NON-NLS-1$ if (publisher == null) { try { initClient(); } catch (JMSException | NamingException e) { result.sampleStart(); result.sampleEnd(); handleError(result, e, false); return result; } } StringBuilder buffer = new StringBuilder(); StringBuilder propBuffer = new StringBuilder(); int loop = getIterationCount(); result.sampleStart(); String type = getMessageChoice(); try { Map<String, Object> msgProperties = getJMSProperties().getJmsPropertysAsMap(); int deliveryMode = getUseNonPersistentDelivery() ? DeliveryMode.NON_PERSISTENT : DeliveryMode.PERSISTENT; int priority = Integer.parseInt(getPriority()); long expiration = Long.parseLong(getExpiration()); for (int idx = 0; idx < loop; idx++) { Message msg; if (JMSPublisherGui.TEXT_MSG_RSC.equals(type)) { String tmsg = getRenderedContent(String.class, TEXT_FILE_EXTS); msg = publisher.publish(tmsg, getDestination(), msgProperties, deliveryMode, priority, expiration); buffer.append(tmsg); } else if (JMSPublisherGui.MAP_MSG_RSC.equals(type)) { @SuppressWarnings("unchecked") Map<String, Object> map = getRenderedContent(Map.class, TEXT_FILE_EXTS); msg = publisher.publish(map, getDestination(), msgProperties, deliveryMode, priority, expiration); } else if (JMSPublisherGui.OBJECT_MSG_RSC.equals(type)) { Serializable omsg = getRenderedContent(Serializable.class, TEXT_FILE_EXTS); msg = publisher.publish(omsg, getDestination(), msgProperties, deliveryMode, priority, expiration); } else if (JMSPublisherGui.BYTES_MSG_RSC.equals(type)) { byte[] bmsg = getRenderedContent(byte[].class, BIN_FILE_EXTS); msg = publisher.publish(bmsg, getDestination(), msgProperties, deliveryMode, priority, expiration); } else { throw new JMSException(type + " is not recognised"); } Utils.messageProperties(propBuffer, msg); } result.setResponseCodeOK(); result.setResponseMessage(loop + " messages published"); result.setSuccessful(true); result.setSamplerData(buffer.toString()); result.setSampleCount(loop); result.setRequestHeaders(propBuffer.toString()); } catch (JMSException e) { handleError(result, e, true); } catch (Exception e) { handleError(result, e, false); } finally { result.sampleEnd(); } return result; } /** * Fills in result and decide whether to reconnect or not depending on * checkForReconnect and underlying {@link JMSException#getErrorCode()} * * @param result * {@link SampleResult} * @param e * {@link Exception} * @param checkForReconnect * if true and exception is a {@link JMSException} */ private void handleError(SampleResult result, Exception e, boolean checkForReconnect) { result.setSuccessful(false); result.setResponseMessage(e.toString()); if (e instanceof JMSException) { JMSException jms = (JMSException) e; String errorCode = Optional.ofNullable(jms.getErrorCode()).orElse(""); if (checkForReconnect && publisher != null && getIsReconnectErrorCode().test(errorCode)) { ClientPool.removeClient(publisher); IOUtils.closeQuietly(publisher, null); publisher = null; } result.setResponseCode(errorCode); } StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); // NOSONAR We're getting it // to put it in ResponseData result.setResponseData(writer.toString(), "UTF-8"); } protected static Cache<Object, Object> buildCache(String configChoice) { Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder(); switch (configChoice) { case JMSPublisherGui.USE_FILE_RSC: cacheBuilder.maximumSize(1); break; default: cacheBuilder.expireAfterWrite(0, TimeUnit.MILLISECONDS).maximumSize(0); } return cacheBuilder.build(); } /** Gets file path to use **/ private String getFilePath(String... ext) { switch (getConfigChoice()) { case JMSPublisherGui.USE_FILE_RSC: return getInputFile(); case JMSPublisherGui.USE_RANDOM_RSC: return FSERVER.getRandomFile(getRandomPath(), ext).getAbsolutePath(); default: throw new IllegalArgumentException("Type of input not handled:" + getConfigChoice()); } } /** * Look-up renderer and get appropriate value * * @param type * Message type to render * @param fileExts * File extensions for directory mode. **/ private <T> T getRenderedContent(Class<T> type, String[] fileExts) { MessageRenderer<T> renderer = Renderers.getInstance(type); if (getConfigChoice().equals(JMSPublisherGui.USE_TEXT_RSC)) { return renderer.getValueFromText(getTextMessage()); } else { return renderer.getValueFromFile(getFilePath(fileExts), getFileEncoding(), !isRaw(), fileCache); } } /** * Specified if value must be parsed or not. * * @return <code>true</code> if value must be sent as-is. */ private boolean isRaw() { return RAW_DATA.equals(getFileEncoding()); } // ------------- get/set properties ----------------------// /** * set the source of the message * * @param choice * source of the messages. One of * {@link JMSPublisherGui#USE_FILE_RSC}, * {@link JMSPublisherGui#USE_RANDOM_RSC} or * JMSPublisherGui#USE_TEXT_RSC */ public void setConfigChoice(String choice) { setProperty(CONFIG_CHOICE, choice); } // These static variables are only used to convert existing files private static final String USE_FILE_LOCALNAME = JMeterUtils.getResString(JMSPublisherGui.USE_FILE_RSC); private static final String USE_RANDOM_LOCALNAME = JMeterUtils.getResString(JMSPublisherGui.USE_RANDOM_RSC); /** * return the source of the message Converts from old JMX files which used * the local language string * * @return source of the messages */ public String getConfigChoice() { // Allow for the old JMX file which used the local language string String config = getPropertyAsString(CONFIG_CHOICE); if (config.equals(USE_FILE_LOCALNAME) || config.equals(JMSPublisherGui.USE_FILE_RSC)) { return JMSPublisherGui.USE_FILE_RSC; } if (config.equals(USE_RANDOM_LOCALNAME) || config.equals(JMSPublisherGui.USE_RANDOM_RSC)) { return JMSPublisherGui.USE_RANDOM_RSC; } return config; // will be the 3rd option, which is not checked // specifically } /** * set the type of the message * * @param choice * type of the message (Text, Object, Map) */ public void setMessageChoice(String choice) { setProperty(MESSAGE_CHOICE, choice); } /** * @return the type of the message (Text, Object, Map) * */ public String getMessageChoice() { return getPropertyAsString(MESSAGE_CHOICE); } /** * set the input file for the publisher * * @param file * input file for the publisher */ public void setInputFile(String file) { setProperty(INPUT_FILE, file); } /** * @return the path of the input file * */ public String getInputFile() { return getPropertyAsString(INPUT_FILE); } /** * set the random path for the messages * * @param path * random path for the messages */ public void setRandomPath(String path) { setProperty(RANDOM_PATH, path); } /** * @return the random path for messages * */ public String getRandomPath() { return getPropertyAsString(RANDOM_PATH); } /** * set the text for the message * * @param message * text for the message */ public void setTextMessage(String message) { setProperty(TEXT_MSG, message); } /** * @return the text for the message * */ public String getTextMessage() { return getPropertyAsString(TEXT_MSG); } public String getExpiration() { String expiration = getPropertyAsString(JMS_EXPIRATION); if (expiration.length() == 0) { return Utils.DEFAULT_NO_EXPIRY; } else { return expiration; } } public String getPriority() { String priority = getPropertyAsString(JMS_PRIORITY); if (priority.length() == 0) { return Utils.DEFAULT_PRIORITY_4; } else { return priority; } } public void setPriority(String s) { // Bug 59173 if (Utils.DEFAULT_PRIORITY_4.equals(s)) { s = ""; // $NON-NLS-1$ make sure the default is not saved explicitly } setProperty(JMS_PRIORITY, s); // always need to save the field } public void setExpiration(String s) { // Bug 59173 if (Utils.DEFAULT_NO_EXPIRY.equals(s)) { s = ""; // $NON-NLS-1$ make sure the default is not saved explicitly } setProperty(JMS_EXPIRATION, s); // always need to save the field } /** * @param value * boolean use NON_PERSISTENT */ public void setUseNonPersistentDelivery(boolean value) { setProperty(NON_PERSISTENT_DELIVERY, value, false); } /** * @return true if NON_PERSISTENT delivery must be used */ public boolean getUseNonPersistentDelivery() { return getPropertyAsBoolean(NON_PERSISTENT_DELIVERY, false); } /** * @return {@link JMSProperties} JMS Properties */ public JMSProperties getJMSProperties() { Object o = getProperty(JMS_PROPERTIES).getObjectValue(); JMSProperties jmsProperties = null; // Backward compatibility with versions <= 2.10 if (o instanceof Arguments) { jmsProperties = Utils.convertArgumentsToJmsProperties((Arguments) o); } else { jmsProperties = (JMSProperties) o; } if (jmsProperties == null) { jmsProperties = new JMSProperties(); setJMSProperties(jmsProperties); } return jmsProperties; } /** * @param jmsProperties * JMS Properties */ public void setJMSProperties(JMSProperties jmsProperties) { setProperty(new TestElementProperty(JMS_PROPERTIES, jmsProperties)); } /** * Gets file encoding to use. If {@link #RAW_DATA}, content isn't parsed. * * @return File encoding. * @see #RAW_DATA * @see #DEFAULT_ENCODING * @see #getSupportedEncodings() */ public String getFileEncoding() { return getPropertyAsString(JMS_FILE_ENCODING, RAW_DATA); } /** * Sets file encoding to use. If {@link #RAW_DATA}, content isn't parsed. * * @param fileEncoding * File encoding. * @see #RAW_DATA * @see #DEFAULT_ENCODING * @see #getSupportedEncodings() */ public void setFileEncoding(String fileEncoding) { setProperty(JMS_FILE_ENCODING, fileEncoding, RAW_DATA); } }
apache-2.0
mswiderski/drools
drools-core/src/main/java/org/drools/spi/AcceptsReadAccessor.java
747
/* * Copyright 2010 JBoss 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.drools.spi; public interface AcceptsReadAccessor extends Acceptor { void setReadAccessor(InternalReadAccessor readAccessor); }
apache-2.0
hxquangnhat/PIG-ROLLUP-MRCUBE
src/org/apache/pig/data/InternalMap.java
1341
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.data; import java.util.HashMap; /** * This class is an empty extension of Map<Object, Object>. It only * exists so that DataType.findType() can distinguish an internal map * type that maps object to object from an external map type that * is string to object. * */ public class InternalMap extends HashMap<Object, Object> { private static final long serialVersionUID = 1L; public InternalMap() { super(); } public InternalMap(int size) { super(size); } }
apache-2.0
wildfly/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/DelayInterceptor2.java
1966
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.cluster.failover; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; public class DelayInterceptor2 implements Interceptor { private volatile boolean loseResponse = true; private final CountDownLatch latch = new CountDownLatch(1); public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException { if (packet.getType() == PacketImpl.NULL_RESPONSE && loseResponse) { // Lose the response from the commit - only lose the first one loseResponse = false; latch.countDown(); return false; } else { return true; } } public boolean await() throws InterruptedException { return latch.await(10, TimeUnit.SECONDS); } }
apache-2.0
apache/drill
contrib/storage-phoenix/src/main/java/org/apache/drill/exec/store/phoenix/PhoenixReader.java
9664
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.store.phoenix; import java.sql.Array; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.util.Map; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.exec.physical.resultSet.ResultSetLoader; import org.apache.drill.exec.physical.resultSet.RowSetLoader; import org.apache.drill.exec.record.metadata.SchemaBuilder; import org.apache.drill.exec.vector.accessor.ColumnWriter; import org.apache.drill.exec.vector.accessor.ScalarWriter; import org.apache.drill.exec.vector.accessor.writer.ScalarArrayWriter; import org.apache.drill.shaded.guava.com.google.common.collect.Maps; public class PhoenixReader implements AutoCloseable { private final RowSetLoader writer; private final ColumnDefn[] columns; private final ResultSet results; public PhoenixReader(ResultSetLoader loader, ColumnDefn[] columns, ResultSet results) { this.writer = loader.writer(); this.columns = columns; this.results = results; } public RowSetLoader getStorage() { return writer; } public long getRowCount() { return writer.loader().totalRowCount(); } public int getBatchCount() { return writer.loader().batchCount(); } /** * Fetch and process one row. * @return return true if one row is processed, return false if there is no next row. * @throws SQLException */ public boolean processRow() throws SQLException { if (results.next()) { writer.start(); for (ColumnDefn columnDefn : columns) { columnDefn.load(results); } writer.save(); return true; } return false; } protected static final Map<Integer, MinorType> COLUMN_TYPE_MAP = Maps.newHashMap(); static { // text COLUMN_TYPE_MAP.put(Types.VARCHAR, MinorType.VARCHAR); COLUMN_TYPE_MAP.put(Types.CHAR, MinorType.VARCHAR); // numbers COLUMN_TYPE_MAP.put(Types.BIGINT, MinorType.BIGINT); COLUMN_TYPE_MAP.put(Types.INTEGER, MinorType.INT); COLUMN_TYPE_MAP.put(Types.SMALLINT, MinorType.INT); COLUMN_TYPE_MAP.put(Types.TINYINT, MinorType.INT); COLUMN_TYPE_MAP.put(Types.DOUBLE, MinorType.FLOAT8); COLUMN_TYPE_MAP.put(Types.FLOAT, MinorType.FLOAT4); COLUMN_TYPE_MAP.put(Types.DECIMAL, MinorType.VARDECIMAL); // time COLUMN_TYPE_MAP.put(Types.DATE, MinorType.DATE); COLUMN_TYPE_MAP.put(Types.TIME, MinorType.TIME); COLUMN_TYPE_MAP.put(Types.TIMESTAMP, MinorType.TIMESTAMP); // binary COLUMN_TYPE_MAP.put(Types.BINARY, MinorType.VARBINARY); // Raw fixed length byte array. Mapped to byte[]. COLUMN_TYPE_MAP.put(Types.VARBINARY, MinorType.VARBINARY); // Raw variable length byte array. // boolean COLUMN_TYPE_MAP.put(Types.BOOLEAN, MinorType.BIT); } @Override public void close() throws Exception { results.close(); } protected abstract static class ColumnDefn { final String name; final int index; final int sqlType; ColumnWriter writer; public String getName() { return name; } public int getIndex() { return index; } public int getSqlType() { return sqlType; } public ColumnDefn(String name, int index, int sqlType) { this.name = name; this.index = index; this.sqlType = sqlType; } public void define(SchemaBuilder builder) { builder.addNullable(getName(), COLUMN_TYPE_MAP.get(getSqlType())); } public void bind(RowSetLoader loader) { writer = loader.scalar(getName()); } public abstract void load(ResultSet row) throws SQLException; } protected static class GenericDefn extends ColumnDefn { public GenericDefn(String name, int index, int sqlType) { super(name, index, sqlType); } @Override public void load(ResultSet row) throws SQLException { Object value = row.getObject(index); if (value != null) { writer.setObject(value); } } } protected static class GenericDateDefn extends GenericDefn { public GenericDateDefn(String name, int index, int sqlType) { super(name, index, sqlType); } @Override public void load(ResultSet row) throws SQLException { Object value = row.getObject(index); if (value != null) { LocalDate date = ((Date) value).toLocalDate(); // java.sql.Date ((ScalarWriter) writer).setDate(date); } } } protected static class GenericTimeDefn extends GenericDefn { public GenericTimeDefn(String name, int index, int sqlType) { super(name, index, sqlType); } @Override public void load(ResultSet row) throws SQLException { Object value = row.getObject(index); if (value != null) { LocalTime time = ((Time) value).toLocalTime(); // java.sql.Time ((ScalarWriter) writer).setTime(time); } } } protected static class GenericTimestampDefn extends GenericDefn { public GenericTimestampDefn(String name, int index, int sqlType) { super(name, index, sqlType); } @Override public void load(ResultSet row) throws SQLException { Object value = row.getObject(index); if (value != null) { Instant ts = ((Timestamp) value).toInstant(); // java.sql.Timestamp ((ScalarWriter) writer).setTimestamp(ts); } } } protected static abstract class ArrayDefn extends ColumnDefn { static final String VARCHAR = "VARCHAR ARRAY"; static final String CHAR = "CHAR ARRAY"; static final String BIGINT = "BIGINT ARRAY"; static final String INTEGER = "INTEGER ARRAY"; static final String DOUBLE = "DOUBLE ARRAY"; static final String FLOAT = "FLOAT ARRAY"; static final String SMALLINT = "SMALLINT ARRAY"; static final String TINYINT = "TINYINT ARRAY"; static final String BOOLEAN = "BOOLEAN ARRAY"; final String baseType; public ArrayDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType); this.baseType = baseType; } @Override public void bind(RowSetLoader loader) { writer = loader.array(getName()); } @Override public void load(ResultSet row) throws SQLException { Array array = row.getArray(index); if (array != null && array.getArray() != null) { Object[] values = (Object[]) array.getArray(); ((ScalarArrayWriter) writer).setObjectArray(values); } } } protected static class ArrayVarcharDefn extends ArrayDefn { public ArrayVarcharDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.VARCHAR); } } protected static class ArrayBigintDefn extends ArrayDefn { public ArrayBigintDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.BIGINT); } } protected static class ArrayIntegerDefn extends ArrayDefn { public ArrayIntegerDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.INT); } } protected static class ArraySmallintDefn extends ArrayDefn { public ArraySmallintDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.SMALLINT); } } protected static class ArrayTinyintDefn extends ArrayDefn { public ArrayTinyintDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.TINYINT); } } protected static class ArrayDoubleDefn extends ArrayDefn { public ArrayDoubleDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.FLOAT8); } } protected static class ArrayBooleanDefn extends ArrayDefn { public ArrayBooleanDefn(String name, int index, int sqlType, String baseType) { super(name, index, sqlType, baseType); } @Override public void define(SchemaBuilder builder) { builder.addArray(getName(), MinorType.BIT); } } }
apache-2.0
jamesnetherton/wildfly-camel
itests/standalone/basic/src/test/java/org/wildfly/camel/test/quickfix/subA/CountDownLatchDecrementer.java
1509
/** * 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.wildfly.camel.test.quickfix.subA; import java.util.concurrent.CountDownLatch; import org.apache.camel.Exchange; import org.apache.camel.Handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CountDownLatchDecrementer { private static final Logger LOG = LoggerFactory.getLogger(CountDownLatchDecrementer.class); private String label; private CountDownLatch latch; public CountDownLatchDecrementer(String label, CountDownLatch latch) { this.label = label; this.latch = latch; } @Handler public void decrement(Exchange exchange) { LOG.info("Decrementing latch count: " + label); latch.countDown(); } }
apache-2.0
blowekamp/ITK
Wrapping/Generators/Java/Tests/notYetUsable/DicomSliceRead.java
1795
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /** * Example on the use of DicomImageIO for reading a single DICOM slice, rescale * the intensities and save it in a different file format. * */ import InsightToolkit.*; public class DicomSliceRead { public static void main( String argv[] ) { System.out.println("DicomSliceRead Example"); itkImageFileReaderUS2_Pointer reader = itkImageFileReaderUS2.itkImageFileReaderUS2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); itkRescaleIntensityImageFilterUS2UC2_Pointer filter = itkRescaleIntensityImageFilterUS2UC2.itkRescaleIntensityImageFilterUS2UC2_New(); filter.SetInput( reader.GetOutput() ); writer.SetInput( filter.GetOutput() ); itkDicomImageIO_Pointer dicomIO = itkDicomImageIO.itkDicomImageIO_New(); reader.SetImageIO( dicomIO ); filter.SetOutputMinimum( (short)0 ); filter.SetOutputMaximum( (short) 255); reader.SetFileName( argv[0] ); writer.SetFileName( argv[1] ); writer.Update(); } }
apache-2.0
Vishwa1311/incubator-fineract
fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/api/BulkLoansApiResource.java
6499
/** * 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.fineract.portfolio.loanaccount.api; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; import org.apache.fineract.organisation.office.data.OfficeData; import org.apache.fineract.organisation.office.service.OfficeReadPlatformService; import org.apache.fineract.organisation.staff.data.BulkTransferLoanOfficerData; import org.apache.fineract.organisation.staff.data.StaffAccountSummaryCollectionData; import org.apache.fineract.organisation.staff.data.StaffData; import org.apache.fineract.organisation.staff.service.StaffReadPlatformService; import org.apache.fineract.portfolio.loanaccount.service.BulkLoansReadPlatformService; import org.joda.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Path("/loans/loanreassignment") @Component @Scope("singleton") public class BulkLoansApiResource { private final Set<String> RESPONSE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("officeId", "fromLoanOfficerId", "assignmentDate", "officeOptions", "loanOfficerOptions", "accountSummaryCollection")); private final String resourceNameForPermissions = "LOAN"; private final PlatformSecurityContext context; private final StaffReadPlatformService staffReadPlatformService; private final OfficeReadPlatformService officeReadPlatformService; private final BulkLoansReadPlatformService bulkLoansReadPlatformService; private final DefaultToApiJsonSerializer<BulkTransferLoanOfficerData> toApiJsonSerializer; private final ApiRequestParameterHelper apiRequestParameterHelper; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired public BulkLoansApiResource(final PlatformSecurityContext context, final StaffReadPlatformService staffReadPlatformService, final OfficeReadPlatformService officeReadPlatformService, final BulkLoansReadPlatformService bulkLoansReadPlatformService, final DefaultToApiJsonSerializer<BulkTransferLoanOfficerData> toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.staffReadPlatformService = staffReadPlatformService; this.officeReadPlatformService = officeReadPlatformService; this.bulkLoansReadPlatformService = bulkLoansReadPlatformService; this.toApiJsonSerializer = toApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @GET @Path("template") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String loanReassignmentTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("fromLoanOfficerId") final Long loanOfficerId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection<OfficeData> offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); Collection<StaffData> loanOfficers = null; StaffAccountSummaryCollectionData staffAccountSummaryCollectionData = null; if (officeId != null) { loanOfficers = this.staffReadPlatformService.retrieveAllLoanOfficersInOfficeById(officeId); } if (loanOfficerId != null) { staffAccountSummaryCollectionData = this.bulkLoansReadPlatformService.retrieveLoanOfficerAccountSummary(loanOfficerId); } final BulkTransferLoanOfficerData loanReassignmentData = BulkTransferLoanOfficerData.templateForBulk(officeId, loanOfficerId, new LocalDate(), offices, loanOfficers, staffAccountSummaryCollectionData); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, loanReassignmentData, this.RESPONSE_DATA_PARAMETERS); } @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String loanReassignment(final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().assignLoanOfficersInBulk().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } }
apache-2.0
sesuncedu/elk-reasoner
elk-reasoner/src/test/java/org/semanticweb/elk/reasoner/HashClassificationCorrectnessTest.java
1861
/* * #%L * ELK Reasoner * * $Id$ * $HeadURL$ * %% * Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.semanticweb.elk.reasoner; import java.io.IOException; import java.net.URISyntaxException; import org.junit.runner.RunWith; import org.semanticweb.elk.testing.HashTestOutput; import org.semanticweb.elk.testing.PolySuite; import org.semanticweb.elk.testing.PolySuite.Config; import org.semanticweb.elk.testing.PolySuite.Configuration; /** * Runs classification tests for all test input in the test directory * * @author Pavel Klinov * * pavel.klinov@uni-ulm.de * */ @RunWith(PolySuite.class) public abstract class HashClassificationCorrectnessTest extends BaseClassificationCorrectnessTest<HashTestOutput> { public HashClassificationCorrectnessTest( ReasoningTestManifest<HashTestOutput, ClassTaxonomyTestOutput> testManifest) { super(testManifest); } /* * --------------------------------------------- Configuration: loading all * test input data --------------------------------------------- */ @Config public static Configuration getConfig() throws URISyntaxException, IOException { return HashConfigurationUtils .<ClassTaxonomyTestOutput> loadConfiguration(INPUT_DATA_LOCATION); } }
apache-2.0
MerritCR/merrit
gerrit-gpg/src/main/java/com/google/gerrit/gpg/GpgModule.java
1905
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.gpg; import com.google.gerrit.extensions.config.FactoryModule; import com.google.gerrit.gpg.api.GpgApiModule; import com.google.gerrit.server.EnableSignedPush; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GpgModule extends FactoryModule { private static final Logger log = LoggerFactory.getLogger(GpgModule.class); private final Config cfg; public GpgModule(Config cfg) { this.cfg = cfg; } @Override protected void configure() { boolean configEnableSignedPush = cfg.getBoolean("receive", null, "enableSignedPush", false); boolean configEditGpgKeys = cfg.getBoolean("gerrit", null, "editGpgKeys", true); boolean havePgp = BouncyCastleUtil.havePGP(); boolean enableSignedPush = configEnableSignedPush && havePgp; bindConstant().annotatedWith(EnableSignedPush.class).to(enableSignedPush); if (configEnableSignedPush && !havePgp) { log.info("Bouncy Castle PGP not installed; signed push verification is" + " disabled"); } if (enableSignedPush) { install(new SignedPushModule()); factory(GerritPushCertificateChecker.Factory.class); } install(new GpgApiModule(enableSignedPush && configEditGpgKeys)); } }
apache-2.0
Huntr0/olingo-odata2
odata2-lib/odata-core/src/main/java/org/apache/olingo/odata2/core/edm/provider/EdmFunctionImportImplProv.java
5304
/******************************************************************************* * 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.olingo.odata2.core.edm.provider; import org.apache.olingo.odata2.api.edm.EdmAnnotatable; import org.apache.olingo.odata2.api.edm.EdmAnnotations; import org.apache.olingo.odata2.api.edm.EdmEntityContainer; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmFunctionImport; import org.apache.olingo.odata2.api.edm.EdmMapping; import org.apache.olingo.odata2.api.edm.EdmParameter; import org.apache.olingo.odata2.api.edm.EdmTyped; import org.apache.olingo.odata2.api.edm.provider.FunctionImport; import org.apache.olingo.odata2.api.edm.provider.FunctionImportParameter; import org.apache.olingo.odata2.api.edm.provider.ReturnType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * */ public class EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { private FunctionImport functionImport; private EdmEntityContainer edmEntityContainer; private Map<String, EdmParameter> edmParameters; private Map<String, FunctionImportParameter> parameters; private List<String> parametersList; private EdmAnnotations annotations; private EdmTyped edmReturnType; public EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer) throws EdmException { super(edm, functionImport.getName()); this.functionImport = functionImport; this.edmEntityContainer = edmEntityContainer; buildFunctionImportParametersInternal(); edmParameters = new HashMap<String, EdmParameter>(); } private void buildFunctionImportParametersInternal() { parameters = new HashMap<String, FunctionImportParameter>(); List<FunctionImportParameter> parameters = functionImport.getParameters(); if (parameters != null) { for (FunctionImportParameter parameter : parameters) { this.parameters.put(parameter.getName(), parameter); } } } @Override public EdmParameter getParameter(final String name) throws EdmException { EdmParameter parameter = null; if (edmParameters.containsKey(name)) { parameter = edmParameters.get(name); } else { parameter = createParameter(name); } return parameter; } private EdmParameter createParameter(final String name) throws EdmException { EdmParameter edmParameter = null; if (parameters.containsKey(name)) { FunctionImportParameter parameter = parameters.get(name); edmParameter = new EdmParameterImplProv(edm, parameter); edmParameters.put(name, edmParameter); } return edmParameter; } @Override public List<String> getParameterNames() throws EdmException { if (parametersList == null) { parametersList = new ArrayList<String>(); List<FunctionImportParameter> parameters = functionImport.getParameters(); if(parameters != null) { for (FunctionImportParameter parameter : parameters) { parametersList.add(parameter.getName()); } } } return parametersList; } @Override public EdmEntitySet getEntitySet() throws EdmException { return edmEntityContainer.getEntitySet(functionImport.getEntitySet()); } @Override public String getHttpMethod() throws EdmException { return functionImport.getHttpMethod(); } @Override public EdmTyped getReturnType() throws EdmException { if (edmReturnType == null) { final ReturnType returnType = functionImport.getReturnType(); if (returnType != null) { edmReturnType = new EdmTypedImplProv(edm, functionImport.getName(), returnType.getTypeName(), returnType.getMultiplicity()); } } return edmReturnType; } @Override public EdmEntityContainer getEntityContainer() throws EdmException { return edmEntityContainer; } @Override public EdmAnnotations getAnnotations() throws EdmException { if (annotations == null) { annotations = new EdmAnnotationsImplProv(functionImport.getAnnotationAttributes(), functionImport.getAnnotationElements()); } return annotations; } @Override public EdmMapping getMapping() throws EdmException { return functionImport.getMapping(); } }
apache-2.0
kieranjwhite/CPI-II
src/org/jdeferred/FailFilter.java
865
/* * Copyright 2013 Ray Tsang * * 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.jdeferred; /** * @see Promise#then(DoneFilter, FailFilter) * @author Ray Tsang * * @param <P> Type of the input * @param <P_OUT> Type of the output from this filter */ public interface FailFilter<F, F_OUT> { public F_OUT filterFail(final F result); }
apache-2.0
michaelgallacher/intellij-community
platform/lang-impl/src/com/intellij/framework/detection/impl/ui/DetectedFrameworksTree.java
7486
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.framework.detection.impl.ui; import com.intellij.framework.FrameworkType; import com.intellij.framework.detection.DetectedFrameworkDescription; import com.intellij.framework.detection.FrameworkDetectionContext; import com.intellij.framework.detection.impl.FrameworkDetectionUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.CheckboxTree; import com.intellij.ui.CheckedTreeNode; import com.intellij.util.Consumer; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import java.util.*; /** * @author nik */ public class DetectedFrameworksTree extends CheckboxTree { private List<? extends DetectedFrameworkDescription> myDetectedFrameworks; private final FrameworkDetectionContext myContext; private DetectedFrameworksComponent.GroupByOption myGroupByOption; public DetectedFrameworksTree(final FrameworkDetectionContext context, DetectedFrameworksComponent.GroupByOption groupByOption) { super(new DetectedFrameworksTreeRenderer(), new CheckedTreeNode(null), new CheckPolicy(true, true, true, false)); myContext = context; myGroupByOption = groupByOption; setShowsRootHandles(false); setRootVisible(false); } private void createNodesGroupedByDirectory(CheckedTreeNode root, final List<? extends DetectedFrameworkDescription> frameworks) { Map<VirtualFile, FrameworkDirectoryNode> nodes = new HashMap<>(); List<DetectedFrameworkNode> externalNodes = new ArrayList<>(); for (DetectedFrameworkDescription framework : frameworks) { VirtualFile parent = VfsUtil.getCommonAncestor(framework.getRelatedFiles()); if (parent != null && !parent.isDirectory()) { parent = parent.getParent(); } final DetectedFrameworkNode frameworkNode = new DetectedFrameworkNode(framework, myContext); if (parent != null) { createDirectoryNodes(parent, nodes).add(frameworkNode); } else { externalNodes.add(frameworkNode); } } List<FrameworkDirectoryNode> rootDirs = new ArrayList<>(); for (FrameworkDirectoryNode directoryNode : nodes.values()) { if (directoryNode.getParent() == null) { rootDirs.add(directoryNode); } } for (FrameworkDirectoryNode dir : rootDirs) { root.add(collapseDirectoryNode(dir)); } for (DetectedFrameworkNode node : externalNodes) { root.add(node); } } public void processUncheckedNodes(@NotNull final Consumer<DetectedFrameworkTreeNodeBase> consumer) { TreeUtil.traverse(getRoot(), node -> { if (node instanceof DetectedFrameworkTreeNodeBase) { final DetectedFrameworkTreeNodeBase frameworkNode = (DetectedFrameworkTreeNodeBase)node; if (!frameworkNode.isChecked()) { consumer.consume(frameworkNode); } } return true; }); } @Override protected void onNodeStateChanged(CheckedTreeNode node) { final List<DetectedFrameworkDescription> checked = Arrays.asList(getCheckedNodes(DetectedFrameworkDescription.class, null)); final List<DetectedFrameworkDescription> disabled = FrameworkDetectionUtil.getDisabledDescriptions(checked, Collections.<DetectedFrameworkDescription>emptyList()); for (DetectedFrameworkDescription description : disabled) { final DefaultMutableTreeNode treeNode = TreeUtil.findNodeWithObject(getRoot(), description); if (treeNode instanceof CheckedTreeNode) { ((CheckedTreeNode)treeNode).setChecked(false); } } } private static FrameworkDirectoryNode collapseDirectoryNode(FrameworkDirectoryNode node) { if (node.getChildCount() == 1) { final TreeNode child = node.getChildAt(0); if (child instanceof FrameworkDirectoryNode) { return collapseDirectoryNode((FrameworkDirectoryNode)child); } } for (int i = 0; i < node.getChildCount(); i++) { TreeNode child = node.getChildAt(i); if (child instanceof FrameworkDirectoryNode) { final FrameworkDirectoryNode collapsed = collapseDirectoryNode((FrameworkDirectoryNode)child); if (collapsed != child) { node.remove(i); node.insert(collapsed, i); } } } return node; } @NotNull private static FrameworkDirectoryNode createDirectoryNodes(@NotNull VirtualFile dir, @NotNull Map<VirtualFile, FrameworkDirectoryNode> nodes) { final FrameworkDirectoryNode node = nodes.get(dir); if (node != null) { return node; } final FrameworkDirectoryNode newNode = new FrameworkDirectoryNode(dir); nodes.put(dir, newNode); final VirtualFile parent = dir.getParent(); if (parent != null) { createDirectoryNodes(parent, nodes).add(newNode); } return newNode; } private void createNodesGroupedByType(CheckedTreeNode root, final List<? extends DetectedFrameworkDescription> frameworks) { Map<FrameworkType, FrameworkTypeNode> groupNodes = new HashMap<>(); for (DetectedFrameworkDescription framework : frameworks) { final FrameworkType type = framework.getDetector().getFrameworkType(); FrameworkTypeNode group = groupNodes.get(type); if (group == null) { group = new FrameworkTypeNode(type); groupNodes.put(type, group); root.add(group); } group.add(new DetectedFrameworkNode(framework, myContext)); } } private CheckedTreeNode getRoot() { return ((CheckedTreeNode)getModel().getRoot()); } public void changeGroupBy(DetectedFrameworksComponent.GroupByOption option) { if (myGroupByOption.equals(option)) return; myGroupByOption = option; if (myDetectedFrameworks != null) { rebuildTree(myDetectedFrameworks); } } public void rebuildTree(final List<? extends DetectedFrameworkDescription> frameworks) { final CheckedTreeNode root = getRoot(); root.removeAllChildren(); if (myGroupByOption == DetectedFrameworksComponent.GroupByOption.TYPE) { createNodesGroupedByType(root, frameworks); } else { createNodesGroupedByDirectory(root, frameworks); } ((DefaultTreeModel)getModel()).nodeStructureChanged(root); TreeUtil.expandAll(this); myDetectedFrameworks = frameworks; } private static class DetectedFrameworksTreeRenderer extends CheckboxTreeCellRenderer { private DetectedFrameworksTreeRenderer() { super(true, false); } @Override public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof DetectedFrameworkTreeNodeBase) { ((DetectedFrameworkTreeNodeBase)value).renderNode(getTextRenderer()); } } } }
apache-2.0
Soya93/Extract-Refactoring
platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java
18059
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.HyperlinkInfoBase; import com.intellij.ide.OccurenceNavigator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.EditorMouseAdapter; import com.intellij.openapi.editor.event.EditorMouseEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Key; import com.intellij.pom.NavigatableAdapter; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.CommonProcessors; import com.intellij.util.Consumer; import com.intellij.util.FilteringProcessor; import com.intellij.util.containers.hash.LinkedHashMap; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author peter */ public class EditorHyperlinkSupport { private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.EditorHyperlinkSupport"); public static final Key<TextAttributes> OLD_HYPERLINK_TEXT_ATTRIBUTES = Key.create("OLD_HYPERLINK_TEXT_ATTRIBUTES"); private static final Key<HyperlinkInfoTextAttributes> HYPERLINK = Key.create("HYPERLINK"); private static final int HYPERLINK_LAYER = HighlighterLayer.SELECTION - 123; private static final int HIGHLIGHT_LAYER = HighlighterLayer.SELECTION - 111; private final Editor myEditor; @NotNull private final Project myProject; public EditorHyperlinkSupport(@NotNull final Editor editor, @NotNull final Project project) { myEditor = editor; myProject = project; editor.addEditorMouseListener(new EditorMouseAdapter() { @Override public void mouseClicked(EditorMouseEvent e) { final MouseEvent mouseEvent = e.getMouseEvent(); if (mouseEvent.getButton() == MouseEvent.BUTTON1 && !mouseEvent.isPopupTrigger()) { Runnable runnable = getLinkNavigationRunnable(myEditor.xyToLogicalPosition(e.getMouseEvent().getPoint())); if (runnable != null) { runnable.run(); } } } }); editor.getContentComponent().addMouseMotionListener(new MouseMotionAdapter() { public void mouseMoved(final MouseEvent e) { final HyperlinkInfo info = getHyperlinkInfoByPoint(e.getPoint()); if (info != null) { myEditor.getContentComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else { final Cursor cursor = editor instanceof EditorEx ? UIUtil.getTextCursor(((EditorEx)editor).getBackgroundColor()) : Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR); myEditor.getContentComponent().setCursor(cursor); } } } ); } public void clearHyperlinks() { for (RangeHighlighter highlighter : getHyperlinks(0, myEditor.getDocument().getTextLength(), myEditor)) { removeHyperlink(highlighter); } } @Deprecated public Map<RangeHighlighter, HyperlinkInfo> getHyperlinks() { LinkedHashMap<RangeHighlighter, HyperlinkInfo> result = new LinkedHashMap<RangeHighlighter, HyperlinkInfo>(); for (RangeHighlighter highlighter : getHyperlinks(0, myEditor.getDocument().getTextLength(), myEditor)) { HyperlinkInfo info = getHyperlinkInfo(highlighter); if (info != null) { result.put(highlighter, info); } } return result; } @Nullable public Runnable getLinkNavigationRunnable(final LogicalPosition logical) { if (EditorUtil.inVirtualSpace(myEditor, logical)) { return null; } final RangeHighlighter range = findLinkRangeAt(this.myEditor.logicalPositionToOffset(logical)); if (range != null) { final HyperlinkInfo hyperlinkInfo = getHyperlinkInfo(range); if (hyperlinkInfo != null) { return new Runnable() { @Override public void run() { if (hyperlinkInfo instanceof HyperlinkInfoBase) { final Point point = myEditor.logicalPositionToXY(logical); final MouseEvent event = new MouseEvent(myEditor.getContentComponent(), 0, 0, 0, point.x, point.y, 1, false); ((HyperlinkInfoBase)hyperlinkInfo).navigate(myProject, new RelativePoint(event)); } else { hyperlinkInfo.navigate(myProject); } linkFollowed(myEditor, getHyperlinks(0, myEditor.getDocument().getTextLength(),myEditor), range); } }; } } return null; } @Nullable public static HyperlinkInfo getHyperlinkInfo(@NotNull RangeHighlighter range) { final HyperlinkInfoTextAttributes attributes = range.getUserData(HYPERLINK); return attributes != null ? attributes.getHyperlinkInfo() : null; } @Nullable private RangeHighlighter findLinkRangeAt(final int offset) { //noinspection LoopStatementThatDoesntLoop for (final RangeHighlighter highlighter : getHyperlinks(offset, offset, myEditor)) { return highlighter; } return null; } @Nullable private HyperlinkInfo getHyperlinkAt(final int offset) { RangeHighlighter range = findLinkRangeAt(offset); return range == null ? null : getHyperlinkInfo(range); } public List<RangeHighlighter> findAllHyperlinksOnLine(int line) { final int lineStart = myEditor.getDocument().getLineStartOffset(line); final int lineEnd = myEditor.getDocument().getLineEndOffset(line); return getHyperlinks(lineStart, lineEnd, myEditor); } public static List<RangeHighlighter> getHyperlinks(int startOffset, int endOffset, final Editor editor) { final MarkupModelEx markupModel = (MarkupModelEx)editor.getMarkupModel(); final CommonProcessors.CollectProcessor<RangeHighlighterEx> processor = new CommonProcessors.CollectProcessor<RangeHighlighterEx>(); markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, new FilteringProcessor<RangeHighlighterEx>(new Condition<RangeHighlighterEx>() { @Override public boolean value(RangeHighlighterEx rangeHighlighterEx) { return HYPERLINK_LAYER == rangeHighlighterEx.getLayer() && rangeHighlighterEx.isValid() && getHyperlinkInfo(rangeHighlighterEx) != null; } }, processor) ); return new ArrayList<RangeHighlighter>(processor.getResults()); } public void removeHyperlink(@NotNull RangeHighlighter hyperlink) { myEditor.getMarkupModel().removeHighlighter(hyperlink); } @Nullable public HyperlinkInfo getHyperlinkInfoByLineAndCol(final int line, final int col) { return getHyperlinkAt(myEditor.logicalPositionToOffset(new LogicalPosition(line, col))); } /** * @deprecated for binary compatibility with older plugins * @see #createHyperlink(int, int, com.intellij.openapi.editor.markup.TextAttributes, com.intellij.execution.filters.HyperlinkInfo) */ public void addHyperlink(final int highlightStartOffset, final int highlightEndOffset, @Nullable final TextAttributes highlightAttributes, @NotNull final HyperlinkInfo hyperlinkInfo) { createHyperlink(highlightStartOffset, highlightEndOffset, highlightAttributes, hyperlinkInfo); } @NotNull public RangeHighlighter createHyperlink(int highlightStartOffset, int highlightEndOffset, @Nullable TextAttributes highlightAttributes, @NotNull HyperlinkInfo hyperlinkInfo) { return createHyperlink(highlightStartOffset, highlightEndOffset, highlightAttributes, hyperlinkInfo, null); } @NotNull private RangeHighlighter createHyperlink(final int highlightStartOffset, final int highlightEndOffset, @Nullable final TextAttributes highlightAttributes, @NotNull final HyperlinkInfo hyperlinkInfo, @Nullable TextAttributes followedHyperlinkAttributes) { TextAttributes textAttributes = highlightAttributes != null ? highlightAttributes : getHyperlinkAttributes(); final RangeHighlighter highlighter = myEditor.getMarkupModel().addRangeHighlighter(highlightStartOffset, highlightEndOffset, HYPERLINK_LAYER, textAttributes, HighlighterTargetArea.EXACT_RANGE); associateHyperlink(highlighter, hyperlinkInfo, followedHyperlinkAttributes); return highlighter; } public static void associateHyperlink(@NotNull RangeHighlighter highlighter, @NotNull HyperlinkInfo hyperlinkInfo) { associateHyperlink(highlighter, hyperlinkInfo, null); } private static void associateHyperlink(@NotNull RangeHighlighter highlighter, @NotNull HyperlinkInfo hyperlinkInfo, @Nullable TextAttributes followedHyperlinkAttributes) { highlighter.putUserData(HYPERLINK, new HyperlinkInfoTextAttributes(hyperlinkInfo, followedHyperlinkAttributes)); } @Nullable public HyperlinkInfo getHyperlinkInfoByPoint(final Point p) { final LogicalPosition pos = myEditor.xyToLogicalPosition(new Point(p.x, p.y)); if (EditorUtil.inVirtualSpace(myEditor, pos)) { return null; } return getHyperlinkInfoByLineAndCol(pos.line, pos.column); } @Deprecated public void highlightHyperlinks(final Filter customFilter, final Filter predefinedMessageFilter, final int line1, final int endLine) { highlightHyperlinks(new Filter() { @Nullable @Override public Result applyFilter(String line, int entireLength) { Result result = customFilter.applyFilter(line, entireLength); return result != null ? result : predefinedMessageFilter.applyFilter(line, entireLength); } }, line1, endLine); } public void highlightHyperlinks(final Filter customFilter, final int line1, final int endLine) { final Document document = myEditor.getDocument(); final int startLine = Math.max(0, line1); for (int line = startLine; line <= endLine; line++) { int endOffset = document.getLineEndOffset(line); if (endOffset < document.getTextLength()) { endOffset++; // add '\n' } final String text = getLineText(document, line, true); Filter.Result result = customFilter.applyFilter(text, endOffset); if (result != null) { for (Filter.ResultItem resultItem : result.getResultItems()) { int start = resultItem.getHighlightStartOffset(); int end = resultItem.getHighlightEndOffset(); if (end < start || end > document.getTextLength()) { LOG.error("Filter returned wrong range: start=" + start + "; end=" + end + "; length=" + document.getTextLength() + "; filter=" + customFilter); continue; } TextAttributes attributes = resultItem.getHighlightAttributes(); if (resultItem.getHyperlinkInfo() != null) { createHyperlink(start, end, attributes, resultItem.getHyperlinkInfo(), resultItem.getFollowedHyperlinkAttributes()); } else if (attributes != null) { addHighlighter(start, end, attributes); } } } } } public void addHighlighter(int highlightStartOffset, int highlightEndOffset, TextAttributes highlightAttributes) { myEditor.getMarkupModel().addRangeHighlighter(highlightStartOffset, highlightEndOffset, HIGHLIGHT_LAYER, highlightAttributes, HighlighterTargetArea.EXACT_RANGE); } private static TextAttributes getHyperlinkAttributes() { return EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.HYPERLINK_ATTRIBUTES); } @NotNull private static TextAttributes getFollowedHyperlinkAttributes(@NotNull RangeHighlighter range) { HyperlinkInfoTextAttributes attrs = HYPERLINK.get(range); TextAttributes result = attrs != null ? attrs.getFollowedHyperlinkAttributes() : null; if (result == null) { result = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.FOLLOWED_HYPERLINK_ATTRIBUTES); } return result; } @Nullable public static OccurenceNavigator.OccurenceInfo getNextOccurrence(final Editor editor, final int delta, final Consumer<RangeHighlighter> action) { final List<RangeHighlighter> ranges = getHyperlinks(0, editor.getDocument().getTextLength(),editor); if (ranges.isEmpty()) { return null; } int i; for (i = 0; i < ranges.size(); i++) { RangeHighlighter range = ranges.get(i); if (range.getUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES) != null) { break; } } i = i % ranges.size(); int newIndex = i; while (newIndex < ranges.size() && newIndex >= 0) { newIndex = (newIndex + delta + ranges.size()) % ranges.size(); final RangeHighlighter next = ranges.get(newIndex); if (editor.getFoldingModel().getCollapsedRegionAtOffset(next.getStartOffset()) == null) { return new OccurenceNavigator.OccurenceInfo(new NavigatableAdapter() { public void navigate(final boolean requestFocus) { action.consume(next); linkFollowed(editor, ranges, next); } }, newIndex == -1 ? -1 : newIndex + 1, ranges.size()); } if (newIndex == i) { break; // cycled through everything, found no next/prev hyperlink } } return null; } // todo fix link followed here! private static void linkFollowed(Editor editor, Collection<RangeHighlighter> ranges, final RangeHighlighter link) { MarkupModelEx markupModel = (MarkupModelEx)editor.getMarkupModel(); for (RangeHighlighter range : ranges) { TextAttributes oldAttr = range.getUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES); if (oldAttr != null) { markupModel.setRangeHighlighterAttributes(range, oldAttr); range.putUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES, null); } if (range == link) { range.putUserData(OLD_HYPERLINK_TEXT_ATTRIBUTES, range.getTextAttributes()); markupModel.setRangeHighlighterAttributes(range, getFollowedHyperlinkAttributes(range)); } } //refresh highlighter text attributes markupModel.addRangeHighlighter(0, 0, HYPERLINK_LAYER, getHyperlinkAttributes(), HighlighterTargetArea.EXACT_RANGE).dispose(); } public static String getLineText(Document document, int lineNumber, boolean includeEol) { int endOffset = document.getLineEndOffset(lineNumber); if (includeEol && endOffset < document.getTextLength()) { endOffset++; } return document.getCharsSequence().subSequence(document.getLineStartOffset(lineNumber), endOffset).toString(); } private static class HyperlinkInfoTextAttributes extends TextAttributes { private final HyperlinkInfo myHyperlinkInfo; private final TextAttributes myFollowedHyperlinkAttributes; public HyperlinkInfoTextAttributes(@NotNull HyperlinkInfo hyperlinkInfo, @Nullable TextAttributes followedHyperlinkAttributes) { myHyperlinkInfo = hyperlinkInfo; myFollowedHyperlinkAttributes = followedHyperlinkAttributes; } @NotNull public HyperlinkInfo getHyperlinkInfo() { return myHyperlinkInfo; } @Nullable public TextAttributes getFollowedHyperlinkAttributes() { return myFollowedHyperlinkAttributes; } } }
apache-2.0
zwets/flowable-engine
modules/flowable-engine/src/test/java/org/flowable/engine/test/bpmn/event/timer/compatibility/BoundaryTimerEventRepeatCompatibilityTest.java
4639
/* 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.flowable.engine.test.bpmn.event.timer.compatibility; import java.util.Calendar; import java.util.Date; import java.util.List; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.job.api.Job; import org.flowable.job.service.impl.persistence.entity.TimerJobEntity; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class BoundaryTimerEventRepeatCompatibilityTest extends TimerEventCompatibilityTest { @Deployment public void testRepeatWithoutEnd() throws Throwable { Calendar calendar = Calendar.getInstance(); Date baseTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 20); // expect to stop boundary jobs after 20 minutes DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); DateTime dt = new DateTime(calendar.getTime()); String dateStr = fmt.print(dt); // reset the timer Calendar nextTimeCal = Calendar.getInstance(); nextTimeCal.setTime(baseTime); processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime()); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("repeatWithEnd"); runtimeService.setVariable(processInstance.getId(), "EndDateForBoundary", dateStr); List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().list(); assertEquals(1, tasks.size()); org.flowable.task.api.Task task = tasks.get(0); assertEquals("Task A", task.getName()); // Test Boundary Events // complete will cause timer to be created taskService.complete(task.getId()); List<Job> jobs = managementService.createTimerJobQuery().list(); assertEquals(1, jobs.size()); // change the job in old mode (the configuration should not be json in // "old mode" but a simple string). TimerJobEntity job = (TimerJobEntity) jobs.get(0); changeConfigurationToPlainText(job); // boundary events waitForJobExecutorToProcessAllJobs(2000, 100); // a new job must be prepared because there are 10 repeats 2 seconds interval jobs = managementService.createTimerJobQuery().list(); assertEquals(1, jobs.size()); for (int i = 0; i < 9; i++) { nextTimeCal.add(Calendar.SECOND, 2); processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime()); waitForJobExecutorToProcessAllJobs(2000, 100); // a new job must be prepared because there are 10 repeats 2 seconds interval jobs = managementService.createTimerJobQuery().list(); assertEquals(1, jobs.size()); } nextTimeCal.add(Calendar.SECOND, 2); processEngineConfiguration.getClock().setCurrentTime(nextTimeCal.getTime()); try { waitForJobExecutorToProcessAllJobs(2000, 100); } catch (Exception ex) { fail("Should not have any other jobs because the endDate is reached"); } tasks = taskService.createTaskQuery().list(); task = tasks.get(0); assertEquals("Task B", task.getName()); assertEquals(1, tasks.size()); taskService.complete(task.getId()); try { waitForJobExecutorToProcessAllJobs(2000, 500); } catch (Exception e) { fail("No jobs should be active here."); } // now All the process instances should be completed List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list(); assertEquals(0, processInstances.size()); // no jobs jobs = managementService.createJobQuery().list(); assertEquals(0, jobs.size()); jobs = managementService.createTimerJobQuery().list(); assertEquals(0, jobs.size()); // no tasks tasks = taskService.createTaskQuery().list(); assertEquals(0, tasks.size()); } }
apache-2.0
gmrodrigues/crate
sql/src/main/java/io/crate/operation/reference/sys/node/NodeProcessCpuExpression.java
2588
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.reference.sys.node; import io.crate.operation.reference.sys.SysNodeObjectReference; import org.elasticsearch.monitor.process.ProcessStats; public class NodeProcessCpuExpression extends SysNodeObjectReference { public static final String NAME = "cpu"; public static final String PERCENT = "percent"; public static final String USER = "user"; public static final String SYSTEM = "system"; public NodeProcessCpuExpression(ProcessStats stats) { addChildImplementations(stats.cpu()); } private void addChildImplementations(final ProcessStats.Cpu cpu) { childImplementations.put(PERCENT, new SysNodeExpression<Short>() { @Override public Short value() { if (cpu != null) { return cpu.getPercent(); } else { return -1; } } }); childImplementations.put(USER, new SysNodeExpression<Long>() { @Override public Long value() { if (cpu != null) { return cpu.getUser().millis(); } else { return -1L; } } }); childImplementations.put(SYSTEM, new SysNodeExpression<Long>() { @Override public Long value() { if (cpu != null) { return cpu.getSys().millis(); } else { return -1L; } } }); } }
apache-2.0
dain/airlift
configuration/src/main/java/io/airlift/configuration/ConfigurationBindingListener.java
187
package io.airlift.configuration; public interface ConfigurationBindingListener { void configurationBound(ConfigurationBinding<?> configurationBinding, ConfigBinder configBinder); }
apache-2.0
themarkypantz/kafka
tools/src/main/java/org/apache/kafka/trogdor/fault/Kibosh.java
6739
/* * 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.trogdor.fault; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.apache.kafka.trogdor.common.JsonUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.TreeMap; public final class Kibosh { public static final Kibosh INSTANCE = new Kibosh(); public final static String KIBOSH_CONTROL = "kibosh_control"; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = KiboshFilesUnreadableFaultSpec.class, name = "unreadable"), }) public static abstract class KiboshFaultSpec { @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Objects.equals(toString(), o.toString()); } @Override public final int hashCode() { return toString().hashCode(); } @Override public final String toString() { return JsonUtil.toJsonString(this); } } public static class KiboshFilesUnreadableFaultSpec extends KiboshFaultSpec { private final String prefix; private final int errorCode; @JsonCreator public KiboshFilesUnreadableFaultSpec(@JsonProperty("prefix") String prefix, @JsonProperty("errorCode") int errorCode) { this.prefix = prefix; this.errorCode = errorCode; } @JsonProperty public String prefix() { return prefix; } @JsonProperty public int errorCode() { return errorCode; } } private static class KiboshProcess { private final Path controlPath; KiboshProcess(String mountPath) { this.controlPath = Paths.get(mountPath, KIBOSH_CONTROL); if (!Files.exists(controlPath)) { throw new RuntimeException("Can't find file " + controlPath); } } synchronized void addFault(KiboshFaultSpec toAdd) throws IOException { KiboshControlFile file = KiboshControlFile.read(controlPath); List<KiboshFaultSpec> faults = new ArrayList<>(file.faults()); faults.add(toAdd); new KiboshControlFile(faults).write(controlPath); } synchronized void removeFault(KiboshFaultSpec toRemove) throws IOException { KiboshControlFile file = KiboshControlFile.read(controlPath); List<KiboshFaultSpec> faults = new ArrayList<>(); boolean foundToRemove = false; for (KiboshFaultSpec fault : file.faults()) { if (fault.equals(toRemove)) { foundToRemove = true; } else { faults.add(fault); } } if (!foundToRemove) { throw new RuntimeException("Failed to find fault " + toRemove + ". "); } new KiboshControlFile(faults).write(controlPath); } } public static class KiboshControlFile { private final List<KiboshFaultSpec> faults; public final static KiboshControlFile EMPTY = new KiboshControlFile(Collections.<KiboshFaultSpec>emptyList()); public static KiboshControlFile read(Path controlPath) throws IOException { byte[] controlFileBytes = Files.readAllBytes(controlPath); return JsonUtil.JSON_SERDE.readValue(controlFileBytes, KiboshControlFile.class); } @JsonCreator public KiboshControlFile(@JsonProperty("faults") List<KiboshFaultSpec> faults) { this.faults = faults; } @JsonProperty public List<KiboshFaultSpec> faults() { return faults; } public void write(Path controlPath) throws IOException { Files.write(controlPath, JsonUtil.JSON_SERDE.writeValueAsBytes(this)); } @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Objects.equals(toString(), o.toString()); } @Override public final int hashCode() { return toString().hashCode(); } @Override public final String toString() { return JsonUtil.toJsonString(this); } } private final TreeMap<String, KiboshProcess> processes = new TreeMap<>(); private Kibosh() { } /** * Get or create a KiboshProcess object to manage the Kibosh process at a given path. */ private synchronized KiboshProcess findProcessObject(String mountPath) { String path = Paths.get(mountPath).normalize().toString(); KiboshProcess process = processes.get(path); if (process == null) { process = new KiboshProcess(mountPath); processes.put(path, process); } return process; } /** * Add a new Kibosh fault. */ void addFault(String mountPath, KiboshFaultSpec spec) throws IOException { KiboshProcess process = findProcessObject(mountPath); process.addFault(spec); } /** * Remove a Kibosh fault. */ void removeFault(String mountPath, KiboshFaultSpec spec) throws IOException { KiboshProcess process = findProcessObject(mountPath); process.removeFault(spec); } }
apache-2.0
lewis007/sky-demo
sky-javafx/src/main/java/org/lewis/sky/fxml/SpringFxmlBuilderFactory.java
1272
package org.lewis.sky.fxml; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; import javafx.util.Builder; import javafx.util.BuilderFactory; @Component public class SpringFxmlBuilderFactory implements InitializingBean, BuilderFactory { @Autowired private ApplicationContext applicationContext; private List<String> packages; @Override public void afterPropertiesSet() throws Exception { packages = applicationContext.getBeansWithAnnotation(ComponentScan.class).values().stream() .map(obj -> obj.getClass().getPackage().getName()).collect(Collectors.toList()); } @Override public Builder<?> getBuilder(Class<?> type) { if (packages.stream().anyMatch(p -> type.getPackage().getName().indexOf(p) == 0)) { try { Object bean = applicationContext.getBean(type); return () -> bean; } catch (NoSuchBeanDefinitionException e) { return null; } } return null; } }
apache-2.0
Commonjava/indy
subsys/jaxrs/src/main/java/org/commonjava/indy/bind/jaxrs/SlashTolerationFilter.java
2651
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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.commonjava.indy.bind.jaxrs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @ApplicationScoped public class SlashTolerationFilter implements Filter { private final Logger logger = LoggerFactory.getLogger( getClass() ); @Override public void init( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletRequest hsr = (HttpServletRequest) servletRequest; final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(hsr) { @Override public StringBuffer getRequestURL() { final StringBuffer originalUrl = hsr.getRequestURL(); try { return new StringBuffer( new URI( originalUrl.toString()).normalize().toString() ); } catch ( URISyntaxException e ) { logger.error("URL rewriting error.", e); } return originalUrl; } @Override public String getRequestURI(){ try { return new URI( hsr.getRequestURI() ).normalize().toString(); } catch ( URISyntaxException e ) { logger.error("URL rewriting error.", e); } return hsr.getRequestURI(); } }; filterChain.doFilter(wrapped, servletResponse); } @Override public void destroy() { } }
apache-2.0
dublinio/smile
SmileDemo/src/main/java/smile/demo/projection/ProjectionDemo.java
5298
/******************************************************************************* * Copyright (c) 2010 Haifeng Li * * 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 smile.demo.projection; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import smile.data.AttributeDataset; import smile.data.NominalAttribute; import smile.data.parser.DelimitedTextParser; @SuppressWarnings("serial") public abstract class ProjectionDemo extends JPanel implements Runnable, ActionListener { private static String[] datasetName = { "IRIS", "US Arrests", "Food Nutrition", "Pen Digits", "COMBO-17" }; private static String[] datasource = { "/smile/demo/data/classification/iris.txt", "/smile/demo/data/projection/USArrests.txt", "/smile/demo/data/projection/food.txt", "/smile/demo/data/classification/pendigits.txt", "/smile/demo/data/projection/COMBO17.dat" }; static AttributeDataset[] dataset = new AttributeDataset[datasetName.length]; static int datasetIndex = 0; JPanel optionPane; JComponent canvas; private JButton startButton; private JComboBox<String> datasetBox; char pointLegend = '.'; /** * Constructor. */ public ProjectionDemo() { startButton = new JButton("Start"); startButton.setActionCommand("startButton"); startButton.addActionListener(this); datasetBox = new JComboBox<String>(); for (int i = 0; i < datasetName.length; i++) { datasetBox.addItem(datasetName[i]); } datasetBox.setSelectedIndex(0); datasetBox.setActionCommand("datasetBox"); datasetBox.addActionListener(this); optionPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); optionPane.setBorder(BorderFactory.createRaisedBevelBorder()); optionPane.add(startButton); optionPane.add(new JLabel("Dataset:")); optionPane.add(datasetBox); setLayout(new BorderLayout()); add(optionPane, BorderLayout.NORTH); } /** * Execute the projection algorithm and return a swing JComponent representing * the clusters. */ public abstract JComponent learn(); @Override public void run() { startButton.setEnabled(false); datasetBox.setEnabled(false); try { JComponent plot = learn(); if (plot != null) { if (canvas != null) remove(canvas); canvas = plot; add(plot, BorderLayout.CENTER); } validate(); } catch (Exception ex) { System.err.println(ex); } startButton.setEnabled(true); datasetBox.setEnabled(true); } @Override public void actionPerformed(ActionEvent e) { if ("startButton".equals(e.getActionCommand())) { datasetIndex = datasetBox.getSelectedIndex(); if (dataset[datasetIndex] == null) { DelimitedTextParser parser = new DelimitedTextParser(); parser.setDelimiter("[\t]+"); if (datasetIndex < 5 && datasetIndex != 3) { parser.setColumnNames(true); } if (datasetIndex == 1) { parser.setRowNames(true); } if (datasetIndex == 0) { parser.setResponseIndex(new NominalAttribute("class"), 4); } if (datasetIndex == 3) { parser.setResponseIndex(new NominalAttribute("class"), 16); } if (datasetIndex >= 5) { parser.setResponseIndex(new NominalAttribute("class"), 4); } try { dataset[datasetIndex] = parser.parse(datasetName[datasetIndex], this.getClass().getResourceAsStream(datasource[datasetIndex])); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Failed to load dataset.", "ERROR", JOptionPane.ERROR_MESSAGE); System.out.println(ex); } } if (dataset[datasetIndex].size() < 500) { pointLegend = 'o'; } else { pointLegend = '.'; } Thread thread = new Thread(this); thread.start(); } } }
apache-2.0
yuyupapa/OpenSource
scouter.common/src/scouter/util/FloatEnumer.java
797
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.util; public interface FloatEnumer { public boolean hasMoreElements(); public float nextFloat(); }
apache-2.0