repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
gdefias/JavaDemo
InitJava/base/src/main/java/Concurrency/Test4_ShareSync2.java
2695
package Concurrency; /** * Created by Defias on 2020/07. * Description: 解决共享资源竞争 使用synchronized块 通用形式: synchronized(object) { //statements to be synchronized } object是被同步对象的引用。如果要同步的只是一个语句那么可以不要花括号 */ public class Test4_ShareSync2 { public static void main(String args[]) { //test1(); test2(); } public static void test1() { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } public static void test2() { final DualSynch ds = new DualSynch(); new Thread() { public void run() { ds.f(); //ds.f2(); } }.start(); ds.g(); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block 同步块 //锁住target target.call(msg); } } } class Callme { //非原子操作 void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println(msg + "]"); } } //f()上的同步与g()上的同步是相互独立的 class DualSynch { private Object syncObject = new Object(); public synchronized void f() { for(int i = 0; i < 5; i++) { System.out.println("f()"); Thread.yield(); } } public void f2() { synchronized(syncObject) { for (int i = 0; i < 5; i++) { System.out.println("f()"); Thread.yield(); } } } public void g() { synchronized(syncObject) { for(int i = 0; i < 5; i++) { System.out.println("g()"); Thread.yield(); } } } public synchronized void g2() { for(int i = 0; i < 5; i++) { System.out.println("g()"); Thread.yield(); } } }
apache-2.0
cy19890513/Leetcode-1
src/main/java/com/fishercoder/solutions/_75.java
1490
package com.fishercoder.solutions; /** Given an array with n objects colored red, white or blue, * sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with an one-pass algorithm using only constant space?*/ public class _75 { public void sortColors(int[] nums) { int zero = 0; int two = nums.length - 1; for (int i = 0; i <= two; ) { if (nums[i] == 0 && i > zero) { swap(nums, i, zero++); } else if (nums[i] == 2 && i < two) { swap(nums, i, two--); } else { i++; } } } void swap(int[] nums, int m, int n) { int temp = nums[m]; nums[m] = nums[n]; nums[n] = temp; } public static void main(String... args) { // int[] nums = new int[]{0,1,2,0,2,1}; // int[] nums = new int[]{0}; // int[] nums = new int[]{2}; int[] nums = new int[]{2, 2, 1}; // int[] nums = new int[]{1,0}; } }
apache-2.0
saulbein/web3j
core/src/main/java/org/web3j/abi/datatypes/generated/Uint112.java
528
package org.web3j.abi.datatypes.generated; import java.math.BigInteger; import org.web3j.abi.datatypes.Uint; /** * <p>Auto generated code.<br> * <strong>Do not modifiy!</strong><br> * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p> */ public class Uint112 extends Uint { public static final Uint112 DEFAULT = new Uint112(BigInteger.ZERO); public Uint112(BigInteger value) { super(112, value); } public Uint112(long value) { this(BigInteger.valueOf(value)); } }
apache-2.0
tankisleva/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactAddressTests.java
1450
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by oleg on 23.03.16. */ public class ContactAddressTests extends TestBase { @BeforeMethod public void ensurePreconditions(){ app.goTo().home(); if (app.contact().all().size() == 0) { ContactData contact = new ContactData().withFirstname("Oleg").withLastname("Malyshev") .withUsername("tanki_sleva").withCompany("wamba").withHomeadress("parkway yraeva kgsgsgj ksglksglkg lksglklsgk ;sg;sg;ssg") .withMobilenumber("79177121162").withAllEmails("gsgssfsf@mail.ru").withtEmail2("gdgdgdgdW@yandex.ru"); app.contact().create(contact, true); } } @Test public void testContactAddress() { app.goTo().home(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFormEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getHomeadress(),equalTo(cleaned(contactInfoFormEditForm.getHomeadress()))); } public static String cleaned(String address){ return address.replaceAll("\\s{2,}"," "); } }
apache-2.0
vergilchiu/hive
llap-server/src/java/org/apache/hadoop/hive/llap/daemon/impl/LlapProtocolServerImpl.java
13738
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.llap.daemon.impl; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.util.concurrent.atomic.AtomicReference; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import com.google.protobuf.BlockingService; import com.google.protobuf.ByteString; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hadoop.hive.llap.DaemonId; import org.apache.hadoop.hive.llap.LlapUtil; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.GetTokenRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.GetTokenResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.QueryCompleteRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.QueryCompleteResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SourceStateUpdatedRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SourceStateUpdatedResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SubmitWorkRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SubmitWorkResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.TerminateFragmentRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.TerminateFragmentResponseProto; import org.apache.hadoop.ipc.ProtobufRpcEngine; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.hive.llap.security.LlapTokenIdentifier; import org.apache.hadoop.hive.llap.security.SecretManager; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.hive.llap.daemon.ContainerRunner; import org.apache.hadoop.hive.llap.protocol.LlapProtocolBlockingPB; import org.apache.hadoop.hive.llap.protocol.LlapManagementProtocolPB; import org.apache.hadoop.hive.llap.security.LlapDaemonPolicyProvider; public class LlapProtocolServerImpl extends AbstractService implements LlapProtocolBlockingPB, LlapManagementProtocolPB { private static final Logger LOG = LoggerFactory.getLogger(LlapProtocolServerImpl.class); private enum TokenRequiresSigning { TRUE, FALSE, EXCEPT_OWNER } private final int numHandlers; private final ContainerRunner containerRunner; private final int srvPort, mngPort; private RPC.Server server, mngServer; private final AtomicReference<InetSocketAddress> srvAddress, mngAddress; private final SecretManager secretManager; private String clusterUser = null; private boolean isRestrictedToClusterUser = false; private final DaemonId daemonId; private TokenRequiresSigning isSigningRequiredConfig = TokenRequiresSigning.TRUE; public LlapProtocolServerImpl(SecretManager secretManager, int numHandlers, ContainerRunner containerRunner, AtomicReference<InetSocketAddress> srvAddress, AtomicReference<InetSocketAddress> mngAddress, int srvPort, int mngPort, DaemonId daemonId) { super("LlapDaemonProtocolServerImpl"); this.numHandlers = numHandlers; this.containerRunner = containerRunner; this.secretManager = secretManager; this.srvAddress = srvAddress; this.srvPort = srvPort; this.mngAddress = mngAddress; this.mngPort = mngPort; this.daemonId = daemonId; LOG.info("Creating: " + LlapProtocolServerImpl.class.getSimpleName() + " with port configured to: " + srvPort); } @Override public SubmitWorkResponseProto submitWork(RpcController controller, SubmitWorkRequestProto request) throws ServiceException { try { return containerRunner.submitWork(request); } catch (IOException e) { throw new ServiceException(e); } } @Override public SourceStateUpdatedResponseProto sourceStateUpdated(RpcController controller, SourceStateUpdatedRequestProto request) throws ServiceException { try { return containerRunner.sourceStateUpdated(request); } catch (IOException e) { throw new ServiceException(e); } } @Override public QueryCompleteResponseProto queryComplete(RpcController controller, QueryCompleteRequestProto request) throws ServiceException { try { return containerRunner.queryComplete(request); } catch (IOException e) { throw new ServiceException(e); } } @Override public TerminateFragmentResponseProto terminateFragment( RpcController controller, TerminateFragmentRequestProto request) throws ServiceException { try { return containerRunner.terminateFragment(request); } catch (IOException e) { throw new ServiceException(e); } } @Override public void serviceStart() { final Configuration conf = getConfig(); isSigningRequiredConfig = getSigningConfig(conf); final BlockingService daemonImpl = LlapDaemonProtocolProtos.LlapDaemonProtocol.newReflectiveBlockingService(this); final BlockingService managementImpl = LlapDaemonProtocolProtos.LlapManagementProtocol.newReflectiveBlockingService(this); if (!UserGroupInformation.isSecurityEnabled()) { startProtocolServers(conf, daemonImpl, managementImpl); return; } try { this.clusterUser = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { throw new RuntimeException(e); } if (isPermissiveManagementAcl(conf)) { LOG.warn("Management protocol has a '*' ACL."); isRestrictedToClusterUser = true; } String llapPrincipal = HiveConf.getVar(conf, ConfVars.LLAP_KERBEROS_PRINCIPAL), llapKeytab = HiveConf.getVar(conf, ConfVars.LLAP_KERBEROS_KEYTAB_FILE); // Start the protocol server after properly authenticating with daemon keytab. UserGroupInformation daemonUgi = null; try { daemonUgi = LlapUtil.loginWithKerberos(llapPrincipal, llapKeytab); } catch (IOException e) { throw new RuntimeException(e); } daemonUgi.doAs(new PrivilegedAction<Void>() { @Override public Void run() { startProtocolServers(conf, daemonImpl, managementImpl); return null; } }); } private static TokenRequiresSigning getSigningConfig(final Configuration conf) { String signSetting = HiveConf.getVar( conf, ConfVars.LLAP_REMOTE_TOKEN_REQUIRES_SIGNING).toLowerCase(); switch (signSetting) { case "true": return TokenRequiresSigning.TRUE; case "except_llap_owner": return TokenRequiresSigning.EXCEPT_OWNER; case "false": return TokenRequiresSigning.FALSE; default: { throw new RuntimeException("Invalid value for " + ConfVars.LLAP_REMOTE_TOKEN_REQUIRES_SIGNING.varname + ": " + signSetting); } } } private static boolean isPermissiveManagementAcl(Configuration conf) { return HiveConf.getBoolVar(conf, ConfVars.LLAP_VALIDATE_ACLS) && AccessControlList.WILDCARD_ACL_VALUE.equals( HiveConf.getVar(conf, ConfVars.LLAP_MANAGEMENT_ACL)) && "".equals(HiveConf.getVar(conf, ConfVars.LLAP_MANAGEMENT_ACL_DENY)); } private void startProtocolServers( Configuration conf, BlockingService daemonImpl, BlockingService managementImpl) { server = startProtocolServer(srvPort, numHandlers, srvAddress, conf, daemonImpl, LlapProtocolBlockingPB.class, ConfVars.LLAP_SECURITY_ACL, ConfVars.LLAP_SECURITY_ACL_DENY); mngServer = startProtocolServer(mngPort, 2, mngAddress, conf, managementImpl, LlapManagementProtocolPB.class, ConfVars.LLAP_MANAGEMENT_ACL, ConfVars.LLAP_MANAGEMENT_ACL_DENY); } private RPC.Server startProtocolServer(int srvPort, int numHandlers, AtomicReference<InetSocketAddress> bindAddress, Configuration conf, BlockingService impl, Class<?> protocolClass, ConfVars... aclVars) { InetSocketAddress addr = new InetSocketAddress(srvPort); RPC.Server server; try { server = createServer(protocolClass, addr, conf, numHandlers, impl, aclVars); server.start(); } catch (IOException e) { LOG.error("Failed to run RPC Server on port: " + srvPort, e); throw new RuntimeException(e); } InetSocketAddress serverBindAddress = NetUtils.getConnectAddress(server); bindAddress.set(NetUtils.createSocketAddrForHost( serverBindAddress.getAddress().getCanonicalHostName(), serverBindAddress.getPort())); LOG.info("Instantiated " + protocolClass.getSimpleName() + " at " + bindAddress); return server; } @Override public void serviceStop() { if (server != null) { server.stop(); } if (mngServer != null) { mngServer.stop(); } } @InterfaceAudience.Private InetSocketAddress getBindAddress() { return srvAddress.get(); } @InterfaceAudience.Private InetSocketAddress getManagementBindAddress() { return mngAddress.get(); } private RPC.Server createServer(Class<?> pbProtocol, InetSocketAddress addr, Configuration conf, int numHandlers, BlockingService blockingService, ConfVars... aclVars) throws IOException { Configuration serverConf = conf; boolean isSecurityEnabled = conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false); if (isSecurityEnabled) { // Enforce Hive defaults. for (ConfVars acl : aclVars) { if (conf.get(acl.varname) != null) continue; // Some value is set. if (serverConf == conf) { serverConf = new Configuration(conf); } serverConf.set(acl.varname, HiveConf.getVar(serverConf, acl)); // Set the default. } } RPC.setProtocolEngine(serverConf, pbProtocol, ProtobufRpcEngine.class); RPC.Builder builder = new RPC.Builder(serverConf) .setProtocol(pbProtocol) .setInstance(blockingService) .setBindAddress(addr.getHostName()) .setPort(addr.getPort()) .setNumHandlers(numHandlers); if (secretManager != null) { builder = builder.setSecretManager(secretManager); } RPC.Server server = builder.build(); if (isSecurityEnabled) { server.refreshServiceAcl(serverConf, new LlapDaemonPolicyProvider()); } return server; } @Override public GetTokenResponseProto getDelegationToken(RpcController controller, GetTokenRequestProto request) throws ServiceException { if (secretManager == null) { throw new ServiceException("Operation not supported on unsecure cluster"); } UserGroupInformation callingUser = null; Token<LlapTokenIdentifier> token = null; try { callingUser = UserGroupInformation.getCurrentUser(); // Determine if the user would need to sign fragments. boolean isSigningRequired = determineIfSigningIsRequired(callingUser); token = secretManager.createLlapToken( request.hasAppId() ? request.getAppId() : null, null, isSigningRequired); } catch (IOException e) { throw new ServiceException(e); } if (isRestrictedToClusterUser && !clusterUser.equals(callingUser.getShortUserName())) { throw new ServiceException("Management protocol ACL is too permissive. The access has been" + " automatically restricted to " + clusterUser + "; " + callingUser.getShortUserName() + " is denied acccess. Please set " + ConfVars.LLAP_VALIDATE_ACLS.varname + " to false," + " or adjust " + ConfVars.LLAP_MANAGEMENT_ACL.varname + " and " + ConfVars.LLAP_MANAGEMENT_ACL_DENY.varname + " to a more restrictive ACL."); } ByteArrayDataOutput out = ByteStreams.newDataOutput(); try { token.write(out); } catch (IOException e) { throw new ServiceException(e); } ByteString bs = ByteString.copyFrom(out.toByteArray()); GetTokenResponseProto response = GetTokenResponseProto.newBuilder().setToken(bs).build(); return response; } private boolean determineIfSigningIsRequired(UserGroupInformation callingUser) { switch (isSigningRequiredConfig) { case FALSE: return false; case TRUE: return true; // Note that this uses short user name without consideration for Kerberos realm. // This seems to be the common approach (e.g. for HDFS permissions), but it may be // better to consider the realm (although not the host, so not the full name). case EXCEPT_OWNER: return !clusterUser.equals(callingUser.getShortUserName()); default: throw new AssertionError("Unknown value " + isSigningRequiredConfig); } } }
apache-2.0
tteofili/jackrabbit-oak
oak-mongomk/src/main/java/org/apache/jackrabbit/mongomk/impl/instruction/SetPropertyInstructionImpl.java
2031
/* * 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.jackrabbit.mongomk.impl.instruction; import org.apache.jackrabbit.mongomk.api.instruction.InstructionVisitor; import org.apache.jackrabbit.mongomk.api.instruction.Instruction.SetPropertyInstruction; /** * Implementation for the set property operation => "^" STRING ":" ATOM | ARRAY */ public class SetPropertyInstructionImpl extends BaseInstruction implements SetPropertyInstruction { private final String key; private final Object value; /** * Constructs a new {@code SetPropertyInstruction}. * * @param path The path. * @param key The key. * @param value The value. */ public SetPropertyInstructionImpl(String path, String key, Object value) { super(path); this.key = key; this.value = value; } @Override public void accept(InstructionVisitor visitor) { visitor.visit(this); } /** * Returns the name of the property. * * @return The name of the property. */ public String getKey() { return key; } /** * Returns the value of the property. * * @return The value of the property. */ public Object getValue() { return value; } }
apache-2.0
SimbaService/Simba
client/SimbaContentService/src/com/necla/simba/protocol/TornRowResponse.java
5531
/******************************************************************************* * Copyright 2015 Dorian Perkins, Younghwan Go, Nitin Agrawal, Akshat Aranya * * 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.necla.simba.protocol; // Generated by proto2javame, Sun Feb 08 14:12:26 KST 2015. import java.io.IOException; import java.io.InputStream; import java.util.*; import net.jarlehansen.protobuf.javame.UninitializedMessageException; import net.jarlehansen.protobuf.javame.input.InputReader; import net.jarlehansen.protobuf.javame.input.DelimitedInputStream; import net.jarlehansen.protobuf.javame.input.DelimitedSizeUtil; import net.jarlehansen.protobuf.javame.ComputeSizeUtil; import net.jarlehansen.protobuf.javame.output.OutputWriter; import net.jarlehansen.protobuf.javame.AbstractOutputWriter; import net.jarlehansen.protobuf.javame.input.taghandler.UnknownTagHandler; import net.jarlehansen.protobuf.javame.input.taghandler.DefaultUnknownTagHandlerImpl; public final class TornRowResponse extends AbstractOutputWriter { private static UnknownTagHandler unknownTagHandler = DefaultUnknownTagHandlerImpl.newInstance(); private final SyncHeader data; private static final int fieldNumberData = 1; public static Builder newBuilder() { return new Builder(); } private TornRowResponse(final Builder builder) { if (builder.hasData ) { this.data = builder.data; } else { throw new UninitializedMessageException("Not all required fields were included (false = not included in message), " + " data:" + builder.hasData + ""); } } public static class Builder { private SyncHeader data; private boolean hasData = false; private Builder() { } public Builder setData(final SyncHeader data) { this.data = data; this.hasData = true; return this; } public TornRowResponse build() { return new TornRowResponse(this); } } public SyncHeader getData() { return data; } public String toString() { final String TAB = " "; String retValue = ""; retValue += this.getClass().getName() + "("; retValue += "data = " + this.data + TAB; retValue += ")"; return retValue; } // Override public int computeSize() { int totalSize = 0; totalSize += computeNestedMessageSize(); return totalSize; } private int computeNestedMessageSize() { int messageSize = 0; messageSize += ComputeSizeUtil.computeMessageSize(fieldNumberData, data.computeSize()); return messageSize; } // Override public void writeFields(final OutputWriter writer) throws IOException { writer.writeMessage(fieldNumberData, data.computeSize()); data.writeFields(writer); } static TornRowResponse parseFields(final InputReader reader) throws IOException { int nextFieldNumber = getNextFieldNumber(reader); final TornRowResponse.Builder builder = TornRowResponse.newBuilder(); while (nextFieldNumber > 0) { if(!populateBuilderWithField(reader, builder, nextFieldNumber)) { reader.getPreviousTagDataTypeAndReadContent(); } nextFieldNumber = getNextFieldNumber(reader); } return builder.build(); } static int getNextFieldNumber(final InputReader reader) throws IOException { return reader.getNextFieldNumber(); } static boolean populateBuilderWithField(final InputReader reader, final Builder builder, final int fieldNumber) throws IOException { boolean fieldFound = true; switch (fieldNumber) { case fieldNumberData: Vector vcData = reader.readMessages(fieldNumberData); for(int i = 0 ; i < vcData.size(); i++) { byte[] eachBinData = (byte[]) vcData.elementAt(i); SyncHeader.Builder builderData = SyncHeader.newBuilder(); InputReader innerInputReader = new InputReader(eachBinData, unknownTagHandler); boolean boolData = true; int nestedFieldData = -1; while(boolData) { nestedFieldData = getNextFieldNumber(innerInputReader); boolData = SyncHeader.populateBuilderWithField(innerInputReader, builderData, nestedFieldData); } eachBinData = null; innerInputReader = null; builder.setData(builderData.build()); } break; default: fieldFound = false; } return fieldFound; } public static void setUnknownTagHandler(final UnknownTagHandler unknownTagHandler) { TornRowResponse.unknownTagHandler = unknownTagHandler; } public static TornRowResponse parseFrom(final byte[] data) throws IOException { return parseFields(new InputReader(data, unknownTagHandler)); } public static TornRowResponse parseFrom(final InputStream inputStream) throws IOException { return parseFields(new InputReader(inputStream, unknownTagHandler)); } public static TornRowResponse parseDelimitedFrom(final InputStream inputStream) throws IOException { final int limit = DelimitedSizeUtil.readDelimitedSize(inputStream); return parseFields(new InputReader(new DelimitedInputStream(inputStream, limit), unknownTagHandler)); } }
apache-2.0
samaitra/ignite
modules/compatibility/src/test/java/org/apache/ignite/compatibility/testsuites/IgniteCompatibilityBasicTestSuite.java
1919
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.compatibility.testsuites; import org.apache.ignite.compatibility.cache.LocalCacheTest; import org.apache.ignite.compatibility.jdbc.JdbcThinCompatibilityTest; import org.apache.ignite.compatibility.persistence.FoldersReuseCompatibilityTest; import org.apache.ignite.compatibility.persistence.MetaStorageCompatibilityTest; import org.apache.ignite.compatibility.persistence.MigratingToWalV2SerializerWithCompactionTest; import org.apache.ignite.compatibility.persistence.MoveBinaryMetadataCompatibility; import org.apache.ignite.compatibility.persistence.PersistenceBasicCompatibilityTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Compatibility tests basic test suite. */ @RunWith(Suite.class) @Suite.SuiteClasses({ PersistenceBasicCompatibilityTest.class, FoldersReuseCompatibilityTest.class, MigratingToWalV2SerializerWithCompactionTest.class, MetaStorageCompatibilityTest.class, LocalCacheTest.class, MoveBinaryMetadataCompatibility.class, JdbcThinCompatibilityTest.class }) public class IgniteCompatibilityBasicTestSuite { }
apache-2.0
RUB-NDS/Single-Sign-On-Libraries
ssolibs/samllib/src/main/java/org/rub/nds/saml/samllib/utils/SAMLUtils.java
16051
/* * Copyright (C) 2014 Vladislav Mladenov<vladislav.mladenov@rub.de>. * * 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 */ package org.rub.nds.saml.samllib.utils; import java.io.*; import java.util.ArrayList; import java.util.List; import javax.security.cert.CertificateException; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import org.apache.xml.security.exceptions.Base64DecodingException; import org.joda.time.DateTime; import org.opensaml.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.common.IdentifierGenerator; import org.opensaml.common.SAMLObject; import org.opensaml.common.SAMLObjectBuilder; import org.opensaml.common.SignableSAMLObject; import org.opensaml.common.impl.RandomIdentifierGenerator; import org.opensaml.saml2.core.*; import org.opensaml.xml.ConfigurationException; import org.opensaml.xml.XMLObject; import org.opensaml.xml.XMLObjectBuilderFactory; import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.io.UnmarshallingException; import org.opensaml.xml.security.credential.BasicCredential; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.signature.KeyInfo; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.X509Data; import org.opensaml.xml.util.XMLHelper; import org.rub.nds.sso.exceptions.ManagerException; import org.rub.nds.saml.samllib.exceptions.SAMLBuildException; import org.rub.nds.sso.exceptions.WrongInputException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * SAML Utilities needed for the processing of SAML messages * * @author Vladislav Mladenov <vladislav.mladenov@rub.de> */ public final class SAMLUtils { private static final SAMLUtils INSTANCE = new SAMLUtils(); private static XMLObjectBuilderFactory builderFactory = null; private static Logger _log = LoggerFactory.getLogger(SAMLUtils.class); private SAMLUtils() { } /** * returns Instance of the class * * @return */ public static SAMLUtils getInstance() { if (INSTANCE == null) { throw new RuntimeException("No singleton instance available"); } return INSTANCE; } /** * Returns unique ID for a SAML element * * @return unique ID as a String */ public static String getID() { _log.trace(SAMLUtils.class.toString() + ": Generate SAML-ID"); IdentifierGenerator idGenerator = new RandomIdentifierGenerator(); return idGenerator.generateIdentifier(); } /** * Returns the current GMT-time * * @return the current GMT-time */ public static DateTime getDateTime() { _log.trace(SAMLUtils.class.toString() + ": Generate SAML-Timestamp"); return new DateTime(); } /** * Returns a XML-ObjectBuilder to create xml-Elements * * @return XML-ObjectBuilder to create xml-Elements * @throws SAMLBuildException */ public static XMLObjectBuilderFactory getSAMLBuilder() throws SAMLBuildException { if (builderFactory != null) { return builderFactory; } try { DefaultBootstrap.bootstrap(); builderFactory = Configuration.getBuilderFactory(); } catch (ConfigurationException ex) { throw new SAMLBuildException(ex.toString(), ex); } return builderFactory; } /** * Returns a SAML-ObjectBuilder to create saml-Elements * * @param elementName * @return SAML-ObjectBuilder to create saml-Elements * @throws SAMLBuildException */ public static SAMLObjectBuilder getSAMLBuilder(final QName elementName) throws SAMLBuildException { SAMLObjectBuilder samlBuilder; samlBuilder = (SAMLObjectBuilder) getSAMLBuilder().getBuilder(elementName); if (samlBuilder == null) { throw new SAMLBuildException("SAMLObjectBuilder is NULL"); } return samlBuilder; } /** * Returns a SAML-ObjectBuilder to create saml-Elements * * @param elementName * @return SAML-ObjectBuilder to create saml-Elements * @throws SAMLBuildException */ public static SAMLObjectBuilder getSAMLBuilder(final Element elementName) throws SAMLBuildException { SAMLObjectBuilder samlBuilder; samlBuilder = (SAMLObjectBuilder) getSAMLBuilder().getBuilder(elementName); if (samlBuilder == null) { throw new SAMLBuildException("SAMLObjectBuilder is NULL"); } return samlBuilder; } /** * * @param decodedObject * @return * @throws WrongInputException */ public static SAMLObject buildObjectfromString(final String decodedObject) throws WrongInputException { try { DocumentBuilderFactory dbf; DocumentBuilder docBuilder; InputSource is2; Element samlElement; dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); docBuilder = dbf.newDocumentBuilder(); is2 = new InputSource(); is2.setCharacterStream(new StringReader(decodedObject)); samlElement = docBuilder.parse(is2).getDocumentElement(); return (SAMLObject) Configuration.getUnmarshallerFactory().getUnmarshaller(samlElement) .unmarshall(samlElement); } catch (UnmarshallingException | SAXException | IOException | ParserConfigurationException | NullPointerException ex) { throw new WrongInputException(ex.getMessage(), ex); } } /** * * @param authnRequest * @return a list of attributes requested in an AuthnRequest * @throws WrongInputException */ public static List<String> getAuthnRequestAttributes(final AuthnRequest authnRequest) throws WrongInputException { List<String> attributes; attributes = new ArrayList<>(); try { if (authnRequest.getExtensions() != null && !authnRequest.getExtensions().getUnknownXMLObjects().isEmpty()) { List<XMLObject> xmlObjects = authnRequest.getExtensions().getUnknownXMLObjects( Attribute.DEFAULT_ELEMENT_NAME); for (int i = 0; i < xmlObjects.size(); i++) { attributes.add(((Attribute) xmlObjects.get(i)).getName()); } } else { List<XMLObject> xmlObjects = authnRequest.getSubject().getSubjectConfirmations().get(0) .getSubjectConfirmationData().getUnknownXMLObjects(Attribute.DEFAULT_ELEMENT_NAME); for (int i = 0; i < xmlObjects.size(); i++) { attributes.add(((Attribute) xmlObjects.get(i)).getName()); } } } catch (NullPointerException ex) { throw new WrongInputException("Cannot extract Attributes from AuthnRequest!"); } return attributes; } /** * * @param samlObject * @return the Issuer element of a SAMLObject * @throws WrongInputException */ public static String getIssuer(final SAMLObject samlObject) throws WrongInputException { String result = ""; try { if (samlObject instanceof Assertion) { result = ((Assertion) samlObject).getIssuer().getValue(); } else if (samlObject instanceof Response) { result = ((Response) samlObject).getIssuer().getValue(); } else if (samlObject instanceof AuthnRequest) { result = ((AuthnRequest) samlObject).getIssuer().getValue(); } } catch (ClassCastException | NullPointerException ex) { throw new WrongInputException(ex.getMessage(), ex); } return result; } /** * * @param signature * @return * @throws WrongInputException */ public static Credential getCredential(final Signature signature) throws WrongInputException { BasicCredential publicCredential = null; try { // Get the KeyInfo node KeyInfo keyInfo = signature.getKeyInfo(); // Get the list of certificates java.util.List<X509Data> x509List = keyInfo.getX509Datas(); // Pull out the first x509 data element X509Data x509Data = x509List.get(0); // Get the current Issuer Signing certificate String of the current // assertion and current x509Data: String base64BinaryCert = x509Data.getX509Certificates().get(0).getValue(); // Get decoded certificate: byte[] decoded = org.apache.xml.security.utils.Base64.decode(base64BinaryCert); javax.security.cert.X509Certificate x509Certificate; x509Certificate = javax.security.cert.X509Certificate.getInstance(decoded); // Validate the signature based on public key. publicCredential = new BasicCredential(); publicCredential.setPublicKey(x509Certificate.getPublicKey()); } catch (NullPointerException | Base64DecodingException | CertificateException ex) { throw new WrongInputException(ex.getMessage(), ex); } return publicCredential; } /** * * @param obj * @return */ public static boolean isSigned(final SAMLObject obj) { boolean issigned = false; if (obj instanceof Response) { issigned = ((Response) obj).isSigned(); } else if (obj instanceof Assertion) { issigned = ((Assertion) obj).isSigned(); } else if (obj instanceof AuthnRequest) { issigned = ((AuthnRequest) obj).isSigned(); } return issigned; } /** * * @param samlObjects * @return * @throws WrongInputException */ public static List<SignableSAMLObject> isSigned(final List<SAMLObject> samlObjects) throws WrongInputException { List<SignableSAMLObject> signObjects; signObjects = new ArrayList<>(); try { for (SAMLObject obj : samlObjects) { if (isSigned(obj)) { signObjects.add((SignableSAMLObject) obj); } } } catch (NullPointerException ex) { throw new WrongInputException("The list is empty!"); } return signObjects; } /** * * @param obj * @param xpathExpression * @return * @throws WrongInputException */ public static NodeList getHokCertificate(final SAMLObject obj, final String xpathExpression) throws WrongInputException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { NamespaceContext nsContext = new SAMLNamespaceContext(); // nsContext.setPrefix(SAMLConstants.SAML20_PREFIX, // SAMLConstants.SAML20_NS); // nsContext.setPrefix(SAMLConstants.SAML20P_PREFIX, // SAMLConstants.SAML20P_NS); // nsContext.setPrefix("ds", "http://www.w3.org/2000/09/xmldsig#"); xpath.setNamespaceContext(nsContext); XPathExpression xpathExpr = xpath.compile(xpathExpression); return ((NodeList) xpathExpr.evaluate(saml2xml(obj), XPathConstants.NODESET)); } catch (XPathExpressionException | NullPointerException ex) { _log.error("Cannot extract HoK-certificate from SAMLObject", ex); throw new WrongInputException("Cannot extract HoK-certificate from SAMLObject", ex); } } /** * * @param samlObj * @return * @throws WrongInputException */ public static Element saml2xml(final SAMLObject samlObj) throws WrongInputException { try { Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(samlObj); return marshaller.marshall(samlObj); } catch (MarshallingException | NullPointerException ex) { _log.error("Wrong input!", ex); throw new WrongInputException("Wrong input!", ex); } } /** * SAML Printer method<br> * <br> * * @param toPrint * @return converted SAMLObject into String * @throws WrongInputException */ public static String samlObj2String(final SAMLObject toPrint) throws WrongInputException { try { // Now we must build our representation to put into the html form to // be submitted to the idp Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(toPrint); org.w3c.dom.Element authDOM = marshaller.marshall(toPrint); StringWriter rspWrt = new StringWriter(); XMLHelper.writeNode(authDOM, rspWrt); String samlObjectAsString = rspWrt.toString(); return samlObjectAsString; } catch (MarshallingException | NullPointerException ex) { _log.error("Error converting SAMLObject -> String: " + ex); throw new WrongInputException("Error converting SAMLObject -> String", ex); } } /** * * @param authnRequest * @return * @throws WrongInputException */ public static AuthnRequest getAuthnRequest(String authnRequest) throws WrongInputException { try { String inflatedAuthnRequest = HTTPUtils.inflateSamlObject(authnRequest, false); return (AuthnRequest) SAMLUtils.buildObjectfromString(inflatedAuthnRequest); } catch (WrongInputException ex) { _log.error("Cannot retrieve informations from the AuthnRequest", ex); throw new WrongInputException("Cannot retrieve informations from the AuthnRequest"); } } /** * * @param authnRequest * @return * @throws WrongInputException */ public static String getAuthnRequestIssuer(String authnRequest) throws WrongInputException { try { String inflatedAuthnRequest = HTTPUtils.inflateSamlObject(authnRequest, false); AuthnRequest request = (AuthnRequest) SAMLUtils.buildObjectfromString(inflatedAuthnRequest); return getIssuer(request); } catch (WrongInputException ex) { _log.error("Cannot retrieve Issuer from the AuthnRequest", ex); throw new WrongInputException("Cannot retrieve Issuer from the AuthnRequest"); } } public static String getAuthenticatedUser(Response response) throws ManagerException { try { return response.getAssertions().get(0).getSubject().getNameID().getValue(); } catch (NullPointerException ex) { _log.error("No authenticated user was found in the token!", ex); throw new ManagerException("No authenticated user was found in the token!"); } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-iotsitewise/src/main/java/com/amazonaws/services/iotsitewise/model/DetailedErrorCode.java
1903
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotsitewise.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum DetailedErrorCode { INCOMPATIBLE_COMPUTE_LOCATION("INCOMPATIBLE_COMPUTE_LOCATION"), INCOMPATIBLE_FORWARDING_CONFIGURATION("INCOMPATIBLE_FORWARDING_CONFIGURATION"); private String value; private DetailedErrorCode(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return DetailedErrorCode corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static DetailedErrorCode fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (DetailedErrorCode enumEntry : DetailedErrorCode.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
MissionCriticalCloud/cosmic
cosmic-core/server/src/test/java/com/cloud/vpc/MockConfigurationManagerImpl.java
20172
package com.cloud.vpc; import com.cloud.api.command.admin.config.UpdateCfgCmd; import com.cloud.api.command.admin.network.CreateNetworkOfferingCmd; import com.cloud.api.command.admin.network.DeleteNetworkOfferingCmd; import com.cloud.api.command.admin.network.UpdateNetworkOfferingCmd; import com.cloud.api.command.admin.offering.CreateDiskOfferingCmd; import com.cloud.api.command.admin.offering.CreateServiceOfferingCmd; import com.cloud.api.command.admin.offering.DeleteDiskOfferingCmd; import com.cloud.api.command.admin.offering.DeleteServiceOfferingCmd; import com.cloud.api.command.admin.offering.UpdateDiskOfferingCmd; import com.cloud.api.command.admin.offering.UpdateServiceOfferingCmd; import com.cloud.api.command.admin.pod.DeletePodCmd; import com.cloud.api.command.admin.pod.UpdatePodCmd; import com.cloud.api.command.admin.vlan.CreateVlanIpRangeCmd; import com.cloud.api.command.admin.vlan.DedicatePublicIpRangeCmd; import com.cloud.api.command.admin.vlan.DeleteVlanIpRangeCmd; import com.cloud.api.command.admin.vlan.ReleasePublicIpRangeCmd; import com.cloud.api.command.admin.zone.CreateZoneCmd; import com.cloud.api.command.admin.zone.DeleteZoneCmd; import com.cloud.api.command.admin.zone.UpdateZoneCmd; import com.cloud.api.command.user.network.ListNetworkOfferingsCmd; import com.cloud.config.Configuration; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationService; import com.cloud.db.model.Zone; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.legacymodel.dc.DataCenter; import com.cloud.legacymodel.dc.Pod; import com.cloud.legacymodel.dc.Vlan; import com.cloud.legacymodel.domain.Domain; import com.cloud.legacymodel.exceptions.ConcurrentOperationException; import com.cloud.legacymodel.exceptions.InsufficientCapacityException; import com.cloud.legacymodel.exceptions.InvalidParameterValueException; import com.cloud.legacymodel.exceptions.ResourceAllocationException; import com.cloud.legacymodel.exceptions.ResourceUnavailableException; import com.cloud.legacymodel.network.Network.Capability; import com.cloud.legacymodel.network.Network.Provider; import com.cloud.legacymodel.network.Network.Service; import com.cloud.legacymodel.storage.DiskOffering; import com.cloud.legacymodel.user.Account; import com.cloud.legacymodel.utils.Pair; import com.cloud.model.enumeration.AllocationState; import com.cloud.model.enumeration.GuestType; import com.cloud.model.enumeration.NetworkType; import com.cloud.model.enumeration.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDaoImpl; import com.cloud.utils.component.ManagerBase; import javax.inject.Inject; import javax.naming.ConfigurationException; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.stereotype.Component; @Component public class MockConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService { @Inject NetworkOfferingDaoImpl _ntwkOffDao; /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#updateConfiguration(com.cloud.api.commands.UpdateCfgCmd) */ @Override public Configuration updateConfiguration(final UpdateCfgCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createServiceOffering(com.cloud.api.commands.CreateServiceOfferingCmd) */ @Override public ServiceOffering createServiceOffering(final CreateServiceOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#updateServiceOffering(com.cloud.api.commands.UpdateServiceOfferingCmd) */ @Override public ServiceOffering updateServiceOffering(final UpdateServiceOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deleteServiceOffering(com.cloud.api.commands.DeleteServiceOfferingCmd) */ @Override public boolean deleteServiceOffering(final DeleteServiceOfferingCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#updateDiskOffering(com.cloud.api.commands.UpdateDiskOfferingCmd) */ @Override public DiskOffering updateDiskOffering(final UpdateDiskOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deleteDiskOffering(com.cloud.api.commands.DeleteDiskOfferingCmd) */ @Override public boolean deleteDiskOffering(final DeleteDiskOfferingCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createDiskOffering(com.cloud.api.commands.CreateDiskOfferingCmd) */ @Override public DiskOffering createDiskOffering(final CreateDiskOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createPod(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public Pod createPod(final long zoneId, final String name, final String startIp, final String endIp, final String gateway, final String netmask, final String allocationState) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#editPod(com.cloud.api.commands.UpdatePodCmd) */ @Override public Pod editPod(final UpdatePodCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deletePod(com.cloud.api.commands.DeletePodCmd) */ @Override public boolean deletePod(final DeletePodCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createZone(com.cloud.api.commands.CreateZoneCmd) */ @Override public DataCenter createZone(final CreateZoneCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#editZone(com.cloud.api.commands.UpdateZoneCmd) */ @Override public DataCenter editZone(final UpdateZoneCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deleteZone(com.cloud.api.commands.DeleteZoneCmd) */ @Override public boolean deleteZone(final DeleteZoneCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createVlanAndPublicIpRange(com.cloud.api.commands.CreateVlanIpRangeCmd) */ @Override public Vlan createVlanAndPublicIpRange(final CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#markDefaultZone(java.lang.String, long, long) */ @Override public Account markDefaultZone(final String accountName, final long domainId, final long defaultZoneId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deleteVlanIpRange(com.cloud.api.commands.DeleteVlanIpRangeCmd) */ @Override public boolean deleteVlanIpRange(final DeleteVlanIpRangeCmd cmd) { // TODO Auto-generated method stub return false; } @Override public Vlan dedicatePublicIpRange(final DedicatePublicIpRangeCmd cmd) throws ResourceAllocationException { // TODO Auto-generated method stub return null; } @Override public boolean releasePublicIpRange(final ReleasePublicIpRangeCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#createNetworkOffering(com.cloud.api.commands.CreateNetworkOfferingCmd) */ @Override public NetworkOffering createNetworkOffering(final CreateNetworkOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#updateNetworkOffering(com.cloud.api.commands.UpdateNetworkOfferingCmd) */ @Override public NetworkOffering updateNetworkOffering(final UpdateNetworkOfferingCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#searchForNetworkOfferings(com.cloud.api.commands.ListNetworkOfferingsCmd) */ @Override public Pair<List<? extends NetworkOffering>, Integer> searchForNetworkOfferings(final ListNetworkOfferingsCmd cmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#deleteNetworkOffering(com.cloud.api.commands.DeleteNetworkOfferingCmd) */ @Override public boolean deleteNetworkOffering(final DeleteNetworkOfferingCmd cmd) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#getVlanAccount(long) */ @Override public Account getVlanAccount(final long vlanId) { // TODO Auto-generated method stub return null; } @Override public Domain getVlanDomain(final long vlanId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#listNetworkOfferings(com.cloud.network.Networks.TrafficType, boolean) */ @Override public List<? extends NetworkOffering> listNetworkOfferings(final TrafficType trafficType, final boolean systemOnly) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#getDefaultPageSize() */ @Override public Long getDefaultPageSize() { return 500L; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#isOfferingForVpc(com.cloud.offering.NetworkOffering) */ @Override public boolean isOfferingForVpc(final NetworkOffering offering) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#getNetworkOfferingNetworkRate(long) */ @Override public Integer getNetworkOfferingNetworkRate(final long networkOfferingId, final Long dataCenterId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationService#getServiceOfferingNetworkRate(long) */ @Override public Integer getServiceOfferingNetworkRate(final long serviceOfferingId, final Long dataCenterId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#updateConfiguration(long, java.lang.String, java.lang.String, java.lang.String) */ @Override public String updateConfiguration(final long userId, final String name, final String category, final String value, final String scope, final Long resourceId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#createPod(long, java.lang.String, long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java * .lang.String, boolean) */ @Override public HostPodVO createPod(final long userId, final String podName, final long zoneId, final String gateway, final String cidr, final String startIp, final String endIp, final String allocationState, final boolean skipGatewayOverlapCheck) { // TODO Auto-generated method stub return null; } @Override public DataCenterVO createZone(final long userId, final String zoneName, final String dns1, final String dns2, final String internalDns1, final String internalDns2, final String guestCidr, final String domain, final Long domainId, final NetworkType zoneType, final String allocationState, final String networkDomain, final boolean isLocalStorageEnabled, final String ip6Dns1, final String ip6Dns2) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#deleteVlanAndPublicIpRange(long, long, com.cloud.legacymodel.user.Account) */ @Override public boolean deleteVlanAndPublicIpRange(final long userId, final long vlanDbId, final Account caller) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#checkZoneAccess(com.cloud.legacymodel.user.Account, com.cloud.legacymodel.dc.DataCenter) */ @Override public void checkZoneAccess(final Account caller, final Zone zone) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#checkDiskOfferingAccess(com.cloud.legacymodel.user.Account, com.cloud.legacymodel.storage.DiskOffering) */ @Override public void checkDiskOfferingAccess(final Account caller, final DiskOffering dof) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#createNetworkOffering(java.lang.String, java.lang.String, com.cloud.network.Networks.TrafficType, java.lang.String, * boolean, com.cloud.offering.NetworkOffering.Availability, java.lang.Integer, java.util.Map, boolean, com.cloud.legacymodel.network.Network.GuestType, boolean, java.lang.Long, * boolean, java.util.Map, boolean) */ @Override public NetworkOfferingVO createNetworkOffering(final String name, final String displayText, final TrafficType trafficType, final String tags, final boolean specifyVlan, final Availability availability, final Integer networkRate, final Map<Service, Set<Provider>> serviceProviderMap, final boolean isDefault, final GuestType type, final boolean systemOnly, final Long serviceOfferingId, final Long secondaryServiceOfferingId, final boolean conserveMode, final Map<Service, Map<Capability, String>> serviceCapabilityMap, final boolean specifyIpRanges, final boolean isPersistent, final Map<NetworkOffering.Detail, String> details, final boolean egressDefaultPolicy, final Integer maxconn, final boolean enableKeepAlive) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#createVlanAndPublicIpRange(long, long, long, boolean, java.lang.Long, java.lang.String, java.lang.String, java.lang * .String, java.lang.String, java.lang.String, com.cloud.legacymodel.user.Account) */ @Override public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final boolean forVirtualNetwork, final Long podId, final String startIP, final String endIP, final String vlanGateway, final String vlanNetmask, final String vlanId, final Domain domain, final Account vlanOwner, final String startIPv6, final String endIPv6, final String vlanGatewayv6, final String vlanCidrv6) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#createDefaultSystemNetworks(long) */ @Override public void createDefaultSystemNetworks(final long zoneId) throws ConcurrentOperationException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#deleteAccountSpecificVirtualRanges(long) */ @Override public boolean releaseAccountSpecificVirtualRanges(final long accountId) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#editPod(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Override public Pod editPod(final long id, final String name, final String startIp, final String endIp, final String gateway, final String netmask, final String allocationStateStr) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#checkPodCidrSubnets(long, java.lang.Long, java.lang.String) */ @Override public void checkPodCidrSubnets(final long zoneId, final Long podIdToBeSkipped, final String cidr) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#findPodAllocationState(com.cloud.dc.HostPodVO) */ @Override public AllocationState findPodAllocationState(final HostPodVO pod) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.configuration.ConfigurationManager#findClusterAllocationState(com.cloud.dc.ClusterVO) */ @Override public AllocationState findClusterAllocationState(final ClusterVO cluster) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.utils.component.Manager#getName() */ @Override public String getName() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see com.cloud.utils.component.Manager#configure(java.lang.String, java.util.Map) */ @Override public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { // TODO Auto-generated method stub return true; } /* (non-Javadoc) * @see com.cloud.utils.component.Manager#start() */ @Override public boolean start() { // TODO Auto-generated method stub return true; } /* (non-Javadoc) * @see com.cloud.utils.component.Manager#stop() */ @Override public boolean stop() { // TODO Auto-generated method stub return true; } }
apache-2.0
Syncleus/aparapi
src/test/java/com/aparapi/codegen/test/ForAsFirstTest.java
1602
/** * Copyright (c) 2016 - 2018 Syncleus, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aparapi.codegen.test; import org.junit.Test; public class ForAsFirstTest extends com.aparapi.codegen.CodeGenJUnitBase { private static final String[] expectedOpenCL = { "typedef struct This_s{\n" + "\n" + " int passid;\n" + " }This;\n" + " int get_pass_id(This *this){\n" + " return this->passid;\n" + " }\n" + "\n" + " __kernel void run(\n" + " int passid\n" + " ){\n" + " This thisStruct;\n" + " This* this=&thisStruct;\n" + " this->passid = passid;\n" + " {\n" + " for (int i = 0; i<1; i++){\n" + " }\n" + " return;\n" + " }\n" + " }\n" + " "}; private static final Class<? extends com.aparapi.internal.exception.AparapiException> expectedException = null; @Test public void ForAsFirstTest() { test(com.aparapi.codegen.test.ForAsFirst.class, expectedException, expectedOpenCL); } @Test public void ForAsFirstTestWorksWithCaching() { test(com.aparapi.codegen.test.ForAsFirst.class, expectedException, expectedOpenCL); } }
apache-2.0
jkrasnay/panelized
src/main/java/ca/krasnay/panelized/datatable/EnumColumn.java
1463
package ca.krasnay.panelized.datatable; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import ca.krasnay.panelized.EnumLabel; import ca.krasnay.panelized.EnumUtils; /** * Column displaying an enum value using an EnumLabel component. See * {@link EnumLabel} and {@link EnumUtils} for more information about how the * column value is determined. * * @author john */ public class EnumColumn<T, E extends Enum<E>> extends AbstractColumn<T, String> { private Class<E> enumClass; private String propertyExpression; public EnumColumn(IModel<String> displayModel, Class<E> enumClass, String sortProperty, String propertyExpression) { super(displayModel, sortProperty); this.enumClass = enumClass; this.propertyExpression = propertyExpression; } public EnumColumn(IModel<String> displayModel, Class<E> enumClass, String propertyExpression) { this(displayModel, enumClass, null, propertyExpression); } @Override public void populateItem(Item<ICellPopulator<T>> cellItem, String componentId, IModel<T> rowModel) { cellItem.add(new EnumLabel<E>(componentId, enumClass, new PropertyModel<Object>(rowModel, propertyExpression))); } }
apache-2.0
isomorphic-software/isc-maven-plugin
src/main/java/com/isomorphic/maven/packaging/License.java
1560
package com.isomorphic.maven.packaging; /* * 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. */ /** * An Isomorphic product 'edition'. * <p> * Refer to http://www.smartclient.com/product/editions.jsp */ public enum License { LGPL("LGPL"), EVAL("Eval"), PRO("Pro"), POWER("PowerEdition", "power"), ENTERPRISE("Enterprise"), ANALYTICS_MODULE("AnalyticsModule", "analytics"), MESSAGING_MODULE("RealtimeMessagingModule", "messaging"); String label; String name; private License(String label) { this(label, label); } private License(String label, String name) { this.label = label; this.name = name.toLowerCase(); } @Override public String toString() { return getLabel(); } public String getLabel() { return label; } public String getName() { return name; } }
apache-2.0
hekate-io/hekate
hekate-core/src/main/java/io/hekate/core/HekateSupport.java
960
/* * Copyright 2022 The Hekate Project * * The Hekate 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.hekate.core; /** * Marker interface for components that can provide a reference to the {@link Hekate} instance that those components belong to. */ public interface HekateSupport { /** * Returns the {@link Hekate} instance. * * @return {@link Hekate} instance. */ Hekate hekate(); }
apache-2.0
google/tsunami-security-scanner-plugins
google/fingerprinters/web/src/main/java/com/google/tsunami/plugins/fingerprinters/web/crawl/SimpleCrawlerSchedulingPool.java
956
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugins.fingerprinters.web.crawl; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Qualifier; /** Annotates the thread pool for scheduling the crawling workers of the {@link SimpleCrawler}. */ @Qualifier @Retention(RetentionPolicy.RUNTIME) @interface SimpleCrawlerSchedulingPool {}
apache-2.0
Ariah-Group/Continuity
src/test/java/org/kuali/continuity/service/ItemServiceTest2.java
2676
// // Copyright 2011 Kuali Foundation, Inc. Licensed under the // Educational Community License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. You may // obtain a copy of the License at // // http://www.opensource.org/licenses/ecl2.php // // 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.kuali.continuity.service; import java.util.HashMap; import java.util.List; import java.util.Set; import org.kuali.continuity.admin.dao.AdminDAOTest; import org.kuali.continuity.admin.dao.ItemDaoFactory; import org.kuali.continuity.admin.dao.MapGetter; import org.kuali.continuity.admin.main.client.DependencyItem; import org.kuali.continuity.admin.main.client.Item; import org.kuali.continuity.admin.main.client.ItemService; import org.kuali.continuity.admin.main.client.SimpleService; import org.kuali.continuity.domain.OrderedType; public class ItemServiceTest2 extends AdminDAOTest { ItemService itemService; SimpleService simpleService; public void setSimpleService(SimpleService simpleService) { this.simpleService = simpleService; } ItemDaoFactory itemDaoFactory; public void setItemDaoFactory(ItemDaoFactory itemDaoFactory) { this.itemDaoFactory = itemDaoFactory; } public void setItemService(ItemService itemService) { this.itemService = itemService; } public void testInjection() { System.out.println("Start"); System.out.println(itemService.getClass().getName()); // System.out.println(listService.getClass().getName()); } public void testSkills() { ListService itemListService = (ListService) itemService; List skillList = itemListService.getSortedList("skill", 1, "name", 999, "ASC", 1); for (Object s: skillList) { System.out.println(s.getClass().getSimpleName()); } } public void testDependency() { ListService itemListService = (ListService) itemService; List<DependencyItem> dList = itemListService.getSortedList("dependency", 1, "name", 999, "ASC", 1); for (DependencyItem s: dList) { System.out.println(s.getName()+" "+s.getDescription()+s.getType()+" "+s.getOrderNo()); } DependencyItem di = (DependencyItem) itemService.getItem("dependency", "85"); System.out.println(di.getDescription()+" "+di.getName()+" "+di.getType()); } }
apache-2.0
adelapena/cassandra_2i
src/java/org/apache/cassandra/tools/NodeProbe.java
35751
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.tools; import java.io.IOException; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.management.RuntimeMXBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import javax.management.*; import javax.management.openmbean.CompositeData; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.management.openmbean.TabularData; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutorMBean; import org.apache.cassandra.db.ColumnFamilyStoreMBean; import org.apache.cassandra.db.HintedHandOffManager; import org.apache.cassandra.db.HintedHandOffManagerMBean; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.CompactionManagerMBean; import org.apache.cassandra.gms.FailureDetector; import org.apache.cassandra.gms.FailureDetectorMBean; import org.apache.cassandra.locator.EndpointSnitchInfoMBean; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.net.MessagingServiceMBean; import org.apache.cassandra.service.*; import org.apache.cassandra.streaming.StreamState; import org.apache.cassandra.streaming.StreamManagerMBean; import org.apache.cassandra.streaming.management.StreamStateCompositeData; import org.apache.cassandra.utils.SimpleCondition; /** * JMX client operations for Cassandra. */ public class NodeProbe { private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; private static final String ssObjName = "org.apache.cassandra.db:type=StorageService"; private static final int defaultPort = 7199; final String host; final int port; private String username; private String password; private JMXConnector jmxc; private MBeanServerConnection mbeanServerConn; private CompactionManagerMBean compactionProxy; private StorageServiceMBean ssProxy; private MemoryMXBean memProxy; private RuntimeMXBean runtimeProxy; private StreamManagerMBean streamProxy; public MessagingServiceMBean msProxy; private FailureDetectorMBean fdProxy; private CacheServiceMBean cacheService; private StorageProxyMBean spProxy; private HintedHandOffManagerMBean hhProxy; private boolean failed; /** * Creates a NodeProbe using the specified JMX host, port, username, and password. * * @param host hostname or IP address of the JMX agent * @param port TCP port of the remote JMX agent * @throws IOException on connection failures */ public NodeProbe(String host, int port, String username, String password) throws IOException { assert username != null && !username.isEmpty() && password != null && !password.isEmpty() : "neither username nor password can be blank"; this.host = host; this.port = port; this.username = username; this.password = password; connect(); } /** * Creates a NodeProbe using the specified JMX host and port. * * @param host hostname or IP address of the JMX agent * @param port TCP port of the remote JMX agent * @throws IOException on connection failures */ public NodeProbe(String host, int port) throws IOException { this.host = host; this.port = port; connect(); } /** * Creates a NodeProbe using the specified JMX host and default port. * * @param host hostname or IP address of the JMX agent * @throws IOException on connection failures */ public NodeProbe(String host) throws IOException { this.host = host; this.port = defaultPort; connect(); } /** * Create a connection to the JMX agent and setup the M[X]Bean proxies. * * @throws IOException on connection failures */ private void connect() throws IOException { JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port)); Map<String,Object> env = new HashMap<String,Object>(); if (username != null) { String[] creds = { username, password }; env.put(JMXConnector.CREDENTIALS, creds); } jmxc = JMXConnectorFactory.connect(jmxUrl, env); mbeanServerConn = jmxc.getMBeanServerConnection(); try { ObjectName name = new ObjectName(ssObjName); ssProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageServiceMBean.class); name = new ObjectName(MessagingService.MBEAN_NAME); msProxy = JMX.newMBeanProxy(mbeanServerConn, name, MessagingServiceMBean.class); name = new ObjectName(StreamManagerMBean.OBJECT_NAME); streamProxy = JMX.newMBeanProxy(mbeanServerConn, name, StreamManagerMBean.class); name = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME); compactionProxy = JMX.newMBeanProxy(mbeanServerConn, name, CompactionManagerMBean.class); name = new ObjectName(FailureDetector.MBEAN_NAME); fdProxy = JMX.newMBeanProxy(mbeanServerConn, name, FailureDetectorMBean.class); name = new ObjectName(CacheService.MBEAN_NAME); cacheService = JMX.newMBeanProxy(mbeanServerConn, name, CacheServiceMBean.class); name = new ObjectName(StorageProxy.MBEAN_NAME); spProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageProxyMBean.class); name = new ObjectName(HintedHandOffManager.MBEAN_NAME); hhProxy = JMX.newMBeanProxy(mbeanServerConn, name, HintedHandOffManagerMBean.class); } catch (MalformedObjectNameException e) { throw new RuntimeException( "Invalid ObjectName? Please report this as a bug.", e); } memProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); runtimeProxy = ManagementFactory.newPlatformMXBeanProxy( mbeanServerConn, ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class); } public void close() throws IOException { jmxc.close(); } public void forceKeyspaceCleanup(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException { ssProxy.forceKeyspaceCleanup(keyspaceName, columnFamilies); } public void scrub(boolean disableSnapshot, String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException { ssProxy.scrub(disableSnapshot, keyspaceName, columnFamilies); } public void upgradeSSTables(String keyspaceName, boolean excludeCurrentVersion, String... columnFamilies) throws IOException, ExecutionException, InterruptedException { ssProxy.upgradeSSTables(keyspaceName, excludeCurrentVersion, columnFamilies); } public void forceKeyspaceCompaction(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException { ssProxy.forceKeyspaceCompaction(keyspaceName, columnFamilies); } public void forceKeyspaceFlush(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException { ssProxy.forceKeyspaceFlush(keyspaceName, columnFamilies); } public void forceKeyspaceRepair(String keyspaceName, boolean isSequential, boolean isLocal, String... columnFamilies) throws IOException { ssProxy.forceKeyspaceRepair(keyspaceName, isSequential, isLocal, columnFamilies); } public void forceRepairAsync(final PrintStream out, final String keyspaceName, boolean isSequential, Collection<String> dataCenters, boolean primaryRange, String... columnFamilies) throws IOException { RepairRunner runner = new RepairRunner(out, keyspaceName, columnFamilies); try { jmxc.addConnectionNotificationListener(runner, null, null); ssProxy.addNotificationListener(runner, null, null); if (!runner.repairAndWait(ssProxy, isSequential, dataCenters, primaryRange)) failed = true; } catch (Exception e) { throw new IOException(e) ; } finally { try { ssProxy.removeNotificationListener(runner); jmxc.removeConnectionNotificationListener(runner); } catch (Throwable ignored) {} } } public void forceRepairRangeAsync(final PrintStream out, final String keyspaceName, boolean isSequential, Collection<String> dataCenters, final String startToken, final String endToken, String... columnFamilies) throws IOException { RepairRunner runner = new RepairRunner(out, keyspaceName, columnFamilies); try { jmxc.addConnectionNotificationListener(runner, null, null); ssProxy.addNotificationListener(runner, null, null); if (!runner.repairRangeAndWait(ssProxy, isSequential, dataCenters, startToken, endToken)) failed = true; } catch (Exception e) { throw new IOException(e) ; } finally { try { ssProxy.removeNotificationListener(runner); jmxc.removeConnectionNotificationListener(runner); } catch (Throwable ignored) {} } } public void forceKeyspaceRepairPrimaryRange(String keyspaceName, boolean isSequential, boolean isLocal, String... columnFamilies) throws IOException { ssProxy.forceKeyspaceRepairPrimaryRange(keyspaceName, isSequential, isLocal, columnFamilies); } public void forceKeyspaceRepairRange(String beginToken, String endToken, String keyspaceName, boolean isSequential, boolean isLocal, String... columnFamilies) throws IOException { ssProxy.forceKeyspaceRepairRange(beginToken, endToken, keyspaceName, isSequential, isLocal, columnFamilies); } public void invalidateKeyCache() { cacheService.invalidateKeyCache(); } public void invalidateRowCache() { cacheService.invalidateRowCache(); } public void drain() throws IOException, InterruptedException, ExecutionException { ssProxy.drain(); } public Map<String, String> getTokenToEndpointMap() { return ssProxy.getTokenToEndpointMap(); } public List<String> getLiveNodes() { return ssProxy.getLiveNodes(); } public List<String> getJoiningNodes() { return ssProxy.getJoiningNodes(); } public List<String> getLeavingNodes() { return ssProxy.getLeavingNodes(); } public List<String> getMovingNodes() { return ssProxy.getMovingNodes(); } public List<String> getUnreachableNodes() { return ssProxy.getUnreachableNodes(); } public Map<String, String> getLoadMap() { return ssProxy.getLoadMap(); } public Map<InetAddress, Float> getOwnership() { return ssProxy.getOwnership(); } public Map<InetAddress, Float> effectiveOwnership(String keyspace) throws IllegalStateException { return ssProxy.effectiveOwnership(keyspace); } public CacheServiceMBean getCacheServiceMBean() { String cachePath = "org.apache.cassandra.db:type=Caches"; try { return JMX.newMBeanProxy(mbeanServerConn, new ObjectName(cachePath), CacheServiceMBean.class); } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } } public Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> getColumnFamilyStoreMBeanProxies() { try { return new ColumnFamilyStoreMBeanIterator(mbeanServerConn); } catch (MalformedObjectNameException e) { throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e); } catch (IOException e) { throw new RuntimeException("Could not retrieve list of stat mbeans.", e); } } public CompactionManagerMBean getCompactionManagerProxy() { return compactionProxy; } public List<String> getTokens() { return ssProxy.getTokens(); } public List<String> getTokens(String endpoint) { try { return ssProxy.getTokens(endpoint); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public String getLocalHostId() { return ssProxy.getLocalHostId(); } public Map<String, String> getHostIdMap() { return ssProxy.getHostIdMap(); } public String getLoadString() { return ssProxy.getLoadString(); } public String getReleaseVersion() { return ssProxy.getReleaseVersion(); } public int getCurrentGenerationNumber() { return ssProxy.getCurrentGenerationNumber(); } public long getUptime() { return runtimeProxy.getUptime(); } public MemoryUsage getHeapMemoryUsage() { return memProxy.getHeapMemoryUsage(); } /** * Take a snapshot of all the keyspaces, optionally specifying only a specific column family. * * @param snapshotName the name of the snapshot. * @param columnFamily the column family to snapshot or all on null * @param keyspaces the keyspaces to snapshot */ public void takeSnapshot(String snapshotName, String columnFamily, String... keyspaces) throws IOException { if (columnFamily != null) { if (keyspaces.length != 1) { throw new IOException("When specifying the column family for a snapshot, you must specify one and only one keyspace"); } ssProxy.takeColumnFamilySnapshot(keyspaces[0], columnFamily, snapshotName); } else ssProxy.takeSnapshot(snapshotName, keyspaces); } /** * Remove all the existing snapshots. */ public void clearSnapshot(String tag, String... keyspaces) throws IOException { ssProxy.clearSnapshot(tag, keyspaces); } public boolean isJoined() { return ssProxy.isJoined(); } public void joinRing() throws IOException { ssProxy.joinRing(); } public void decommission() throws InterruptedException { ssProxy.decommission(); } public void move(String newToken) throws IOException { ssProxy.move(newToken); } public void removeNode(String token) { ssProxy.removeNode(token); } public String getRemovalStatus() { return ssProxy.getRemovalStatus(); } public void forceRemoveCompletion() { ssProxy.forceRemoveCompletion(); } public Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>> getThreadPoolMBeanProxies() { try { return new ThreadPoolProxyMBeanIterator(mbeanServerConn); } catch (MalformedObjectNameException e) { throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e); } catch (IOException e) { throw new RuntimeException("Could not retrieve list of stat mbeans.", e); } } /** * Set the compaction threshold * * @param minimumCompactionThreshold minimum compaction threshold * @param maximumCompactionThreshold maximum compaction threshold */ public void setCompactionThreshold(String ks, String cf, int minimumCompactionThreshold, int maximumCompactionThreshold) { ColumnFamilyStoreMBean cfsProxy = getCfsProxy(ks, cf); cfsProxy.setCompactionThresholds(minimumCompactionThreshold, maximumCompactionThreshold); } public void disableAutoCompaction(String ks, String ... columnFamilies) throws IOException { ssProxy.disableAutoCompaction(ks, columnFamilies); } public void enableAutoCompaction(String ks, String ... columnFamilies) throws IOException { ssProxy.enableAutoCompaction(ks, columnFamilies); } public void setIncrementalBackupsEnabled(boolean enabled) { ssProxy.setIncrementalBackupsEnabled(enabled); } public void setCacheCapacities(int keyCacheCapacity, int rowCacheCapacity) { try { String keyCachePath = "org.apache.cassandra.db:type=Caches"; CacheServiceMBean cacheMBean = JMX.newMBeanProxy(mbeanServerConn, new ObjectName(keyCachePath), CacheServiceMBean.class); cacheMBean.setKeyCacheCapacityInMB(keyCacheCapacity); cacheMBean.setRowCacheCapacityInMB(rowCacheCapacity); } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } } public void setCacheKeysToSave(int keyCacheKeysToSave, int rowCacheKeysToSave) { try { String keyCachePath = "org.apache.cassandra.db:type=Caches"; CacheServiceMBean cacheMBean = JMX.newMBeanProxy(mbeanServerConn, new ObjectName(keyCachePath), CacheServiceMBean.class); cacheMBean.setKeyCacheKeysToSave(keyCacheKeysToSave); cacheMBean.setRowCacheKeysToSave(rowCacheKeysToSave); } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } } public List<InetAddress> getEndpoints(String keyspace, String cf, String key) { return ssProxy.getNaturalEndpoints(keyspace, cf, key); } public List<String> getSSTables(String keyspace, String cf, String key) { ColumnFamilyStoreMBean cfsProxy = getCfsProxy(keyspace, cf); return cfsProxy.getSSTablesForKey(key); } public Set<StreamState> getStreamStatus() { return Sets.newHashSet(Iterables.transform(streamProxy.getCurrentStreams(), new Function<CompositeData, StreamState>() { public StreamState apply(CompositeData input) { return StreamStateCompositeData.fromCompositeData(input); } })); } public String getOperationMode() { return ssProxy.getOperationMode(); } public void truncate(String keyspaceName, String cfName) { try { ssProxy.truncate(keyspaceName, cfName); } catch (TimeoutException e) { throw new RuntimeException("Error while executing truncate", e); } catch (IOException e) { throw new RuntimeException("Error while executing truncate", e); } } public EndpointSnitchInfoMBean getEndpointSnitchInfoProxy() { try { return JMX.newMBeanProxy(mbeanServerConn, new ObjectName("org.apache.cassandra.db:type=EndpointSnitchInfo"), EndpointSnitchInfoMBean.class); } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } } public ColumnFamilyStoreMBean getCfsProxy(String ks, String cf) { ColumnFamilyStoreMBean cfsProxy = null; try { String type = cf.contains(".") ? "IndexColumnFamilies" : "ColumnFamilies"; Set<ObjectName> beans = mbeanServerConn.queryNames( new ObjectName("org.apache.cassandra.db:type=*" + type +",keyspace=" + ks + ",columnfamily=" + cf), null); if (beans.isEmpty()) throw new MalformedObjectNameException("couldn't find that bean"); assert beans.size() == 1; for (ObjectName bean : beans) cfsProxy = JMX.newMBeanProxy(mbeanServerConn, bean, ColumnFamilyStoreMBean.class); } catch (MalformedObjectNameException mone) { System.err.println("ColumnFamilyStore for " + ks + "/" + cf + " not found."); System.exit(1); } catch (IOException e) { System.err.println("ColumnFamilyStore for " + ks + "/" + cf + " not found: " + e); System.exit(1); } return cfsProxy; } public StorageProxyMBean getSpProxy() { return spProxy; } public String getEndpoint() { // Try to find the endpoint using the local token, doing so in a crazy manner // to maintain backwards compatibility with the MBean interface String stringToken = ssProxy.getTokens().get(0); Map<String, String> tokenToEndpoint = ssProxy.getTokenToEndpointMap(); for (Map.Entry<String, String> pair : tokenToEndpoint.entrySet()) { if (pair.getKey().toString().equals(stringToken)) { return pair.getValue(); } } throw new RuntimeException("Could not find myself in the endpoint list, something is very wrong! Is the Cassandra node fully started?"); } public String getDataCenter() { try { return getEndpointSnitchInfoProxy().getDatacenter(getEndpoint()); } catch (UnknownHostException e) { return "Unknown"; } } public String getRack() { try { return getEndpointSnitchInfoProxy().getRack(getEndpoint()); } catch (UnknownHostException e) { return "Unknown"; } } public List<String> getKeyspaces() { return ssProxy.getKeyspaces(); } public String getClusterName() { return ssProxy.getClusterName(); } public String getPartitioner() { return ssProxy.getPartitionerName(); } public void disableHintedHandoff() { spProxy.setHintedHandoffEnabled(false); } public void enableHintedHandoff() { spProxy.setHintedHandoffEnabled(true); } public void pauseHintsDelivery() { hhProxy.pauseHintsDelivery(true); } public void resumeHintsDelivery() { hhProxy.pauseHintsDelivery(false); } public void truncateHints(final String host) { hhProxy.deleteHintsForEndpoint(host); } public void truncateHints() { try { hhProxy.truncateAllHints(); } catch (ExecutionException e) { throw new RuntimeException("Error while executing truncate hints", e); } catch (InterruptedException e) { throw new RuntimeException("Error while executing truncate hints", e); } } public void stopNativeTransport() { ssProxy.stopNativeTransport(); } public void startNativeTransport() { ssProxy.startNativeTransport(); } public boolean isNativeTransportRunning() { return ssProxy.isNativeTransportRunning(); } public void stopGossiping() { ssProxy.stopGossiping(); } public void startGossiping() { ssProxy.startGossiping(); } public void stopThriftServer() { ssProxy.stopRPCServer(); } public void startThriftServer() { ssProxy.startRPCServer(); } public boolean isThriftServerRunning() { return ssProxy.isRPCServerRunning(); } public void stopCassandraDaemon() { ssProxy.stopDaemon(); } public boolean isInitialized() { return ssProxy.isInitialized(); } public void setCompactionThroughput(int value) { ssProxy.setCompactionThroughputMbPerSec(value); } public int getCompactionThroughput() { return ssProxy.getCompactionThroughputMbPerSec(); } public int getStreamThroughput() { return ssProxy.getStreamThroughputMbPerSec(); } public int getExceptionCount() { return ssProxy.getExceptionCount(); } public Map<String, Integer> getDroppedMessages() { return msProxy.getDroppedMessages(); } public void loadNewSSTables(String ksName, String cfName) { ssProxy.loadNewSSTables(ksName, cfName); } public void rebuildIndex(String ksName, String cfName, String... idxNames) { ssProxy.rebuildSecondaryIndex(ksName, cfName, idxNames); } public String getGossipInfo() { return fdProxy.getAllEndpointStates(); } public void stop(String string) { compactionProxy.stopCompaction(string); } public void setStreamThroughput(int value) { ssProxy.setStreamThroughputMbPerSec(value); } public void setTraceProbability(double value) { ssProxy.setTraceProbability(value); } public String getSchemaVersion() { return ssProxy.getSchemaVersion(); } public List<String> describeRing(String keyspaceName) throws IOException { return ssProxy.describeRingJMX(keyspaceName); } public void rebuild(String sourceDc) { ssProxy.rebuild(sourceDc); } public List<String> sampleKeyRange() { return ssProxy.sampleKeyRange(); } public void resetLocalSchema() throws IOException { ssProxy.resetLocalSchema(); } public boolean isFailed() { return failed; } public long getReadRepairAttempted() { return spProxy.getReadRepairAttempted(); } public long getReadRepairRepairedBlocking() { return spProxy.getReadRepairRepairedBlocking(); } public long getReadRepairRepairedBackground() { return spProxy.getReadRepairRepairedBackground(); } public TabularData getCompactionHistory() { return compactionProxy.getCompactionHistory(); } public void reloadTriggers() { spProxy.reloadTriggerClasses(); } } class ColumnFamilyStoreMBeanIterator implements Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> { private MBeanServerConnection mbeanServerConn; Iterator<Entry<String, ColumnFamilyStoreMBean>> mbeans; public ColumnFamilyStoreMBeanIterator(MBeanServerConnection mbeanServerConn) throws MalformedObjectNameException, NullPointerException, IOException { this.mbeanServerConn = mbeanServerConn; List<Entry<String, ColumnFamilyStoreMBean>> cfMbeans = getCFSMBeans(mbeanServerConn, "ColumnFamilies"); cfMbeans.addAll(getCFSMBeans(mbeanServerConn, "IndexColumnFamilies")); Collections.sort(cfMbeans, new Comparator<Entry<String, ColumnFamilyStoreMBean>>() { public int compare(Entry<String, ColumnFamilyStoreMBean> e1, Entry<String, ColumnFamilyStoreMBean> e2) { //compare keyspace, then CF name, then normal vs. index int keyspaceNameCmp = e1.getKey().compareTo(e2.getKey()); if(keyspaceNameCmp != 0) return keyspaceNameCmp; // get CF name and split it for index name String e1CF[] = e1.getValue().getColumnFamilyName().split("\\."); String e2CF[] = e1.getValue().getColumnFamilyName().split("\\."); assert e1CF.length <= 2 && e2CF.length <= 2 : "unexpected split count for column family name"; //if neither are indexes, just compare CF names if(e1CF.length == 1 && e2CF.length == 1) return e1CF[0].compareTo(e2CF[0]); //check if it's the same CF int cfNameCmp = e1CF[0].compareTo(e2CF[0]); if(cfNameCmp != 0) return cfNameCmp; // if both are indexes (for the same CF), compare them if(e1CF.length == 2 && e2CF.length == 2) return e1CF[1].compareTo(e2CF[1]); //if length of e1CF is 1, it's not an index, so sort it higher return e1CF.length == 1 ? 1 : -1; } }); mbeans = cfMbeans.iterator(); } private List<Entry<String, ColumnFamilyStoreMBean>> getCFSMBeans(MBeanServerConnection mbeanServerConn, String type) throws MalformedObjectNameException, IOException { ObjectName query = new ObjectName("org.apache.cassandra.db:type=" + type +",*"); Set<ObjectName> cfObjects = mbeanServerConn.queryNames(query, null); List<Entry<String, ColumnFamilyStoreMBean>> mbeans = new ArrayList<Entry<String, ColumnFamilyStoreMBean>>(cfObjects.size()); for(ObjectName n : cfObjects) { String keyspaceName = n.getKeyProperty("keyspace"); ColumnFamilyStoreMBean cfsProxy = JMX.newMBeanProxy(mbeanServerConn, n, ColumnFamilyStoreMBean.class); mbeans.add(new AbstractMap.SimpleImmutableEntry<String, ColumnFamilyStoreMBean>(keyspaceName, cfsProxy)); } return mbeans; } public boolean hasNext() { return mbeans.hasNext(); } public Entry<String, ColumnFamilyStoreMBean> next() { return mbeans.next(); } public void remove() { throw new UnsupportedOperationException(); } } class ThreadPoolProxyMBeanIterator implements Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>> { private final Iterator<ObjectName> resIter; private final MBeanServerConnection mbeanServerConn; public ThreadPoolProxyMBeanIterator(MBeanServerConnection mbeanServerConn) throws MalformedObjectNameException, NullPointerException, IOException { Set<ObjectName> requests = mbeanServerConn.queryNames(new ObjectName("org.apache.cassandra.request:type=*"), null); Set<ObjectName> internal = mbeanServerConn.queryNames(new ObjectName("org.apache.cassandra.internal:type=*"), null); resIter = Iterables.concat(requests, internal).iterator(); this.mbeanServerConn = mbeanServerConn; } public boolean hasNext() { return resIter.hasNext(); } public Map.Entry<String, JMXEnabledThreadPoolExecutorMBean> next() { ObjectName objectName = resIter.next(); String poolName = objectName.getKeyProperty("type"); JMXEnabledThreadPoolExecutorMBean threadPoolProxy = JMX.newMBeanProxy(mbeanServerConn, objectName, JMXEnabledThreadPoolExecutorMBean.class); return new AbstractMap.SimpleImmutableEntry<String, JMXEnabledThreadPoolExecutorMBean>(poolName, threadPoolProxy); } public void remove() { throw new UnsupportedOperationException(); } } class RepairRunner implements NotificationListener { private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); private final Condition condition = new SimpleCondition(); private final PrintStream out; private final String keyspace; private final String[] columnFamilies; private int cmd; private volatile boolean success = true; private volatile Exception error = null; RepairRunner(PrintStream out, String keyspace, String... columnFamilies) { this.out = out; this.keyspace = keyspace; this.columnFamilies = columnFamilies; } public boolean repairAndWait(StorageServiceMBean ssProxy, boolean isSequential, Collection<String> dataCenters, boolean primaryRangeOnly) throws Exception { cmd = ssProxy.forceRepairAsync(keyspace, isSequential, dataCenters, primaryRangeOnly, columnFamilies); waitForRepair(); return success; } public boolean repairRangeAndWait(StorageServiceMBean ssProxy, boolean isSequential, Collection<String> dataCenters, String startToken, String endToken) throws Exception { cmd = ssProxy.forceRepairRangeAsync(startToken, endToken, keyspace, isSequential, dataCenters, columnFamilies); waitForRepair(); return success; } private void waitForRepair() throws Exception { if (cmd > 0) { condition.await(); } else { String message = String.format("[%s] Nothing to repair for keyspace '%s'", format.format(System.currentTimeMillis()), keyspace); out.println(message); } if (error != null) { throw error; } } public void handleNotification(Notification notification, Object handback) { if ("repair".equals(notification.getType())) { int[] status = (int[]) notification.getUserData(); assert status.length == 2; if (cmd == status[0]) { String message = String.format("[%s] %s", format.format(notification.getTimeStamp()), notification.getMessage()); out.println(message); // repair status is int array with [0] = cmd number, [1] = status if (status[1] == ActiveRepairService.Status.SESSION_FAILED.ordinal()) success = false; else if (status[1] == ActiveRepairService.Status.FINISHED.ordinal()) condition.signalAll(); } } else if (JMXConnectionNotification.NOTIFS_LOST.equals(notification.getType())) { String message = String.format("[%s] Lost notification. You should check server log for repair status of keyspace %s", format.format(notification.getTimeStamp()), keyspace); out.println(message); success = false; condition.signalAll(); } else if (JMXConnectionNotification.FAILED.equals(notification.getType()) || JMXConnectionNotification.CLOSED.equals(notification.getType())) { String message = String.format("JMX connection closed. You should check server log for repair status of keyspace %s" + "(Subsequent keyspaces are not going to be repaired).", keyspace); error = new IOException(message); condition.signalAll(); } } }
apache-2.0
ohsu-computational-biology/compliance
cts-java/src/test/java/org/ga4gh/cts/api/Utils.java
42895
package org.ga4gh.cts.api; import com.google.protobuf.InvalidProtocolBufferException; import com.mashape.unirest.http.exceptions.UnirestException; import org.assertj.core.api.ThrowableAssert; import org.ga4gh.ctk.transport.GAWrapperException; import org.ga4gh.ctk.transport.protocols.Client; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Callable; import java.util.stream.Collectors; import ga4gh.AlleleAnnotationServiceOuterClass.SearchVariantAnnotationSetsRequest; import ga4gh.AlleleAnnotationServiceOuterClass.SearchVariantAnnotationSetsResponse; import ga4gh.AlleleAnnotationServiceOuterClass.SearchVariantAnnotationsRequest; import ga4gh.AlleleAnnotationServiceOuterClass.SearchVariantAnnotationsResponse; import ga4gh.AlleleAnnotations.VariantAnnotation; import ga4gh.AlleleAnnotations.VariantAnnotationSet; import ga4gh.BioMetadata.BioSample; import ga4gh.BioMetadataServiceOuterClass.SearchBioSamplesRequest; import ga4gh.BioMetadataServiceOuterClass.SearchBioSamplesResponse; import ga4gh.GenotypePhenotype.PhenotypeAssociationSet; import ga4gh.GenotypePhenotypeServiceOuterClass.SearchPhenotypeAssociationSetsRequest; import ga4gh.GenotypePhenotypeServiceOuterClass.SearchPhenotypeAssociationSetsResponse; import ga4gh.Metadata; import ga4gh.Metadata.Dataset; import ga4gh.MetadataServiceOuterClass.SearchDatasetsRequest; import ga4gh.MetadataServiceOuterClass.SearchDatasetsResponse; import ga4gh.ReadServiceOuterClass.SearchReadGroupSetsRequest; import ga4gh.ReadServiceOuterClass.SearchReadGroupSetsResponse; import ga4gh.ReadServiceOuterClass.SearchReadsRequest; import ga4gh.ReadServiceOuterClass.SearchReadsResponse; import ga4gh.Reads.ReadAlignment; import ga4gh.Reads.ReadGroup; import ga4gh.Reads.ReadGroupSet; import ga4gh.ReferenceServiceOuterClass.SearchReferenceSetsRequest; import ga4gh.ReferenceServiceOuterClass.SearchReferenceSetsResponse; import ga4gh.ReferenceServiceOuterClass.SearchReferencesRequest; import ga4gh.ReferenceServiceOuterClass.SearchReferencesResponse; import ga4gh.References.Reference; import ga4gh.References.ReferenceSet; import ga4gh.SequenceAnnotationServiceOuterClass.SearchFeatureSetsRequest; import ga4gh.SequenceAnnotations.FeatureSet; import ga4gh.VariantServiceOuterClass.SearchCallSetsRequest; import ga4gh.VariantServiceOuterClass.SearchCallSetsResponse; import ga4gh.VariantServiceOuterClass.SearchVariantSetsRequest; import ga4gh.VariantServiceOuterClass.SearchVariantSetsResponse; import ga4gh.VariantServiceOuterClass.SearchVariantsRequest; import ga4gh.VariantServiceOuterClass.SearchVariantsResponse; import ga4gh.Variants.CallSet; import ga4gh.Variants.Variant; import ga4gh.Variants.VariantSet; import static ga4gh.SequenceAnnotationServiceOuterClass.SearchFeatureSetsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.StrictAssertions.catchThrowable; import static org.assertj.core.api.StrictAssertions.fail; /** * Handy test-related static methods and data. * * @author Herb Jellinek */ public class Utils { /** * You can't instantiate one of these. */ private Utils() { } /** * For some reason, the class {@link java.net.HttpURLConnection} doesn't define a constant * for HTTP status 416, "Requested Range Not Satisfiable." (See * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17">HTTP Status Code Definitions</a>.) */ public static final int HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** * Certain AssertJ methods accept a variable number of args: <tt>assertThat(Collection).doesNotContain(...)</tt>, * for instance. Sometimes we want to pass null to such a method, but the IDE complains that this is "confusing." * If we supply a typed value, the complaint goes away. * This is a null suitable for use where we might want to pass a {@link Program} to a varargs method. */ public static final Metadata.Program nullProgram = null; /** * Certain AssertJ methods accept a variable number of args: <tt>assertThat(Collection).doesNotContain(...)</tt>, * for instance. Sometimes we want to pass null to such a method, but the IDE complains that this is "confusing." * If we supply a typed value, the complaint goes away. * This is a null suitable for use where we might want to pass a {@link ReadAlignment} to a varargs method. */ public static final ReadAlignment nullReadAlignment = null; /** * Make it easy to create lists of a single element, which we do a lot. * @param s the single item (typically a {@link String}) * @param <T> the class of the parameter * @return the resulting {@link List} containing the single element */ public static <T> List<T> aSingle(T s) { return Collections.singletonList(s); } /** * Is the argument character a valid hexadecimal digit? * @param c the candidate character * @return true if it's hex, false otherwise */ public static boolean isHex(char c) { return Character.isDigit(c) || (('a' <= c) && (c <= 'f')) || (('A' <= c) && (c <= 'F')); } /** * MD5 hash values are 32 characters long. */ private static final int MD5_LENGTH = 32; /** * Is the argument a legitimate-seeming MD5 value? * That is, is it the right length (32 characters), and does it consist only of hex digits? * * @param possibleMd5 the supposed MD5 hash to check * @return true if the parameter is a plausible MD5 value */ public static boolean looksLikeValidMd5(String possibleMd5) { return (possibleMd5 != null) && possibleMd5.length() == MD5_LENGTH && possibleMd5.chars().allMatch(c -> isHex((char)c)); } /** * Create and return an ID that's (virtually) guaranteed not to name a real object on a * GA4GH server. It uses {@link UUID#randomUUID()} to do it. * This is identical to {@link #randomName()} but for the name. * @return an ID that's (virtually) guaranteed not to name a real object */ public static String randomId() { return UUID.randomUUID().toString(); } /** * Create and return a name that's (virtually) guaranteed not to name a real object on a * GA4GH server. It uses {@link UUID#randomUUID()} to do it. * This is identical to {@link #randomId()} but for the name. * @return a name that's (virtually) guaranteed not to name a real object */ public static String randomName() { return UUID.randomUUID().toString(); } /** * Utility method to fetch the ID of a reference to which we can map the reads we're testing. * @param client the {@link Client} connection to the server * @return the ID of a reference * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getValidReferenceId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchReferencesRequest refsReq = SearchReferencesRequest .newBuilder() .setReferenceSetId(Utils.getReferenceSetIdByAssemblyId(client, TestData.REFERENCESET_ASSEMBLY_ID)) .setMd5Checksum(TestData.REFERENCE_BRCA1_MD5_CHECKSUM) .build(); final SearchReferencesResponse refsResp = client.references.searchReferences(refsReq); assertThat(refsResp).isNotNull(); final List<Reference> references = refsResp.getReferencesList(); assertThat(references).isNotNull().isNotEmpty(); assertThat(references).hasSize(1); return references.get(0).getId(); } /** * Utility method to fetch the ID of an arbitrary {@link ReadGroup}. * @param client the {@link Client} connection to the server * @return the ID of an arbitrary {@link ReadGroup} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getReadGroupId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchReadGroupSetsRequest readGroupSetsReq = SearchReadGroupSetsRequest .newBuilder() .setDatasetId(TestData.getDatasetId()) .build(); final SearchReadGroupSetsResponse readGroupSetsResp = client.reads.searchReadGroupSets(readGroupSetsReq); assertThat(readGroupSetsResp).isNotNull(); final List<ReadGroupSet> readGroupSets = readGroupSetsResp.getReadGroupSetsList(); assertThat(readGroupSets).isNotEmpty().isNotNull(); final ReadGroupSet readGroupSet = readGroupSets.get(0); List<ReadGroup> readGroups = readGroupSet.getReadGroupsList(); assertThat(readGroups).isNotEmpty().isNotNull(); final ReadGroup readGroup = readGroups.get(0); assertThat(readGroup).isNotNull(); return readGroup.getId(); } /** * Utility method to fetch the ID of a named {@link ReadGroup} in a named {@link ReadGroupSet}. * @param client the {@link Client} connection to the server * @param readGroupSetName the name of a {@link ReadGroupSet} * @param readGroupName the name of a {@link ReadGroup} in the given {@link ReadGroupSet} * @return the ID of the {@link ReadGroup}, or null if not found * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getReadGroupIdForName(Client client, String readGroupSetName, String readGroupName) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchReadGroupSetsRequest readGroupSetsReq = SearchReadGroupSetsRequest.newBuilder() .setDatasetId(TestData.getDatasetId()) .setName(readGroupSetName) .build(); final SearchReadGroupSetsResponse readGroupSetsResp = client.reads.searchReadGroupSets(readGroupSetsReq); final List<ReadGroupSet> readGroupSets = readGroupSetsResp.getReadGroupSetsList(); assertThat(readGroupSets).isNotEmpty().isNotNull(); final ReadGroupSet readGroupSet = readGroupSets.get(0); final List<ReadGroup> readGroups = readGroupSet.getReadGroupsList(); final Optional<ReadGroup> result = readGroups.stream().filter(readGroup -> readGroupName.equals(readGroup.getName())).findFirst(); return result.isPresent() ? result.get().getId() : null; } /** * Utility method to fetch all {@link ReadGroupSet}s. * @param client the {@link Client} connection to the server * @return all {@link ReadGroupSet}s * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<ReadGroupSet> getAllReadGroupSets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<ReadGroupSet> result = new LinkedList<>(); String pageToken = ""; do { final SearchReadGroupSetsRequest readGroupSetsReq = SearchReadGroupSetsRequest .newBuilder() .setPageSize(100) .setPageToken(pageToken) .setDatasetId(TestData.getDatasetId()) .build(); final SearchReadGroupSetsResponse readGroupSetsResp = client.reads.searchReadGroupSets(readGroupSetsReq); pageToken = readGroupSetsResp.getNextPageToken(); assertThat(readGroupSetsResp).isNotNull(); final List<ReadGroupSet> readGroupSets = readGroupSetsResp.getReadGroupSetsList(); assertThat(readGroupSets).isNotEmpty().isNotNull(); result.addAll(readGroupSets); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Utility method to fetch all {@link ReadGroup}s given a {@link ReadGroupSet} name. * @param client the {@link Client} connection to the server * @param name the name of a {@link ReadGroupSet} * @return all {@link ReadGroup}s in the {@link ReadGroupSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<ReadGroup> getReadGroupsForName(Client client, String name) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<ReadGroup> result = new LinkedList<>(); String pageToken = ""; do { final SearchReadGroupSetsRequest readGroupSetsReq = SearchReadGroupSetsRequest .newBuilder() .setName(name) .setDatasetId(TestData.getDatasetId()) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchReadGroupSetsResponse readGroupSetsResp = client.reads.searchReadGroupSets(readGroupSetsReq); pageToken = readGroupSetsResp.getNextPageToken(); final List<ReadGroupSet> readGroupSets = readGroupSetsResp.getReadGroupSetsList(); assertThat(readGroupSets).isNotEmpty().isNotNull(); result.addAll(readGroupSets.stream() .flatMap(rgs -> rgs.getReadGroupsList().stream()) .collect(Collectors.toList())); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Utility method to fetch a ReferenceSetId given a {@link ReferenceSet#getAssemblyId()}. * @param client the connection to the server * @param assemblyId the {@link ReferenceSet#getAssemblyId()} of the {@link ReferenceSet} * @return The ReferenceSet ID * * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getReferenceSetIdByAssemblyId(Client client, String assemblyId) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchReferenceSetsRequest req = SearchReferenceSetsRequest.newBuilder() .setAssemblyId(assemblyId) .build(); final SearchReferenceSetsResponse resp = client.references.searchReferenceSets(req); final List<ReferenceSet> refSets = resp.getReferenceSetsList(); assertThat(refSets).isNotNull(); assertThat(refSets).hasSize(1); final ReferenceSet refSet = refSets.get(0); return refSet.getId(); } /** * Utility method to fetch the ID of an arbitrary {@link VariantSet}. * @param client the connection to the server * @return the ID of a {@link VariantSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getVariantSetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchVariantSetsRequest req = SearchVariantSetsRequest.newBuilder() .setDatasetId(TestData.getDatasetId()) .build(); final SearchVariantSetsResponse resp = client.variants.searchVariantSets(req); final List<VariantSet> variantSets = resp.getVariantSetsList(); assertThat(variantSets).isNotEmpty(); return variantSets.get(0).getId(); } /** * Convenience function for getting a variant set by name. When no set is found * matching the name returns the first variant set found. * @param client * @param name * @return * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static VariantSet getVariantSetByName(Client client, String name) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<VariantSet> variantSets = Utils.getAllVariantSets(client); for (VariantSet v: variantSets) { if (v.getName() == name) { return v; } } return variantSets.get(0); } /** * Utility method to fetch the ID of an arbitrary {@link PhenotypeAssociationSet}. * @param client the connection to the server * @return the ID of a {@link PhenotypeAssociationSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server **/ public static String getPhenotypeAssociationSetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchPhenotypeAssociationSetsRequest req = SearchPhenotypeAssociationSetsRequest.newBuilder() .setDatasetId(getDatasetId(client)) .build(); final SearchPhenotypeAssociationSetsResponse resp = client.genotypePhenotype.searchPhenotypeAssociationSets(req); final List<PhenotypeAssociationSet> phenotypeAssociationSets = resp.getPhenotypeAssociationSetsList(); assertThat(phenotypeAssociationSets).isNotEmpty(); return phenotypeAssociationSets.get(0).getId(); } /** * Utility method to fetch the ID of an arbitrary {@link PhenotypeAssociationSet}. * @param client the connection to the server * @return the ID of a {@link PhenotypeAssociationSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server **/ public static String getDatasetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchDatasetsRequest req = SearchDatasetsRequest.newBuilder() .build(); final SearchDatasetsResponse resp = client.metadata.searchDatasets(req); assertThat(resp.getDatasetsList()).isNotEmpty(); return resp.getDatasets(0).getId() ; } /** * Search for and return all {@link Variant} objects in the {@link VariantSet} with ID * <tt>variantSetId</tt>, from <tt>start</tt> to <tt>end</tt>. * @param client the connection to the server * @param variantSetId the ID of the {@link VariantSet} * @param start the start of the range to search * @param end the end of the range to search * @return the {@link List} of results * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<Variant> getAllVariantsInRange(Client client, String variantSetId, long start, long end) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all variants in the range final List<Variant> result = new LinkedList<>(); String pageToken = ""; do { final SearchVariantsRequest vReq = SearchVariantsRequest.newBuilder() .setVariantSetId(variantSetId) .setReferenceName(TestData.REFERENCE_NAME) .setStart(start).setEnd(end) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchVariantsResponse vResp = client.variants.searchVariants(vReq); pageToken = vResp.getNextPageToken(); result.addAll(vResp.getVariantsList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Search for and return all {@link VariantSet}s. * * @param client the connection to the server * @return the {@link List} of results * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<VariantSet> getAllVariantSets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<VariantSet> result = new LinkedList<>(); String pageToken = ""; do { final SearchVariantSetsRequest req = SearchVariantSetsRequest.newBuilder() .setDatasetId(TestData.getDatasetId()) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchVariantSetsResponse resp = client.variants.searchVariantSets(req); pageToken = resp.getNextPageToken(); result.addAll(resp.getVariantSetsList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Search for and return all {@link CallSet}s in the {@link VariantSet} named by <tt>variantSetId</tt>. * * @param client the connection to the server * @param variantSetId the ID of the {@link VariantSet} * @return the {@link List} of results * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<CallSet> getAllCallSets(Client client, String variantSetId) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<CallSet> result = new LinkedList<>(); String pageToken = ""; do { final SearchCallSetsRequest callSetsSearchRequest = SearchCallSetsRequest.newBuilder() .setPageSize(100) .setPageToken(pageToken) .setVariantSetId(variantSetId) .build(); final SearchCallSetsResponse csResp = client.variants.searchCallSets(callSetsSearchRequest); pageToken = csResp.getNextPageToken(); result.addAll(csResp.getCallSetsList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Retrieve all {@link ReferenceSet}s. * @param client the connection to the server * @return a {@link List} of all {@link Reference}s in the first {@link ReferenceSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<ReferenceSet> getAllReferenceSets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<ReferenceSet> result = new LinkedList<>(); String pageToken = ""; do { final SearchReferenceSetsRequest refSetsReq = SearchReferenceSetsRequest.newBuilder() .setPageSize(100) .setPageToken(pageToken) .build(); final SearchReferenceSetsResponse refSetsResp = client.references.searchReferenceSets(refSetsReq); pageToken = refSetsResp.getNextPageToken(); result.addAll(refSetsResp.getReferenceSetsList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Retrieve all references in the {@link ReferenceSet} named by the reference set ID. * * @param client the connection to the server * @param refSetId the ID of the {@link ReferenceSet} we're using * @return a {@link List} of all {@link Reference}s in the first {@link ReferenceSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<Reference> getAllReferences(Client client,String refSetId) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<Reference> result = new LinkedList<>(); String pageToken = ""; do { final SearchReferencesRequest refsReq = SearchReferencesRequest.newBuilder() .setReferenceSetId(refSetId) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchReferencesResponse refsResp = client.references.searchReferences(refsReq); pageToken = refsResp.getNextPageToken(); result.addAll(refsResp.getReferencesList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Given a reference ID, return all {@link ReadAlignment}s * @param client the connection to the server * @param referenceId the ID of the {@link Reference} we're using * @param readGroupId the ID of the {@link ReadGroup} we're using * @return all the {@link ReadAlignment} objects that match * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<ReadAlignment> getAllReads(Client client, String referenceId, String readGroupId) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<ReadAlignment> result = new LinkedList<>(); String pageToken = ""; do { final SearchReadsRequest req = SearchReadsRequest.newBuilder() .setReferenceId(referenceId) .addAllReadGroupIds(aSingle(readGroupId)) .setPageToken(pageToken) .setPageSize(100) .build(); final SearchReadsResponse resp = client.reads.searchReads(req); result.addAll(resp.getAlignmentsList()); pageToken = resp.getNextPageToken(); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Retrieve all {@link Dataset}s we're allowed to access. * @param client the connection to the server * @return all the {@link Dataset}s * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<Dataset> getAllDatasets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<Dataset> result = new LinkedList<>(); String pageToken = ""; do { final SearchDatasetsRequest req = SearchDatasetsRequest.newBuilder() .setPageSize(100) .setPageToken(pageToken) .build(); final SearchDatasetsResponse resp = client.metadata.searchDatasets(req); pageToken = resp.getNextPageToken(); result.addAll(resp.getDatasetsList()); } while (pageToken != null && !pageToken.equals("")); return result; } /** * Convenience method to catch a {@link GAWrapperException} and cast the return value to that type. * <b>Only use this when you're expecting the enclosed code to throw that exception.</b> * If the enclosed code doesn't throw the expected {@link GAWrapperException}, this method calls * {@link org.assertj.core.api.StrictAssertions#fail(String)} to cause the enclosing test to fail * and log the stack trace. * @param thisShouldThrow the {@link Callable} we're calling, which should throw {@link GAWrapperException} * @return the {@link Throwable} thrown in the execution of the {@link Callable} */ public static GAWrapperException catchGAWrapperException(ThrowableAssert.ThrowingCallable thisShouldThrow) { final GAWrapperException maybeAnException = (GAWrapperException)catchThrowable(thisShouldThrow); if (maybeAnException == null) { // we were expecting an exception and didn't get one. log it as a failure. fail("Expected but did not receive GAWrapperException"); } return maybeAnException; } /** * Search for and return all {@link VariantAnnotation} objects in the {@link VariantAnnotationSet} with ID <tt>variantAnnotationSetId</tt>, from * <tt>start</tt> to <tt>end</tt>. * * @param client the connection to the server * @param variantAnnotationSetId the ID of the {@link VariantAnnotationSet} * @param start the start of the range to search * @param end the end of the range to search * @return the {@link List} of results * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<VariantAnnotation> getAllVariantAnnotationsInRange(Client client, String variantAnnotationSetId, long start, long end) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all variantAnnotations in the range final List<VariantAnnotation> result = new LinkedList<>(); String pageToken = ""; do { final SearchVariantAnnotationsRequest vReq = SearchVariantAnnotationsRequest.newBuilder() .setVariantAnnotationSetId(variantAnnotationSetId) .setReferenceName(TestData.VARIANT_ANNOTATION_REFERENCE_NAME) .setStart(start).setEnd(end) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchVariantAnnotationsResponse vResp = client.variantAnnotations.searchVariantAnnotations(vReq); pageToken = vResp.getNextPageToken(); result.addAll(vResp.getVariantAnnotationsList()); } while (!pageToken.equals("")); return result; } /** * Utility method to fetch alist of {@link VariantAnnotationSet} given the ID of a {@link Dataset}. * @param client the connection to the server * @return a list of {@link VariantAnnotationSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<VariantAnnotationSet> getAllVariantAnnotationSets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // Get all compliance variant sets. final List<VariantSet> variantSetsCompliance = getAllVariantSets(client); //Check some sets are available. assertThat(variantSetsCompliance).isNotEmpty(); // Build a list of VariantAnnotationSets. final List<VariantAnnotationSet> result = new LinkedList<>(); // there may be multiple variantSets to check for (final VariantSet variantSet : variantSetsCompliance) { final SearchVariantAnnotationSetsRequest req = SearchVariantAnnotationSetsRequest.newBuilder() .setVariantSetId(variantSet.getId()) .build(); final SearchVariantAnnotationSetsResponse resp = client.variantAnnotations.searchVariantAnnotationSets(req); if (resp.getVariantAnnotationSetsList() != null) { result.addAll(resp.getVariantAnnotationSetsList()); } } return result; } /** * Utility method to fetch the Id of a {@link VariantAnnotationSet} for the compliance dataset. * @param client the connection to the server * @return the ID of a {@link VariantAnnotationSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getVariantAnnotationSetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all compliance variant annotation sets final List<VariantAnnotationSet> variantAnnotationSets = getAllVariantAnnotationSets(client); return variantAnnotationSets.get(0).getId(); } /** * Given a name return the variant annotation set corresponding to that name. When that name * is not found returns the first annotation set found. * @param client the connection to the server * @param name the string name of the annotation set * @return a {@link VariantAnnotationSet} with the requested name * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static VariantAnnotationSet getVariantAnnotationSetByName(Client client, String name) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all compliance variant annotation sets final List<VariantAnnotationSet> variantAnnotationSets = getAllVariantAnnotationSets(client); for (VariantAnnotationSet vas : variantAnnotationSets) { if (vas.getName().equals(name)) { return vas; } } return variantAnnotationSets.get(0); } /** * Search for and return all {@link FeatureSet}s. * * @param client the connection to the server * @return the {@link List} of results * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static List<FeatureSet> getAllFeatureSets(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final List<FeatureSet> result = new LinkedList<>(); String pageToken = ""; do { final SearchFeatureSetsRequest req = SearchFeatureSetsRequest.newBuilder() .setDatasetId(TestData.getDatasetId()) .setPageSize(100) .setPageToken(pageToken) .build(); final SearchFeatureSetsResponse resp = client.sequenceAnnotations.searchFeatureSets(req); pageToken = resp.getNextPageToken(); result.addAll(resp.getFeatureSetsList()); } while (!pageToken.equals("")); return result; } /** * Utility method to fetch the Id of a {@link FeatureSet} for the compliance dataset. * @param client the connection to the server * @return the ID of a {@link FeatureSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getFeatureSetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all compliance feature sets final List<FeatureSet> featureSets = getAllFeatureSets(client); return featureSets.get(0).getId(); } /** * Utility method to fetch the Id of a {@link FeatureSet} for the compliance dataset. * @param client the connection to the server * @return the ID of a {@link FeatureSet} * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static String getFeatureG2PSetId(Client client) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all compliance feature sets final List<FeatureSet> featureSets = getAllFeatureSets(client); return featureSets.get(1).getId(); } /** * Given a name, return the feature set corresponding to that name. When that name * is not found returns the first feature set found. * @param client the connection to the server * @param name the string name of the annotation set * @return a {@link FeatureSet} with the requested name * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static FeatureSet getFeatureSetByName(Client client, String name) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { // get all compliance feature sets final List<FeatureSet> featureSets = getAllFeatureSets(client); for (FeatureSet fs : featureSets) { if (fs.getName().equals(name)) { return fs; } } return featureSets.get(0); } /** * Sugar for getting the first BioSample result that matches the name search request. * @param client * @param name The name of the BioSample * @return BioSample * @throws GAWrapperException if the server finds the request invalid in some way * @throws UnirestException if there's a problem speaking HTTP to the server * @throws InvalidProtocolBufferException if there's a problem processing the JSON response from the server */ public static BioSample getBioSampleByName(Client client, String name) throws InvalidProtocolBufferException, UnirestException, GAWrapperException { final SearchBioSamplesRequest req = SearchBioSamplesRequest.newBuilder() .setDatasetId(TestData.getDatasetId()) .setName(name) .build(); final SearchBioSamplesResponse resp = client.bioMetadata.searchBiosamples(req); return (BioSample)resp.getBiosamplesList().get(0); } }
apache-2.0
xroca/planFormacionJava
spring/dao/JPA/SpringJpaWeb/src/main/java/com/curso/java/configuracion/Configuracion.java
1328
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.curso.java.configuracion; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.context.annotation.Bean; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; /** * * @author Administrador */ @Component public class Configuracion { @Bean(name = "transactionManager", autowire = Autowire.BY_TYPE) JpaTransactionManager getJpaTx() { return new JpaTransactionManager(); } @Bean LocalEntityManagerFactoryBean getEmf() { LocalEntityManagerFactoryBean bean = new LocalEntityManagerFactoryBean(); bean.setPersistenceUnitName("SpringJpaWebPU"); return bean; } @Bean PersistenceAnnotationBeanPostProcessor getPa() { return new PersistenceAnnotationBeanPostProcessor(); } @Bean PersistenceExceptionTranslationPostProcessor getPe() { return new PersistenceExceptionTranslationPostProcessor(); } }
apache-2.0
egopulse/querydsl-rethinkdb
src/test/java/com/egopulse/querydsl/rethinkdb/domain/Fish.java
1147
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * 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.egopulse.querydsl.rethinkdb.domain; import com.querydsl.core.annotations.QueryEntity; // TODO: verify if custom collection name is necessary //@Entity("food") @QueryEntity public class Fish extends Food { private final String breed; public Fish(final String name) { super(name); this.breed = "unknown"; } public Fish(final String name, final String breed) { super(name); this.breed = breed; } public String getBreed() { return breed; } }
apache-2.0
Myasuka/systemml
src/main/java/org/apache/sysml/lops/PartialAggregate.java
11530
/* * 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.sysml.lops; import org.apache.sysml.hops.HopsException; import org.apache.sysml.hops.AggBinaryOp.SparkAggType; import org.apache.sysml.lops.LopProperties.ExecLocation; import org.apache.sysml.lops.LopProperties.ExecType; import org.apache.sysml.lops.compile.JobType; import org.apache.sysml.parser.Expression.*; /** * Lop to perform a partial aggregation. It was introduced to do some initial * aggregation operations on blocks in the mapper/reducer. */ public class PartialAggregate extends Lop { public enum DirectionTypes { RowCol, Row, Col }; public enum CorrectionLocationType { NONE, LASTROW, LASTCOLUMN, LASTTWOROWS, LASTTWOCOLUMNS, INVALID }; private Aggregate.OperationTypes operation; private DirectionTypes direction; private boolean _dropCorr = false; //optional attribute for CP num threads private int _numThreads = -1; //optional attribute for spark exec type private SparkAggType _aggtype = SparkAggType.MULTI_BLOCK; public PartialAggregate( Lop input, Aggregate.OperationTypes op, PartialAggregate.DirectionTypes direct, DataType dt, ValueType vt) throws LopsException { super(Lop.Type.PartialAggregate, dt, vt); init(input, op, direct, dt, vt, ExecType.MR); } public PartialAggregate( Lop input, Aggregate.OperationTypes op, PartialAggregate.DirectionTypes direct, DataType dt, ValueType vt, ExecType et) throws LopsException { super(Lop.Type.PartialAggregate, dt, vt); init(input, op, direct, dt, vt, et); } public PartialAggregate( Lop input, Aggregate.OperationTypes op, PartialAggregate.DirectionTypes direct, DataType dt, ValueType vt, ExecType et, int k) throws LopsException { super(Lop.Type.PartialAggregate, dt, vt); init(input, op, direct, dt, vt, et); _numThreads = k; } public PartialAggregate( Lop input, Aggregate.OperationTypes op, PartialAggregate.DirectionTypes direct, DataType dt, ValueType vt, SparkAggType aggtype, ExecType et) throws LopsException { super(Lop.Type.PartialAggregate, dt, vt); init(input, op, direct, dt, vt, et); _aggtype = aggtype; } /** * Constructor to setup a partial aggregate operation. * * @param input * @param op * @return * @throws LopsException */ private void init(Lop input, Aggregate.OperationTypes op, PartialAggregate.DirectionTypes direct, DataType dt, ValueType vt, ExecType et) { operation = op; direction = direct; this.addInput(input); input.addOutput(this); boolean breaksAlignment = true; boolean aligner = false; boolean definesMRJob = false; if ( et == ExecType.MR ) { /* * This lop CAN NOT be executed in PARTITION, SORT, STANDALONE MMCJ: * only in mapper. */ lps.addCompatibility(JobType.GMR); lps.addCompatibility(JobType.DATAGEN); lps.addCompatibility(JobType.REBLOCK); lps.addCompatibility(JobType.MMCJ); lps.addCompatibility(JobType.MMRJ); this.lps.setProperties(inputs, et, ExecLocation.Map, breaksAlignment, aligner, definesMRJob); } else //CP | SPARK { lps.addCompatibility(JobType.INVALID); this.lps.setProperties(inputs, et, ExecLocation.ControlProgram, breaksAlignment, aligner, definesMRJob); } } public void setDropCorrection() { _dropCorr = true; } public static CorrectionLocationType decodeCorrectionLocation(String loc) { return CorrectionLocationType.valueOf(loc); } /** * This method computes the location of "correction" terms in the output * produced by PartialAgg instruction. * * When computing the stable sum, "correction" refers to the compensation as * defined by the original Kahan algorithm. When computing the stable mean, * "correction" refers to two extra values (the running mean, count) * produced by each Mapper i.e., by each PartialAgg instruction. * * This method is invoked during hop-to-lop translation, while creating the * corresponding Aggregate lop * * Computed information is encoded in the PartialAgg instruction so that the * appropriate aggregate operator is used at runtime (see: * dml.runtime.matrix.operator.AggregateOperator.java and dml.runtime.matrix) */ public CorrectionLocationType getCorrectionLocation() throws LopsException { return getCorrectionLocation(operation, direction); } public static CorrectionLocationType getCorrectionLocation(Aggregate.OperationTypes operation, DirectionTypes direction) throws LopsException { CorrectionLocationType loc; switch (operation) { case KahanSum: case KahanSumSq: case KahanTrace: switch (direction) { case Col: // colSums: corrections will be present as a last row in the // result loc = CorrectionLocationType.LASTROW; break; case Row: case RowCol: // rowSums, sum: corrections will be present as a last column in // the result loc = CorrectionLocationType.LASTCOLUMN; break; default: throw new LopsException("PartialAggregate.getCorrectionLocation() - " + "Unknown aggregate direction: " + direction); } break; case Mean: // Computation of stable mean requires each mapper to output both // the running mean as well as the count switch (direction) { case Col: // colMeans: last row is correction 2nd last is count loc = CorrectionLocationType.LASTTWOROWS; break; case Row: case RowCol: // rowMeans, mean: last column is correction 2nd last is count loc = CorrectionLocationType.LASTTWOCOLUMNS; break; default: throw new LopsException("PartialAggregate.getCorrectionLocation() - " + "Unknown aggregate direction: " + direction); } break; case MaxIndex: case MinIndex: loc = CorrectionLocationType.LASTCOLUMN; break; default: loc = CorrectionLocationType.NONE; } return loc; } public void setDimensionsBasedOnDirection(long dim1, long dim2, long rowsPerBlock, long colsPerBlock) throws LopsException { setDimensionsBasedOnDirection(this, dim1, dim2, rowsPerBlock, colsPerBlock, direction); } public static void setDimensionsBasedOnDirection(Lop lop, long dim1, long dim2, long rowsPerBlock, long colsPerBlock, DirectionTypes dir) throws LopsException { try { if (dir == DirectionTypes.Row) lop.outParams.setDimensions(dim1, 1, rowsPerBlock, colsPerBlock, -1); else if (dir == DirectionTypes.Col) lop.outParams.setDimensions(1, dim2, rowsPerBlock, colsPerBlock, -1); else if (dir == DirectionTypes.RowCol) lop.outParams.setDimensions(1, 1, rowsPerBlock, colsPerBlock, -1); else throw new LopsException("In PartialAggregate Lop, Unknown aggregate direction " + dir); } catch (HopsException e) { throw new LopsException("In PartialAggregate Lop, error setting dimensions based on direction", e); } } public String toString() { return "Partial Aggregate " + operation; } private String getOpcode() { return getOpcode(operation, direction); } /** * Instruction generation for for CP and Spark */ @Override public String getInstructions(String input1, String output) throws LopsException { StringBuilder sb = new StringBuilder(); sb.append( getExecType() ); sb.append( OPERAND_DELIMITOR ); sb.append( getOpcode() ); sb.append( OPERAND_DELIMITOR ); sb.append( getInputs().get(0).prepInputOperand(input1) ); sb.append( OPERAND_DELIMITOR ); sb.append( this.prepOutputOperand(output) ); //in case of spark, we also compile the optional aggregate flag into the instruction. if( getExecType() == ExecType.SPARK ) { sb.append( OPERAND_DELIMITOR ); sb.append( _aggtype ); } //in case of cp, we also compile the number of threads into the instruction if( getExecType() == ExecType.CP ){ sb.append( OPERAND_DELIMITOR ); sb.append( _numThreads ); } return sb.toString(); } @Override public String getInstructions(int input_index, int output_index) throws LopsException { StringBuilder sb = new StringBuilder(); sb.append( getExecType() ); sb.append( Lop.OPERAND_DELIMITOR ); sb.append( getOpcode() ); sb.append( OPERAND_DELIMITOR ); sb.append( getInputs().get(0).prepInputOperand(input_index) ); sb.append( OPERAND_DELIMITOR ); sb.append( this.prepOutputOperand(output_index) ); sb.append( OPERAND_DELIMITOR ); sb.append( _dropCorr ); return sb.toString(); } /** * * @param op * @param dir * @return */ public static String getOpcode(Aggregate.OperationTypes op, DirectionTypes dir) { switch( op ) { case Sum: { if( dir == DirectionTypes.RowCol ) return "ua+"; else if( dir == DirectionTypes.Row ) return "uar+"; else if( dir == DirectionTypes.Col ) return "uac+"; break; } case Mean: { if( dir == DirectionTypes.RowCol ) return "uamean"; else if( dir == DirectionTypes.Row ) return "uarmean"; else if( dir == DirectionTypes.Col ) return "uacmean"; break; } case KahanSum: { // instructions that use kahanSum are similar to ua+,uar+,uac+ // except that they also produce correction values along with partial // sums. if( dir == DirectionTypes.RowCol ) return "uak+"; else if( dir == DirectionTypes.Row ) return "uark+"; else if( dir == DirectionTypes.Col ) return "uack+"; break; } case KahanSumSq: { if( dir == DirectionTypes.RowCol ) return "uasqk+"; else if( dir == DirectionTypes.Row ) return "uarsqk+"; else if( dir == DirectionTypes.Col ) return "uacsqk+"; break; } case Product: { if( dir == DirectionTypes.RowCol ) return "ua*"; break; } case Max: { if( dir == DirectionTypes.RowCol ) return "uamax"; else if( dir == DirectionTypes.Row ) return "uarmax"; else if( dir == DirectionTypes.Col ) return "uacmax"; break; } case Min: { if( dir == DirectionTypes.RowCol ) return "uamin"; else if( dir == DirectionTypes.Row ) return "uarmin"; else if( dir == DirectionTypes.Col ) return "uacmin"; break; } case MaxIndex:{ if( dir == DirectionTypes.Row ) return "uarimax"; break; } case MinIndex: { if( dir == DirectionTypes.Row ) return "uarimin"; break; } case Trace: { if( dir == DirectionTypes.RowCol) return "uatrace"; break; } case KahanTrace: { if( dir == DirectionTypes.RowCol ) return "uaktrace"; break; } } //should never come here for normal compilation throw new UnsupportedOperationException("Instruction is not defined for PartialAggregate operation " + op); } }
apache-2.0
hhu94/Synapse-Repository-Services
services/repository-managers/src/main/java/org/sagebionetworks/repo/manager/AuthorizationManagerUtil.java
1486
package org.sagebionetworks.repo.manager; import org.sagebionetworks.repo.model.UnauthorizedException; import org.sagebionetworks.repo.model.file.FileHandleAssociateType; public class AuthorizationManagerUtil { private static final String FILE_HANDLE_ID_IS_NOT_ASSOCIATED_TEMPLATE = "FileHandleId: %1s is not associated with objectId: %2s of type: %3s"; public static final AuthorizationStatus AUTHORIZED = new AuthorizationStatus(true, ""); // convenience for testing. In production we don't leave the reason field blank. public static final AuthorizationStatus ACCESS_DENIED = new AuthorizationStatus(false, ""); public static void checkAuthorizationAndThrowException(AuthorizationStatus auth) throws UnauthorizedException { if (!auth.getAuthorized()) throw new UnauthorizedException(auth.getReason()); } public static AuthorizationStatus accessDenied(String reason) { return new AuthorizationStatus(false, reason); } /** * Create an access denied status for a file handle not associated with the requested object. * @param fileHandleId * @param associatedObjectId * @param associationType * @return */ public static AuthorizationStatus accessDeniedFileNotAssociatedWithObject(String fileHandleId, String associatedObjectId, FileHandleAssociateType associateType){ return AuthorizationManagerUtil.accessDenied(String .format(FILE_HANDLE_ID_IS_NOT_ASSOCIATED_TEMPLATE, fileHandleId, associatedObjectId, associateType)); } }
apache-2.0
guhanjie/wine
src/test/java/top/guhanjie/wine/mapper/TestRushLotteryMapper.java
2835
package top.guhanjie.wine.mapper; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import top.guhanjie.wine.model.RushItem; import top.guhanjie.wine.model.RushLottery; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = {"classpath:/context/db-mysql.xml", "classpath:/test-application-context.xml"}) public class TestRushLotteryMapper { private Logger logger = LoggerFactory.getLogger(TestRushLotteryMapper.class); @Autowired private RushLotteryMapper mapper; private String tableName; @Before public void setup() throws Exception { tableName = "rush_lottery"; } @Test public void testCRUD() { //Create logger.debug("Create one record to table[{}]...", tableName); RushLottery model = new RushLottery(); model.setUserId(1); model.setLotteryCode("888"); model.setRushItemId(3); long insertCount = mapper.insertSelective(model); assertEquals(insertCount, 1L); //Retrieve logger.debug("Select one record from table[{}]...", tableName); model = mapper.selectByPrimaryKey(model.getId()); logger.debug(JSON.toJSONString(model, true)); //Update logger.debug("Update one record in table[{}]...", tableName); model.setLotteryCode("666"); long updateCount = mapper.updateByPrimaryKeySelective(model); logger.debug("Update [{}] record(s) in table[{}]...", updateCount, tableName); model = mapper.selectByPrimaryKey(model.getId()); logger.debug(JSON.toJSONString(model, true)); //Delete logger.debug("Delete one record from table[{}]...", tableName); long deleteCount = mapper.deleteByPrimaryKey(model.getId()); assertEquals(deleteCount, 1L); } @Test public void testSelectByUserItem() { List<RushLottery> items = mapper.selectByOrderItem(1, 1); for(RushLottery item : items) { logger.debug(JSON.toJSONString(item)); } } @Test public void testSelectByCodeItem() { // exist case: RushLottery item1 = mapper.selectByItemCode(1, "505"); System.out.println(JSON.toJSONString(item1, true)); // not exist case: RushLottery item2 = mapper.selectByItemCode(1, "222"); System.out.println(JSON.toJSONString(item2, true)); } @Test public void testcountByItem() { int cnt = mapper.countByItem(5); System.out.println(cnt); } @Test public void testcountUsersByItem() { int cnt = mapper.countUsersByItem(1); System.out.println(cnt); } }
apache-2.0
xiaomin0322/hadoop_demo
spark/src/main/java/zzm/spark/streaming/JavaCustomReceiver.java
2008
package zzm.spark.streaming; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.ConnectException; import java.net.Socket; import org.apache.spark.storage.StorageLevel; import org.apache.spark.streaming.receiver.Receiver; public class JavaCustomReceiver extends Receiver<String> { String host = null; int port = -1; public JavaCustomReceiver(String host_ , int port_) { super(StorageLevel.MEMORY_AND_DISK_2()); host = host_; port = port_; } public void onStart() { // Start the thread that receives data over a connection new Thread() { @Override public void run() { receive(); } }.start(); } public void onStop() { // There is nothing much to do as the thread calling receive() // is designed to stop by itself if isStopped() returns false } /** Create a socket connection and receive data until receiver is stopped */ private void receive() { Socket socket = null; String userInput = null; try { // connect to the server socket = new Socket(host, port); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Until stopped or connection broken continue reading while (!isStopped() && (userInput = reader.readLine()) != null) { System.out.println("Received data '" + userInput + "'"); store(userInput); } reader.close(); socket.close(); // Restart in an attempt to connect again when server is active again restart("Trying to connect again"); } catch(ConnectException ce) { // restart if could not connect to server restart("Could not connect", ce); } catch(Throwable t) { // restart if there is any other error restart("Error receiving data", t); } } }
apache-2.0
aosp-mirror/platform_frameworks_support
room/common/src/main/java/androidx/room/Index.java
2997
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares an index on an Entity. * see: <a href="https://sqlite.org/lang_createindex.html">SQLite Index Documentation</a> * <p> * Adding an index usually speeds up your select queries but will slow down other queries like * insert or update. You should be careful when adding indices to ensure that this additional cost * is worth the gain. * <p> * There are 2 ways to define an index in an {@link Entity}. You can either set * {@link ColumnInfo#index()} property to index individual fields or define composite indices via * {@link Entity#indices()}. * <p> * If an indexed field is embedded into another Entity via {@link Embedded}, it is <b>NOT</b> * added as an index to the containing {@link Entity}. If you want to keep it indexed, you must * re-declare it in the containing {@link Entity}. * <p> * Similarly, if an {@link Entity} extends another class, indices from the super classes are * <b>NOT</b> inherited. You must re-declare them in the child {@link Entity} or set * {@link Entity#inheritSuperIndices()} to {@code true}. * */ @Target({}) @Retention(RetentionPolicy.CLASS) public @interface Index { /** * List of column names in the Index. * <p> * The order of columns is important as it defines when SQLite can use a particular index. * See <a href="https://www.sqlite.org/optoverview.html">SQLite documentation</a> for details on * index usage in the query optimizer. * * @return The list of column names in the Index. */ String[] value(); /** * Name of the index. If not set, Room will set it to the list of columns joined by '_' and * prefixed by "index_${tableName}". So if you have a table with name "Foo" and with an index * of {"bar", "baz"}, generated index name will be "index_Foo_bar_baz". If you need to specify * the index in a query, you should never rely on this name, instead, specify a name for your * index. * * @return The name of the index. */ String name() default ""; /** * If set to true, this will be a unique index and any duplicates will be rejected. * * @return True if index is unique. False by default. */ boolean unique() default false; }
apache-2.0
pac4j/pac4j
pac4j-cas/src/main/java/org/pac4j/cas/client/direct/DirectCasProxyClient.java
4030
package org.pac4j.cas.client.direct; import org.pac4j.cas.authorization.DefaultCasAuthorizationGenerator; import org.pac4j.cas.client.CasProxyReceptor; import org.pac4j.cas.config.CasConfiguration; import org.pac4j.cas.config.CasProtocol; import org.pac4j.cas.credentials.authenticator.CasAuthenticator; import org.pac4j.core.client.DirectClient; import org.pac4j.core.credentials.extractor.ParameterExtractor; import org.pac4j.core.http.callback.CallbackUrlResolver; import org.pac4j.core.http.callback.NoParameterCallbackUrlResolver; import org.pac4j.core.http.url.DefaultUrlResolver; import org.pac4j.core.http.url.UrlResolver; import static org.pac4j.core.util.CommonHelper.*; /** * <p>This class is the direct client to authenticate users based on CAS proxy tickets.</p> * * <p>The configuration can be defined via the {@link #configuration} object.</p> * * <p>As no session is meant to be created, this client does not handle CAS logout requests.</p> * * <p>For proxy support, a {@link CasProxyReceptor} must be defined in the configuration (the corresponding "callback filter" must be * enabled) and set to the CAS configuration of this client. In that case, a {@link org.pac4j.cas.profile.CasProxyProfile} will be return * (instead of a {@link org.pac4j.cas.profile.CasProfile}) to be able to request proxy tickets.</p> * * @author Jerome Leleu * @since 1.9.2 */ public class DirectCasProxyClient extends DirectClient { private CasConfiguration configuration; private UrlResolver urlResolver = new DefaultUrlResolver(); private CallbackUrlResolver callbackUrlResolver = new NoParameterCallbackUrlResolver(); private String serviceUrl; public DirectCasProxyClient() { } public DirectCasProxyClient(final CasConfiguration casConfiguration, final String serviceUrl) { this.configuration = casConfiguration; this.serviceUrl = serviceUrl; } @Override protected void internalInit(final boolean forceReinit) { assertNotBlank("serviceUrl", this.serviceUrl); assertNotNull("configuration", this.configuration); // must be a CAS proxy protocol final var protocol = configuration.getProtocol(); assertTrue(protocol == CasProtocol.CAS20_PROXY || protocol == CasProtocol.CAS30_PROXY, "The DirectCasProxyClient must be configured with a CAS proxy protocol (CAS20_PROXY or CAS30_PROXY)"); defaultCredentialsExtractor(new ParameterExtractor(CasConfiguration.TICKET_PARAMETER, true, false)); defaultAuthenticator(new CasAuthenticator(configuration, getName(), urlResolver, callbackUrlResolver, this.serviceUrl)); addAuthorizationGenerator(new DefaultCasAuthorizationGenerator()); } public CasConfiguration getConfiguration() { return configuration; } public void setConfiguration(final CasConfiguration configuration) { this.configuration = configuration; } public String getServiceUrl() { return serviceUrl; } public void setServiceUrl(final String serviceUrl) { this.serviceUrl = serviceUrl; } public UrlResolver getUrlResolver() { return urlResolver; } public void setUrlResolver(final UrlResolver urlResolver) { this.urlResolver = urlResolver; } public CallbackUrlResolver getCallbackUrlResolver() { return callbackUrlResolver; } public void setCallbackUrlResolver(final CallbackUrlResolver callbackUrlResolver) { this.callbackUrlResolver = callbackUrlResolver; } @Override public String toString() { return toNiceString(this.getClass(), "name", getName(), "credentialsExtractor", getCredentialsExtractor(), "authenticator", getAuthenticator(), "profileCreator", getProfileCreator(), "authorizationGenerators", getAuthorizationGenerators(), "configuration", this.configuration, "callbackUrlResolver", callbackUrlResolver, "serviceUrl", serviceUrl, "urlResolver", this.urlResolver); } }
apache-2.0
health-and-care-developer-network/health-and-care-developer-network
source/common/common-http-server-sun/uk/nhs/hdn/common/http/server/sun/restEndpoints/resourceStateSnapshots/resourceContents/ByteArraysResourceContent.java
3759
/* * © Crown Copyright 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.nhs.hdn.common.http.server.sun.restEndpoints.resourceStateSnapshots.resourceContents; import com.sun.net.httpserver.HttpExchange; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import uk.nhs.hdn.common.http.ContentTypeWithCharacterSet; import uk.nhs.hdn.common.reflection.toString.AbstractToString; import uk.nhs.hdn.common.reflection.toString.ExcludeFromToString; import java.io.IOException; import java.io.OutputStream; import static java.lang.System.currentTimeMillis; import static uk.nhs.hdn.common.CharsetHelper.Utf8; import static uk.nhs.hdn.common.GregorianCalendarHelper.toRfc2822Form; import static uk.nhs.hdn.common.GregorianCalendarHelper.utc; import static uk.nhs.hdn.common.http.ContentTypeWithCharacterSet.JsonContentTypeUtf8; import static uk.nhs.hdn.common.http.ResponseCode.OkResponseCode; import static uk.nhs.hdn.common.http.server.sun.helpers.ResponseHeadersHelper.withEntityHeaders; import static uk.nhs.hdn.common.http.server.sun.restEndpoints.methodEndpoints.MethodEndpoint.CacheControlHeaderValueOneHour; public final class ByteArraysResourceContent extends AbstractToString implements ResourceContent { private static final byte[] OpenBraceBytes = {(byte) '{'}; private static final byte[] EndingBytes = ");\n".getBytes(Utf8); @NotNull public static ByteArraysResourceContent jsonpByteArraysResourceContent(@NotNull final String jsonpFunctionName, @NotNull final ByteArrayResourceContent jsonUtf8Content) { final byte[] bytes = jsonpFunctionName.getBytes(Utf8); return new ByteArraysResourceContent(JsonContentTypeUtf8, bytes, OpenBraceBytes, jsonUtf8Content.content(), EndingBytes); } private static final long OneHourInMilliseconds = 60 * 60 * 1000; @NotNull @ContentTypeWithCharacterSet @NonNls private final String contentType; @NotNull @ExcludeFromToString private final byte[][] contents; private final long length; @SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter") public ByteArraysResourceContent(@ContentTypeWithCharacterSet @NonNls @NotNull final String contentType, @NotNull final byte[]... contents) { this.contentType = contentType; this.contents = contents; long lengthAccumulator = 0L; for (final byte[] content : contents) { lengthAccumulator += (long) content.length; } this.length = lengthAccumulator; } @Override public void head(@NotNull final HttpExchange httpExchange) throws IOException { httpExchange.sendResponseHeaders(OkResponseCode, length); } @Override public void get(@NotNull final HttpExchange httpExchange) throws IOException { head(httpExchange); try (OutputStream responseBody = httpExchange.getResponseBody()) { for (final byte[] content : contents) { responseBody.write(content); } } } @Override public void setHeaders(@NotNull final HttpExchange httpExchange, @NotNull final String lastModifiedInRfc2822Form) { final String expiresOneHourFromNow = toRfc2822Form(utc(currentTimeMillis() + OneHourInMilliseconds)); withEntityHeaders(httpExchange, contentType, CacheControlHeaderValueOneHour, expiresOneHourFromNow, lastModifiedInRfc2822Form); } }
apache-2.0
Sivl/platform
module/platform-pay/src/main/java/sivl/platform/pay/service/impl/WechatPublicServiceImpl.java
1480
package sivl.platform.pay.service.impl; import java.util.Map; import org.springframework.stereotype.Service; import sivl.platform.common.model.ResultModel; import sivl.platform.pay.constant.ResultCons; import sivl.platform.pay.model.PaymentsModel; import sivl.platform.pay.sdk.wxpay.common.util.ValidataPayment; import sivl.platform.pay.sdk.wxpay.publics.PublicServiceUtil; import sivl.platform.pay.service.PaymentService; @Service("wechatPublicService") public class WechatPublicServiceImpl implements PaymentService{ public ResultModel<Object> payment(Map<String, Object> params) { ResultModel<Object> result = new ResultModel<Object>(); // 参数不为空验证 PaymentsModel payment = new PaymentsModel(params); result = ValidataPayment.validatePayment(payment); if (result.getCode().equals(ResultCons.SUCCESS)) { // 调起支付支付 result = PublicServiceUtil.payment(payment); } return result; } public ResultModel<Object> refundment(Map<String, Object> params) { // TODO Auto-generated method stub return null; } public ResultModel<Object> withdrawal(Map<String, Object> params) { // TODO Auto-generated method stub return null; } public ResultModel<Object> getResult(Map<String, Object> params) { // TODO Auto-generated method stub return null; } public ResultModel<Object> checking(Map<String, Object> params) { // TODO Auto-generated method stub return null; } }
apache-2.0
Groostav/CMPT880-term-project
intruder/benchs/exo/exo.portal.webui.portal-3.8.2.Final-sources/org/exoplatform/portal/application/state/ContextualPropertyManager.java
1386
/* * Copyright (C) 2009 eXo Platform SAS. * * 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.exoplatform.portal.application.state; import java.util.Map; import javax.xml.namespace.QName; import org.exoplatform.portal.webui.application.UIPortlet; /** * @author <a href="mailto:hoang281283@gmail.com">Minh Hoang TO</a> */ public interface ContextualPropertyManager { /** * Returns a map of qualified names and string values for contextual properties of the portlet. * * @param portletWindow the portlet * @return the contextual properties */ Map<QName, String[]> getProperties(UIPortlet portletWindow); }
apache-2.0
JetBrains/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/scaladoc/lexer/ScalaDocElementType.java
485
package org.jetbrains.plugins.scala.lang.scaladoc.lexer; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.scalaDoc.ScalaDocLanguage; /** * User: Alexander Podkhalyuzin * Date: 22.07.2008 */ public class ScalaDocElementType extends IElementType { public ScalaDocElementType(@NotNull @NonNls String debugName) { super(debugName, ScalaDocLanguage.INSTANCE); } }
apache-2.0
dnotez/backend
web-server/src/main/java/com/dz/web/EsStoreModule.java
1313
package com.dz.web; import com.dz.store.es.*; import com.google.inject.AbstractModule; import org.elasticsearch.client.Client; /** * Configure Elasticsearch store bindings * * @author mamad * @since 13/11/14. */ public class EsStoreModule extends AbstractModule { //name of the Elasticsearch client private final String clusterName; //if true, a local JVM node will be created, use it for testing private final boolean localJvm; public EsStoreModule(String clusterName, boolean localJvm) { this.clusterName = clusterName; this.localJvm = localJvm; } @Override protected void configure() { Client client = localJvm ? EsClientBuilder.localClient(clusterName) : EsClientBuilder.client(clusterName); bind(Client.class).toInstance(client); bind(EsQueryBuilderFactory.class).to(NoteQueryBuilderFactory.class); bind(UUIDGenerator.class).to(SimpleUUIDGenerator.class); bind(ActionTimeouts.class).to(DefaultTimeouts.class); bind(NoteSuggestionComposer.class).to(NoteCompletionSuggesterComposer.class); bind(IndexableNoteComposer.class).to(IndexableNoteComposerImpl.class); bind(NoteSuggester.class).to(NoteTitleCompletionSuggester.class); bind(NoteStore.class).to(NoteEsStore.class); } }
apache-2.0
Nickname0806/Test_Q4
java/org/apache/catalina/tribes/transport/nio/NioReceiver.java
18152
/* * 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.catalina.tribes.transport.nio; import java.io.IOException; import java.net.ServerSocket; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Deque; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicReference; import org.apache.catalina.tribes.io.ObjectReader; import org.apache.catalina.tribes.transport.AbstractRxTask; import org.apache.catalina.tribes.transport.ReceiverBase; import org.apache.catalina.tribes.transport.RxTaskPool; import org.apache.catalina.tribes.util.ExceptionUtils; import org.apache.catalina.tribes.util.StringManager; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; public class NioReceiver extends ReceiverBase implements Runnable { private static final Log log = LogFactory.getLog(NioReceiver.class); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(NioReceiver.class); private volatile boolean running = false; private AtomicReference<Selector> selector = new AtomicReference<>(); private ServerSocketChannel serverChannel = null; private DatagramChannel datagramChannel = null; protected final Deque<Runnable> events = new ConcurrentLinkedDeque<>(); public NioReceiver() { } @Override public void stop() { this.stopListening(); super.stop(); } /** * Start cluster receiver. * * @throws IOException If the receiver fails to start * * @see org.apache.catalina.tribes.ChannelReceiver#start() */ @Override public void start() throws IOException { super.start(); try { setPool(new RxTaskPool(getMaxThreads(),getMinThreads(),this)); } catch (Exception x) { log.fatal(sm.getString("nioReceiver.threadpool.fail"), x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } try { getBind(); bind(); String channelName = ""; if (getChannel().getName() != null) channelName = "[" + getChannel().getName() + "]"; Thread t = new Thread(this, "NioReceiver" + channelName); t.setDaemon(true); t.start(); } catch (Exception x) { log.fatal(sm.getString("nioReceiver.start.fail"), x); if ( x instanceof IOException ) throw (IOException)x; else throw new IOException(x.getMessage()); } } @Override public AbstractRxTask createRxTask() { NioReplicationTask thread = new NioReplicationTask(this,this); thread.setUseBufferPool(this.getUseBufferPool()); thread.setRxBufSize(getRxBufSize()); thread.setOptions(getWorkerThreadOptions()); return thread; } protected void bind() throws IOException { // allocate an unbound server socket channel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below this.selector.set(Selector.open()); // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(this.selector.get(), SelectionKey.OP_ACCEPT); //set up the datagram channel if (this.getUdpPort()>0) { datagramChannel = DatagramChannel.open(); configureDatagraChannel(); //bind to the address to avoid security checks bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind()); } } private void configureDatagraChannel() throws IOException { datagramChannel.configureBlocking(false); datagramChannel.socket().setSendBufferSize(getUdpTxBufSize()); datagramChannel.socket().setReceiveBufferSize(getUdpRxBufSize()); datagramChannel.socket().setReuseAddress(getSoReuseAddress()); datagramChannel.socket().setSoTimeout(getTimeout()); datagramChannel.socket().setTrafficClass(getSoTrafficClass()); } public void addEvent(Runnable event) { Selector selector = this.selector.get(); if (selector != null) { events.add(event); if (log.isTraceEnabled()) { log.trace("Adding event to selector:" + event); } if (isListening()) { selector.wakeup(); } } } public void events() { if (events.isEmpty()) { return; } Runnable r = null; while ((r = events.pollFirst()) != null ) { try { if (log.isTraceEnabled()) { log.trace("Processing event in selector:" + r); } r.run(); } catch (Exception x) { log.error("", x); } } } public static void cancelledKey(SelectionKey key) { ObjectReader reader = (ObjectReader)key.attachment(); if ( reader != null ) { reader.setCancelled(true); reader.finish(); } key.cancel(); key.attach(null); if (key.channel() instanceof SocketChannel) try { ((SocketChannel)key.channel()).socket().close(); } catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); } if (key.channel() instanceof DatagramChannel) try { ((DatagramChannel)key.channel()).socket().close(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("", e); } try { key.channel().close(); } catch (IOException e) { if (log.isDebugEnabled()) log.debug("", e); } } protected long lastCheck = System.currentTimeMillis(); protected void socketTimeouts() { long now = System.currentTimeMillis(); if ( (now-lastCheck) < getSelectorTimeout() ) return; //timeout Selector tmpsel = this.selector.get(); Set<SelectionKey> keys = (isListening()&&tmpsel!=null)?tmpsel.keys():null; if ( keys == null ) return; for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) { SelectionKey key = iter.next(); try { // if (key.interestOps() == SelectionKey.OP_READ) { // //only timeout sockets that we are waiting for a read from // ObjectReader ka = (ObjectReader) key.attachment(); // long delta = now - ka.getLastAccess(); // if (delta > (long) getTimeout()) { // cancelledKey(key); // } // } // else if ( key.interestOps() == 0 ) { //check for keys that didn't make it in. ObjectReader ka = (ObjectReader) key.attachment(); if ( ka != null ) { long delta = now - ka.getLastAccess(); if (delta > getTimeout() && (!ka.isAccessed())) { if (log.isWarnEnabled()) log.warn(sm.getString( "nioReceiver.threadsExhausted", Integer.valueOf(getTimeout()), Boolean.valueOf(ka.isCancelled()), key, new java.sql.Timestamp(ka.getLastAccess()))); ka.setLastAccess(now); //key.interestOps(SelectionKey.OP_READ); }//end if } else { cancelledKey(key); }//end if }//end if }catch ( CancelledKeyException ckx ) { cancelledKey(key); } } lastCheck = System.currentTimeMillis(); } /** * Get data from channel and store in byte array * send it to cluster * @throws IOException IO error */ protected void listen() throws Exception { if (doListen()) { log.warn(sm.getString("nioReceiver.alreadyStarted")); return; } setListen(true); // Avoid NPEs if selector is set to null on stop. Selector selector = this.selector.get(); if (selector!=null && datagramChannel!=null) { ObjectReader oreader = new ObjectReader(MAX_UDP_SIZE); //max size for a datagram packet registerChannel(selector,datagramChannel,SelectionKey.OP_READ,oreader); } while (doListen() && selector != null) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { events(); socketTimeouts(); int n = selector.select(getSelectorTimeout()); if (n == 0) { //there is a good chance that we got here //because the TcpReplicationThread called //selector wakeup(). //if that happens, we must ensure that that //thread has enough time to call interestOps // synchronized (interestOpsMutex) { //if we got the lock, means there are no //keys trying to register for the //interestOps method // } continue; // nothing to do } // get an iterator over the set of selected keys Iterator<SelectionKey> it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it!=null && it.hasNext()) { SelectionKey key = it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); channel.socket().setReceiveBufferSize(getTxBufSize()); channel.socket().setSendBufferSize(getTxBufSize()); channel.socket().setTcpNoDelay(getTcpNoDelay()); channel.socket().setKeepAlive(getSoKeepAlive()); channel.socket().setOOBInline(getOoBInline()); channel.socket().setReuseAddress(getSoReuseAddress()); channel.socket().setSoLinger(getSoLingerOn(),getSoLingerTime()); channel.socket().setSoTimeout(getTimeout()); Object attach = new ObjectReader(channel); registerChannel(selector, channel, SelectionKey.OP_READ, attach); } // is there data to read on this channel? if (key.isReadable()) { readDataFromSocket(key); } else { key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } } catch (java.nio.channels.ClosedSelectorException cse) { // ignore is normal at shutdown or stop listen socket } catch (java.nio.channels.CancelledKeyException nx) { log.warn(sm.getString("nioReceiver.clientDisconnect")); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("nioReceiver.requestError"), t); } } serverChannel.close(); if (datagramChannel!=null) { try { datagramChannel.close(); }catch (Exception iox) { if (log.isDebugEnabled()) log.debug("Unable to close datagram channel.",iox); } datagramChannel=null; } closeSelector(); } /** * Close Selector. * * @see org.apache.catalina.tribes.transport.ReceiverBase#stop() */ protected void stopListening() { setListen(false); Selector selector = this.selector.get(); if (selector != null) { try { // Unlock the thread if is is blocked waiting for input selector.wakeup(); // Wait for the receiver thread to finish int count = 0; while (running && count < 50) { Thread.sleep(100); count ++; } if (running) { log.warn(sm.getString("nioReceiver.stop.threadRunning")); } closeSelector(); } catch (Exception x) { log.error(sm.getString("nioReceiver.stop.fail"), x); } finally { this.selector.set(null); } } } private void closeSelector() throws IOException { Selector selector = this.selector.getAndSet(null); if (selector == null) return; try { Iterator<SelectionKey> it = selector.keys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = it.next(); key.channel().close(); key.attach(null); key.cancel(); } } catch (IOException ignore){ if (log.isWarnEnabled()) { log.warn(sm.getString("nioReceiver.cleanup.fail"), ignore); } } catch (ClosedSelectorException ignore){ // Ignore } try { selector.selectNow(); } catch (Throwable t){ ExceptionUtils.handleThrowable(t); // Ignore everything else } selector.close(); } // ---------------------------------------------------------- /** * Register the given channel with the given selector for * the given operations of interest * @param selector The selector to use * @param channel The channel * @param ops The operations to register * @param attach Attachment object * @throws Exception IO error with channel */ protected void registerChannel(Selector selector, SelectableChannel channel, int ops, Object attach) throws Exception { if (channel == null)return; // could happen // set the new channel non-blocking channel.configureBlocking(false); // register it with the selector channel.register(selector, ops, attach); } /** * Start thread and listen */ @Override public void run() { running = true; try { listen(); } catch (Exception x) { log.error(sm.getString("nioReceiver.run.fail"), x); } finally { running = false; } } // ---------------------------------------------------------- /** * Sample data handler method for a channel with data ready to read. * @param key A SelectionKey object associated with a channel * determined by the selector to be ready for reading. If the * channel returns an EOF condition, it is closed here, which * automatically invalidates the associated key. The selector * will then de-register the channel on the next select call. * @throws Exception IO error with channel */ protected void readDataFromSocket(SelectionKey key) throws Exception { NioReplicationTask task = (NioReplicationTask) getTaskPool().getRxTask(); if (task == null) { // No threads/tasks available, do nothing, the selection // loop will keep calling this method until a // thread becomes available, the thread pool itself has a waiting mechanism // so we will not wait here. if (log.isDebugEnabled()) log.debug("No TcpReplicationThread available"); } else { // invoking this wakes up the worker thread then returns //add task to thread pool task.serviceChannel(key); getExecutor().execute(task); } } }
apache-2.0
apereo/cas
support/cas-server-support-cassandra-ticket-registry/src/main/java/org/apereo/cas/ticket/registry/CassandraTicketRegistry.java
11361
package org.apereo.cas.ticket.registry; import org.apereo.cas.cassandra.CassandraSessionFactory; import org.apereo.cas.configuration.model.support.cassandra.ticketregistry.CassandraTicketRegistryProperties; import org.apereo.cas.configuration.support.Beans; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.TicketCatalog; import org.apereo.cas.ticket.TicketDefinition; import org.apereo.cas.ticket.serialization.TicketSerializationManager; import org.apereo.cas.util.function.FunctionUtils; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.querybuilder.QueryBuilder; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import java.util.Collection; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; /** * This is {@link CassandraTicketRegistry}. * * @author Misagh Moayyed * @author doomviking * @since 6.1.0 */ @Slf4j @RequiredArgsConstructor public class CassandraTicketRegistry extends AbstractTicketRegistry implements DisposableBean, InitializingBean { private final TicketCatalog ticketCatalog; private final CassandraSessionFactory cassandraSessionFactory; private final CassandraTicketRegistryProperties properties; private final TicketSerializationManager ticketSerializationManager; private static int getTimeToLive(final Ticket ticket) { val timeToLive = ticket.getExpirationPolicy().getTimeToLive(); val ttl = Long.MAX_VALUE == timeToLive ? Long.valueOf(Integer.MAX_VALUE) : timeToLive; if (ttl >= CassandraSessionFactory.MAX_TTL) { return CassandraSessionFactory.MAX_TTL; } return ttl.intValue(); } @Override public Ticket getTicket(final String ticketId, final Predicate<Ticket> predicate) { LOGGER.trace("Locating ticket [{}]", ticketId); val encodedTicketId = encodeTicketId(ticketId); if (StringUtils.isBlank(encodedTicketId)) { LOGGER.debug("Ticket id [{}] could not be found", ticketId); return null; } val definition = ticketCatalog.find(ticketId); if (definition == null) { LOGGER.debug("Ticket definition [{}] could not be found in the ticket catalog", ticketId); return null; } val holder = findCassandraTicketBy(definition, encodedTicketId); if (holder.isEmpty()) { LOGGER.debug("Ticket [{}] could not be found in Cassandra", encodedTicketId); return null; } val object = deserialize(holder.iterator().next()); val result = decodeTicket(object); return FunctionUtils.doAndReturn(result != null && predicate.test(result), () -> result, () -> { LOGGER.trace("The condition enforced by the predicate [{}] cannot successfully accept/test the ticket id [{}]", encodedTicketId, predicate.getClass().getSimpleName()); return null; }); } @Override public void addTicketInternal(final Ticket ticket) throws Exception { addTicketToCassandra(ticket, true); } @Override public Ticket updateTicket(final Ticket ticket) throws Exception { addTicketToCassandra(ticket, false); return ticket; } @Override public Collection<Ticket> getTickets() { return this.ticketCatalog.findAll() .stream() .map(definition -> { val results = findCassandraTicketBy(definition); return results .stream() .map(holder -> { val result = deserialize(holder); return decodeTicket(result); }) .collect(Collectors.toSet()); }) .flatMap(Set::stream) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @Override public boolean deleteSingleTicket(final String ticketIdToDelete) { val ticketId = encodeTicketId(ticketIdToDelete); LOGGER.debug("Deleting ticket [{}]", ticketId); val definition = this.ticketCatalog.find(ticketIdToDelete); val delete = QueryBuilder .deleteFrom(this.properties.getKeyspace(), definition.getProperties().getStorageName()) .whereColumn("id").isEqualTo(QueryBuilder.literal(ticketId)) .build() .setConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getConsistencyLevel())) .setSerialConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getSerialConsistencyLevel())) .setTimeout(Beans.newDuration(properties.getTimeout())); cassandraSessionFactory.getCqlTemplate().execute(delete); return true; } @Override public long deleteAll() { ticketCatalog.findAll() .forEach(definition -> { val delete = QueryBuilder .truncate(this.properties.getKeyspace(), definition.getProperties().getStorageName()) .build() .setConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getConsistencyLevel())) .setSerialConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getSerialConsistencyLevel())) .setTimeout(Beans.newDuration(properties.getTimeout())); LOGGER.trace("Attempting to delete all via query [{}]", delete); cassandraSessionFactory.getCqlTemplate().execute(delete); }); return -1; } @Override public void destroy() throws Exception { this.cassandraSessionFactory.close(); } @Override public void afterPropertiesSet() { createTablesIfNecessary(); } private Ticket deserialize(final CassandraTicketHolder holder) { return ticketSerializationManager.deserializeTicket(holder.getData(), holder.getType()); } private Collection<CassandraTicketHolder> findCassandraTicketBy(final TicketDefinition definition) { return findCassandraTicketBy(definition, null); } private Collection<CassandraTicketHolder> findCassandraTicketBy(final TicketDefinition definition, final String ticketId) { val builder = QueryBuilder.selectFrom(this.properties.getKeyspace(), definition.getProperties().getStorageName()).all(); if (StringUtils.isNotBlank(ticketId)) { builder.whereColumn("id").isEqualTo(QueryBuilder.literal(ticketId)).limit(1); } val select = builder.build() .setConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getConsistencyLevel())) .setSerialConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getSerialConsistencyLevel())) .setTimeout(Beans.newDuration(properties.getTimeout())); LOGGER.trace("Attempting to locate ticket via query [{}]", select); return cassandraSessionFactory.getCqlTemplate().query(select, (row, i) -> { val id = row.get("id", String.class); val data = row.get("data", String.class); val type = row.get("type", String.class); return new CassandraTicketHolder(id, data, type); }); } private void createTablesIfNecessary() { val createNs = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ") .append(this.properties.getKeyspace()).append(" WITH replication = {") .append("'class':'SimpleStrategy','replication_factor':1") .append("};") .toString(); LOGGER.trace("Creating Cassandra keyspace with query [{}]", createNs); cassandraSessionFactory.getCqlTemplate().execute(createNs); ticketCatalog.findAll() .stream() .filter(metadata -> StringUtils.isNotBlank(metadata.getProperties().getStorageName())) .forEach(metadata -> { if (properties.isDropTablesOnStartup()) { val drop = new StringBuilder("DROP TABLE IF EXISTS ") .append(this.properties.getKeyspace()) .append('.') .append(metadata.getProperties().getStorageName()) .append(';') .toString(); LOGGER.trace("Dropping Cassandra table with query [{}]", drop); cassandraSessionFactory.getCqlTemplate().execute(drop); } val createTable = new StringBuilder("CREATE TABLE IF NOT EXISTS ") .append(this.properties.getKeyspace()) .append('.') .append(metadata.getProperties().getStorageName()) .append('(') .append("id text,") .append("type text,") .append("data text, ") .append("PRIMARY KEY(id,type) ") .append(");") .toString(); LOGGER.trace("Creating Cassandra table with query [{}]", createTable); cassandraSessionFactory.getCqlTemplate().execute(createTable); }); } private void addTicketToCassandra(final Ticket ticket, final boolean inserting) throws Exception { LOGGER.debug("Adding ticket [{}]", ticket.getId()); val metadata = this.ticketCatalog.find(ticket); LOGGER.trace("Located ticket definition [{}] in the ticket catalog", metadata); val encTicket = encodeTicket(ticket); val data = ticketSerializationManager.serializeTicket(encTicket); val ttl = getTimeToLive(ticket); var insert = (Statement) null; if (inserting) { insert = QueryBuilder.insertInto(this.properties.getKeyspace(), metadata.getProperties().getStorageName()) .value("id", QueryBuilder.literal(encTicket.getId())) .value("data", QueryBuilder.literal(data)) .value("type", QueryBuilder.literal(encTicket.getClass().getName())) .usingTtl(ttl) .build(); } else { insert = QueryBuilder.update(this.properties.getKeyspace(), metadata.getProperties().getStorageName()) .usingTtl(ttl) .setColumn("data", QueryBuilder.literal(data)) .whereColumn("id").isEqualTo(QueryBuilder.literal(encTicket.getId())) .whereColumn("type").isEqualTo(QueryBuilder.literal(encTicket.getClass().getName())) .build(); } insert = insert.setConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getConsistencyLevel())) .setSerialConsistencyLevel(DefaultConsistencyLevel.valueOf(properties.getSerialConsistencyLevel())) .setTimeout(Beans.newDuration(properties.getTimeout())); LOGGER.trace("Attempting to locate ticket via query [{}]", insert); cassandraSessionFactory.getCqlTemplate().execute(insert); LOGGER.debug("Added ticket [{}]", encTicket.getId()); } }
apache-2.0
googleapis/discovery-artifact-manager
toolkit/src/main/java/com/google/api/codegen/transformer/ModelTypeFormatterImpl.java
2801
/* Copyright 2016 Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.transformer; import com.google.api.codegen.config.FieldModel; import com.google.api.codegen.config.InterfaceModel; import com.google.api.codegen.config.ProtoInterfaceModel; import com.google.api.tools.framework.model.ProtoElement; import com.google.api.tools.framework.model.TypeRef; /** Default implementation of ModelTypeFormatter. */ public class ModelTypeFormatterImpl implements ModelTypeFormatter { private ModelTypeNameConverter typeNameConverter; public ModelTypeFormatterImpl(ModelTypeNameConverter typeNameConverter) { this.typeNameConverter = typeNameConverter; } @Override public String getImplicitPackageFullNameFor(String shortName) { return typeNameConverter.getTypeNameInImplicitPackage(shortName).getFullName(); } @Override public String getFullNameFor(TypeRef type) { return typeNameConverter.getTypeName(type).getFullName(); } @Override public String getFullNameFor(ProtoElement element) { return typeNameConverter.getTypeName(element).getFullName(); } @Override public String getFullNameFor(InterfaceModel interfaceModel) { return typeNameConverter .getTypeName(((ProtoInterfaceModel) interfaceModel).getInterface()) .getFullName(); } @Override public String getFullNameForElementType(TypeRef type) { return typeNameConverter.getTypeNameForElementType(type).getFullName(); } @Override public String getNicknameFor(TypeRef type) { return typeNameConverter.getTypeName(type).getNickname(); } @Override public String renderPrimitiveValue(TypeRef type, String value) { return typeNameConverter.renderPrimitiveValue(type, value); } @Override public String getFullNameFor(FieldModel type) { return getFullNameFor(type.getProtoTypeRef()); } @Override public String getFullNameForElementType(FieldModel type) { return getFullNameForElementType(type.getProtoTypeRef()); } @Override public String getNicknameFor(FieldModel type) { return getNicknameFor(type.getProtoTypeRef()); } @Override public String renderPrimitiveValue(FieldModel type, String key) { return renderPrimitiveValue(type.getProtoTypeRef(), key); } }
apache-2.0
jhelmer-unicon/uPortal
uportal-war/src/test/java/org/apereo/portal/io/xml/user/UserDataUpgradeTest.java
2690
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.apereo.portal.io.xml.user; import org.apereo.portal.io.xml.BaseXsltDataUpgraderTest; import org.junit.Test; import org.springframework.core.io.ClassPathResource; /** @author Eric Dalquist */ public class UserDataUpgradeTest extends BaseXsltDataUpgraderTest { @Test public void testUpgradeUser26to40() throws Exception { testXsltUpgrade( new ClassPathResource("/org/apereo/portal/io/xml/user/upgrade-user_3-2.xsl"), UserPortalDataType.IMPORT_26_DATA_KEY, new ClassPathResource("/org/apereo/portal/io/xml/user/test_2-6.user.xml"), new ClassPathResource( "/org/apereo/portal/io/xml/user/test_2-6_to_4-0_expected.user.xml"), new ClassPathResource("/xsd/io/user/user-4.0.xsd")); } @Test public void testUpgradeUser30to40() throws Exception { testXsltUpgrade( new ClassPathResource("/org/apereo/portal/io/xml/user/upgrade-user_3-2.xsl"), UserPortalDataType.IMPORT_30_DATA_KEY, new ClassPathResource("/org/apereo/portal/io/xml/user/test_3-0.user.xml"), new ClassPathResource( "/org/apereo/portal/io/xml/user/test_3-0_to_4-0_expected.user.xml"), new ClassPathResource("/xsd/io/user/user-4.0.xsd")); } @Test public void testUpgradeUser32to40() throws Exception { testXsltUpgrade( new ClassPathResource("/org/apereo/portal/io/xml/user/upgrade-user_3-2.xsl"), UserPortalDataType.IMPORT_32_DATA_KEY, new ClassPathResource("/org/apereo/portal/io/xml/user/test_3-2.user.xml"), new ClassPathResource( "/org/apereo/portal/io/xml/user/test_3-2_to_4-0_expected.user.xml"), new ClassPathResource("/xsd/io/user/user-4.0.xsd")); } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-authorizedbuyersmarketplace/v1/1.31.0/com/google/api/services/authorizedbuyersmarketplace/v1/model/Note.java
3298
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.authorizedbuyersmarketplace.v1.model; /** * A text note attached to the proposal to facilitate the communication between buyers and sellers. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Authorized Buyers Marketplace API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Note extends com.google.api.client.json.GenericJson { /** * Output only. When this note was created. * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * Output only. The role who created the note. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creatorRole; /** * The text of the note. Maximum length is 1024 characters. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String note; /** * Output only. When this note was created. * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Output only. When this note was created. * @param createTime createTime or {@code null} for none */ public Note setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * Output only. The role who created the note. * @return value or {@code null} for none */ public java.lang.String getCreatorRole() { return creatorRole; } /** * Output only. The role who created the note. * @param creatorRole creatorRole or {@code null} for none */ public Note setCreatorRole(java.lang.String creatorRole) { this.creatorRole = creatorRole; return this; } /** * The text of the note. Maximum length is 1024 characters. * @return value or {@code null} for none */ public java.lang.String getNote() { return note; } /** * The text of the note. Maximum length is 1024 characters. * @param note note or {@code null} for none */ public Note setNote(java.lang.String note) { this.note = note; return this; } @Override public Note set(String fieldName, Object value) { return (Note) super.set(fieldName, value); } @Override public Note clone() { return (Note) super.clone(); } }
apache-2.0
engaric/graphhopper
core/src/main/java/uk/co/ordnancesurvey/api/srs/LatLong.java
118
package uk.co.ordnancesurvey.api.srs; public interface LatLong { double getLatAngle(); double getLongAngle(); }
apache-2.0
consulo/consulo
modules/web/web-platform-impl/src/main/java/consulo/web/platform/WebPlatformImpl.java
804
/* * Copyright 2013-2017 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.web.platform; import consulo.platform.impl.PlatformBase; /** * @author VISTALL * @since 15-Sep-17 */ public class WebPlatformImpl extends PlatformBase { public WebPlatformImpl() { } }
apache-2.0
safarmer/bazel
src/main/java/com/google/devtools/build/lib/sandbox/SandboxModule.java
24728
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.sandbox; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.GoogleLogger; import com.google.devtools.build.lib.actions.ExecException; import com.google.devtools.build.lib.actions.Spawn; import com.google.devtools.build.lib.actions.SpawnExecutedEvent; import com.google.devtools.build.lib.actions.SpawnResult; import com.google.devtools.build.lib.buildtool.buildevent.BuildCompleteEvent; import com.google.devtools.build.lib.buildtool.buildevent.BuildInterruptedEvent; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.exec.ExecutionOptions; import com.google.devtools.build.lib.exec.RunfilesTreeUpdater; import com.google.devtools.build.lib.exec.SpawnRunner; import com.google.devtools.build.lib.exec.SpawnStrategyRegistry; import com.google.devtools.build.lib.exec.TreeDeleter; import com.google.devtools.build.lib.exec.local.LocalEnvProvider; import com.google.devtools.build.lib.exec.local.LocalExecutionOptions; import com.google.devtools.build.lib.exec.local.LocalSpawnRunner; import com.google.devtools.build.lib.profiler.Profiler; import com.google.devtools.build.lib.profiler.SilentCloseable; import com.google.devtools.build.lib.runtime.BlazeModule; import com.google.devtools.build.lib.runtime.Command; import com.google.devtools.build.lib.runtime.CommandEnvironment; import com.google.devtools.build.lib.runtime.ProcessWrapper; import com.google.devtools.build.lib.server.FailureDetails.FailureDetail; import com.google.devtools.build.lib.server.FailureDetails.Sandbox; import com.google.devtools.build.lib.util.AbruptExitException; import com.google.devtools.build.lib.util.DetailedExitCode; import com.google.devtools.build.lib.util.Fingerprint; import com.google.devtools.build.lib.util.OS; import com.google.devtools.build.lib.vfs.FileSystem; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.common.options.OptionsBase; import com.google.devtools.common.options.TriState; import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; /** This module provides the Sandbox spawn strategy. */ public final class SandboxModule extends BlazeModule { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); /** Tracks whether we are issuing the very first build within this Bazel server instance. */ private static boolean firstBuild = true; /** Environment for the running command. */ @Nullable private CommandEnvironment env; /** Path to the location of the sandboxes. */ @Nullable private Path sandboxBase; /** Instance of the sandboxfs process in use, if enabled. */ @Nullable private SandboxfsProcess sandboxfsProcess; /** * Collection of spawn runner instantiated during the executor setup. * * <p>We need this information to clean up the heavy subdirectories of the sandbox base on build * completion but to avoid wiping the whole sandbox base itself, which could be problematic across * builds. */ private final Set<SpawnRunner> spawnRunners = new HashSet<>(); /** * Handler to process expensive tree deletions outside of the critical path. * * <p>Sandboxing creates one separate tree for each action, and this tree is used to run the * action commands in. These trees are disjoint for all actions and have unique identifiers. * Therefore, there is no need for their deletion (which can be very expensive) to happen in the * critical path -- so if the user so wishes, we process those deletions asynchronously. */ @Nullable private TreeDeleter treeDeleter; /** * Whether to remove the sandbox worker directories after a build or not. Useful for debugging to * inspect the state of files on failures. */ private boolean shouldCleanupSandboxBase; @Override public Iterable<Class<? extends OptionsBase>> getCommandOptions(Command command) { return "build".equals(command.name()) ? ImmutableList.of(SandboxOptions.class) : ImmutableList.of(); } /** Computes the path to the sandbox base tree for the given running command. */ private static Path computeSandboxBase(SandboxOptions options, CommandEnvironment env) throws IOException { if (options.sandboxBase.isEmpty()) { return env.getOutputBase().getRelative("sandbox"); } else { String dirName = String.format( "%s-sandbox.%s", env.getRuntime().getProductName(), Fingerprint.getHexDigest(env.getOutputBase().toString())); FileSystem fileSystem = env.getRuntime().getFileSystem(); Path resolvedSandboxBase = fileSystem.getPath(options.sandboxBase).resolveSymbolicLinks(); return resolvedSandboxBase.getRelative(dirName); } } @Override public void beforeCommand(CommandEnvironment env) { // We can't assert that env is null because the Blaze runtime does not guarantee that // afterCommand() will be called if the command fails due to, e.g. a syntax error. this.env = env; env.getEventBus().register(this); // Don't attempt cleanup unless the executor is initialized. shouldCleanupSandboxBase = false; } @Override public void registerSpawnStrategies( SpawnStrategyRegistry.Builder registryBuilder, CommandEnvironment env) throws AbruptExitException, InterruptedException { checkNotNull(env, "env not initialized; was beforeCommand called?"); try { setup(env, registryBuilder); } catch (IOException e) { throw new AbruptExitException( DetailedExitCode.of( FailureDetail.newBuilder() .setMessage(String.format("Failed to initialize sandbox: %s", e.getMessage())) .setSandbox( Sandbox.newBuilder().setCode(Sandbox.Code.INITIALIZATION_FAILURE).build()) .build()), e); } } /** * Returns true if windows-sandbox should be used for this build. * * <p>Returns true if requested in ["auto", "yes"] and binary is valid. Throws an error if state * is "yes" and binary is not valid. * * @param requested whether windows-sandbox use was requested or not * @param binary path of the windows-sandbox binary to use, can be absolute or relative path * @return true if windows-sandbox can and should be used; false otherwise * @throws IOException if there are problems trying to determine the status of windows-sandbox */ private static boolean shouldUseWindowsSandbox(TriState requested, PathFragment binary) throws IOException { switch (requested) { case AUTO: return WindowsSandboxUtil.isAvailable(binary); case NO: return false; case YES: if (!WindowsSandboxUtil.isAvailable(binary)) { throw new IOException( "windows-sandbox explicitly requested but \"" + binary + "\" could not be found or is not valid"); } return true; } throw new IllegalStateException("Not reachable"); } private void setup(CommandEnvironment cmdEnv, SpawnStrategyRegistry.Builder builder) throws IOException, InterruptedException { SandboxOptions options = checkNotNull(env.getOptions().getOptions(SandboxOptions.class)); sandboxBase = computeSandboxBase(options, env); SandboxHelpers helpers = new SandboxHelpers(options.delayVirtualInputMaterialization); // Do not remove the sandbox base when --sandbox_debug was specified so that people can check // out the contents of the generated sandbox directories. shouldCleanupSandboxBase = !options.sandboxDebug; // If there happens to be any live tree deleter from a previous build and it's different than // the one we want now, leave it alone (i.e. don't attempt to wait for pending deletions). Its // deletions shouldn't overlap any new directories we create during this build (because the // identifiers in the subdirectories will be different). if (options.asyncTreeDeleteIdleThreads == 0) { if (!(treeDeleter instanceof SynchronousTreeDeleter)) { treeDeleter = new SynchronousTreeDeleter(); } } else { if (!(treeDeleter instanceof AsynchronousTreeDeleter)) { treeDeleter = new AsynchronousTreeDeleter(); } } Path mountPoint = sandboxBase.getRelative("sandboxfs"); if (sandboxfsProcess != null) { if (options.sandboxDebug) { env.getReporter() .handle( Event.info( "Unmounting sandboxfs instance left behind on " + mountPoint + " by a previous command")); } sandboxfsProcess.destroy(); sandboxfsProcess = null; } // SpawnExecutionPolicy#getId returns unique base directories for each sandboxed action during // the life of a Bazel server instance so we don't need to worry about stale directories from // previous builds. However, on the very first build of an instance of the server, we must // wipe old contents to avoid reusing stale directories. if (firstBuild && sandboxBase.exists()) { cmdEnv.getReporter().handle(Event.info("Deleting stale sandbox base " + sandboxBase)); sandboxBase.deleteTree(); } firstBuild = false; PathFragment sandboxfsPath = PathFragment.create(options.sandboxfsPath); sandboxBase.createDirectoryAndParents(); if (options.useSandboxfs != TriState.NO) { mountPoint.createDirectory(); Path logFile = sandboxBase.getRelative("sandboxfs.log"); if (sandboxfsProcess == null) { if (options.sandboxDebug) { env.getReporter().handle(Event.info("Mounting sandboxfs instance on " + mountPoint)); } try (SilentCloseable c = Profiler.instance().profile("mountSandboxfs")) { sandboxfsProcess = RealSandboxfsProcess.mount(sandboxfsPath, mountPoint, logFile); } catch (IOException e) { if (options.sandboxDebug) { env.getReporter() .handle( Event.info( "sandboxfs failed to mount due to " + e.getMessage() + "; ignoring")); } if (options.useSandboxfs == TriState.YES) { throw e; } } } } PathFragment windowsSandboxPath = PathFragment.create(options.windowsSandboxPath); boolean windowsSandboxSupported; try (SilentCloseable c = Profiler.instance().profile("shouldUseWindowsSandbox")) { windowsSandboxSupported = shouldUseWindowsSandbox(options.useWindowsSandbox, windowsSandboxPath); } Duration timeoutKillDelay = cmdEnv.getOptions().getOptions(LocalExecutionOptions.class).getLocalSigkillGraceSeconds(); boolean processWrapperSupported = ProcessWrapperSandboxedSpawnRunner.isSupported(cmdEnv); boolean linuxSandboxSupported = LinuxSandboxedSpawnRunner.isSupported(cmdEnv); boolean darwinSandboxSupported = DarwinSandboxedSpawnRunner.isSupported(cmdEnv); boolean verboseFailures = checkNotNull(cmdEnv.getOptions().getOptions(ExecutionOptions.class)).verboseFailures; // This works on most platforms, but isn't the best choice, so we put it first and let later // platform-specific sandboxing strategies become the default. if (processWrapperSupported) { SpawnRunner spawnRunner = withFallback( cmdEnv, new ProcessWrapperSandboxedSpawnRunner( helpers, cmdEnv, sandboxBase, sandboxfsProcess, options.sandboxfsMapSymlinkTargets, treeDeleter)); spawnRunners.add(spawnRunner); builder.registerStrategy( new ProcessWrapperSandboxedStrategy(cmdEnv.getExecRoot(), spawnRunner, verboseFailures), "sandboxed", "processwrapper-sandbox"); } if (options.enableDockerSandbox) { // This strategy uses Docker to execute spawns. It should work on all platforms that support // Docker. Path pathToDocker = getPathToDockerClient(cmdEnv); // DockerSandboxedSpawnRunner.isSupported is expensive! It runs docker as a subprocess, and // docker hangs sometimes. if (pathToDocker != null && DockerSandboxedSpawnRunner.isSupported(cmdEnv, pathToDocker)) { String defaultImage = options.dockerImage; boolean useCustomizedImages = options.dockerUseCustomizedImages; SpawnRunner spawnRunner = withFallback( cmdEnv, new DockerSandboxedSpawnRunner( helpers, cmdEnv, pathToDocker, sandboxBase, defaultImage, useCustomizedImages, treeDeleter)); spawnRunners.add(spawnRunner); builder.registerStrategy( new DockerSandboxedStrategy(cmdEnv.getExecRoot(), spawnRunner, verboseFailures), "docker"); } } else if (options.dockerVerbose) { cmdEnv .getReporter() .handle( Event.info( "Docker sandboxing disabled. Use the '--experimental_enable_docker_sandbox'" + " command line option to enable it")); } // This is the preferred sandboxing strategy on Linux. if (linuxSandboxSupported) { SpawnRunner spawnRunner = withFallback( cmdEnv, LinuxSandboxedStrategy.create( helpers, cmdEnv, sandboxBase, timeoutKillDelay, sandboxfsProcess, options.sandboxfsMapSymlinkTargets, treeDeleter)); spawnRunners.add(spawnRunner); builder.registerStrategy( new LinuxSandboxedStrategy(cmdEnv.getExecRoot(), spawnRunner, verboseFailures), "sandboxed", "linux-sandbox"); } // This is the preferred sandboxing strategy on macOS. if (darwinSandboxSupported) { SpawnRunner spawnRunner = withFallback( cmdEnv, new DarwinSandboxedSpawnRunner( helpers, cmdEnv, sandboxBase, sandboxfsProcess, options.sandboxfsMapSymlinkTargets, treeDeleter)); spawnRunners.add(spawnRunner); builder.registerStrategy( new DarwinSandboxedStrategy(cmdEnv.getExecRoot(), spawnRunner, verboseFailures), "sandboxed", "darwin-sandbox"); } if (windowsSandboxSupported) { SpawnRunner spawnRunner = withFallback( cmdEnv, new WindowsSandboxedSpawnRunner( helpers, cmdEnv, timeoutKillDelay, windowsSandboxPath)); spawnRunners.add(spawnRunner); builder.registerStrategy( new WindowsSandboxedStrategy(cmdEnv.getExecRoot(), spawnRunner, verboseFailures), "sandboxed", "windows-sandbox"); } if (processWrapperSupported || linuxSandboxSupported || darwinSandboxSupported || windowsSandboxSupported) { // This makes the "sandboxed" strategy the default Spawn strategy, unless it is // overridden by a later BlazeModule. builder.setDefaultStrategies(ImmutableList.of("sandboxed")); } } private static Path getPathToDockerClient(CommandEnvironment cmdEnv) { String path = cmdEnv.getClientEnv().getOrDefault("PATH", ""); // TODO(philwo): Does this return the correct result if one of the elements intentionally ends // in white space? Splitter pathSplitter = Splitter.on(OS.getCurrent() == OS.WINDOWS ? ';' : ':').trimResults().omitEmptyStrings(); FileSystem fs = cmdEnv.getRuntime().getFileSystem(); for (String pathElement : pathSplitter.split(path)) { // Sometimes the PATH contains the non-absolute entry "." - this resolves it against the // current working directory. pathElement = new File(pathElement).getAbsolutePath(); try { for (Path dentry : fs.getPath(pathElement).getDirectoryEntries()) { if (dentry.getBaseName().replace(".exe", "").equals("docker")) { return dentry; } } } catch (IOException e) { continue; } } return null; } private static SpawnRunner withFallback(CommandEnvironment env, SpawnRunner sandboxSpawnRunner) { return new SandboxFallbackSpawnRunner( sandboxSpawnRunner, createFallbackRunner(env), env.getReporter()); } private static SpawnRunner createFallbackRunner(CommandEnvironment env) { LocalExecutionOptions localExecutionOptions = env.getOptions().getOptions(LocalExecutionOptions.class); return new LocalSpawnRunner( env.getExecRoot(), localExecutionOptions, env.getLocalResourceManager(), LocalEnvProvider.forCurrentOs(env.getClientEnv()), env.getBlazeWorkspace().getBinTools(), ProcessWrapper.fromCommandEnvironment(env), // TODO(buchgr): Replace singleton by a command-scoped RunfilesTreeUpdater RunfilesTreeUpdater.INSTANCE); } private static final class SandboxFallbackSpawnRunner implements SpawnRunner { private final SpawnRunner sandboxSpawnRunner; private final SpawnRunner fallbackSpawnRunner; private final ExtendedEventHandler extendedEventHandler; SandboxFallbackSpawnRunner( SpawnRunner sandboxSpawnRunner, SpawnRunner fallbackSpawnRunner, ExtendedEventHandler extendedEventHandler) { this.sandboxSpawnRunner = sandboxSpawnRunner; this.fallbackSpawnRunner = fallbackSpawnRunner; this.extendedEventHandler = extendedEventHandler; } @Override public String getName() { return "sandbox-fallback"; } @Override public SpawnResult exec(Spawn spawn, SpawnExecutionContext context) throws InterruptedException, IOException, ExecException { Instant spawnExecutionStartInstant = Instant.now(); SpawnResult spawnResult; if (sandboxSpawnRunner.canExec(spawn)) { spawnResult = sandboxSpawnRunner.exec(spawn, context); } else { spawnResult = fallbackSpawnRunner.exec(spawn, context); } extendedEventHandler.post( new SpawnExecutedEvent(spawn, spawnResult, spawnExecutionStartInstant)); return spawnResult; } @Override public boolean canExec(Spawn spawn) { return sandboxSpawnRunner.canExec(spawn) || fallbackSpawnRunner.canExec(spawn); } @Override public boolean handlesCaching() { return false; } @Override public void cleanupSandboxBase(Path sandboxBase, TreeDeleter treeDeleter) throws IOException { sandboxSpawnRunner.cleanupSandboxBase(sandboxBase, treeDeleter); fallbackSpawnRunner.cleanupSandboxBase(sandboxBase, treeDeleter); } } /** * Unmounts an existing sandboxfs instance unless the user asked not to by providing the {@code * --sandbox_debug} flag. */ private void unmountSandboxfs() { if (sandboxfsProcess != null) { if (shouldCleanupSandboxBase) { sandboxfsProcess.destroy(); sandboxfsProcess = null; } else { checkNotNull(env, "env not initialized; was beforeCommand called?"); env.getReporter() .handle(Event.info("Leaving sandboxfs mounted because of --sandbox_debug")); } } } /** Silently tries to unmount an existing sandboxfs instance, ignoring errors. */ private void tryUnmountSandboxfsOnShutdown() { if (sandboxfsProcess != null) { sandboxfsProcess.destroy(); sandboxfsProcess = null; } } @Subscribe public void buildComplete(@SuppressWarnings("unused") BuildCompleteEvent event) { unmountSandboxfs(); } @Subscribe public void buildInterrupted(@SuppressWarnings("unused") BuildInterruptedEvent event) { unmountSandboxfs(); } /** * Best-effort cleanup of the sandbox base assuming all per-spawn contents have been removed. * * <p>When this gets called, the individual trees of each spawn should have been cleaned up but we * may be left with the top-level subdirectories used by each sandboxed spawn runner (e.g. {@code * darwin-sandbox}) and the sandbox base itself. Try to delete those so that a Bazel server * restart doesn't print a spurious {@code Deleting stale sandbox base} message. */ private static void cleanupSandboxBaseTop(Path sandboxBase) { try { // This might be called twice for a given sandbox base, so don't bother recording error // messages if any of the files we try to delete don't exist. for (Path leftover : sandboxBase.getDirectoryEntries()) { leftover.delete(); } sandboxBase.delete(); } catch (IOException e) { logger.atWarning().withCause(e).log("Failed to clean up sandbox base %s", sandboxBase); } } @Override public void afterCommand() { checkNotNull(env, "env not initialized; was beforeCommand called?"); SandboxOptions options = env.getOptions().getOptions(SandboxOptions.class); int asyncTreeDeleteThreads = options != null ? options.asyncTreeDeleteIdleThreads : 0; if (treeDeleter != null && asyncTreeDeleteThreads > 0) { // If asynchronous deletions were requested, they may still be ongoing so let them be: trying // to delete the base tree synchronously could fail as we can race with those other deletions, // and scheduling an asynchronous deletion could race with future builds. AsynchronousTreeDeleter treeDeleter = (AsynchronousTreeDeleter) checkNotNull(this.treeDeleter); treeDeleter.setThreads(asyncTreeDeleteThreads); } if (shouldCleanupSandboxBase) { try { checkNotNull(sandboxBase, "shouldCleanupSandboxBase implies sandboxBase has been set"); for (SpawnRunner spawnRunner : spawnRunners) { spawnRunner.cleanupSandboxBase(sandboxBase, treeDeleter); } } catch (IOException e) { env.getReporter() .handle(Event.warn("Failed to delete contents of sandbox " + sandboxBase + ": " + e)); } shouldCleanupSandboxBase = false; checkState( sandboxfsProcess == null, "sandboxfs instance should have been shut down at this " + "point; were the buildComplete/buildInterrupted events sent?"); cleanupSandboxBaseTop(sandboxBase); // We intentionally keep sandboxBase around, without resetting it to null, in case we have // asynchronous deletions going on. In that case, we'd still want to retry this during // shutdown. } spawnRunners.clear(); env.getEventBus().unregister(this); env = null; } private void commonShutdown() { tryUnmountSandboxfsOnShutdown(); // Try to clean up as much garbage as possible, if there happens to be any. This will delay // server termination but it's the nice thing to do. If the user gets impatient, they can always // kill us again. if (treeDeleter != null) { try { treeDeleter.shutdown(); } finally { treeDeleter = null; // Avoid potential reexecution if we crash. } } if (sandboxBase != null) { cleanupSandboxBaseTop(sandboxBase); } } @Override public void blazeShutdown() { commonShutdown(); } @Override public void blazeShutdownOnCrash(DetailedExitCode exitCode) { commonShutdown(); } }
apache-2.0
ParkJinSang/Jinseng-Server
src/connection/ConnectlessUnit.java
820
package connection; import java.io.IOException; import java.net.DatagramSocket; import core.udp.IUdpServiceLogic; public class ConnectlessUnit implements Runnable{ /*** * This is the Access Unit for handling UDP protocol. * */ private IUdpServiceLogic logic = null; private DatagramSocket socket; private Object request; public ConnectlessUnit(IUdpServiceLogic logic, DatagramSocket socket, Object request){ this.logic = logic; this.socket = socket; this.request = request; System.out.println("New client access the server."); } /*** * Only handle response as per given requests. */ @Override public void run() { // TODO Auto-generated method stub try{ logic.SendResponse(request); //Call response handle method. }finally{ //Do not close the socket. } } }
apache-2.0
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/plan/FilterNode.java
3371
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.spi.plan; import com.facebook.presto.spi.SourceLocation; import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.concurrent.Immutable; import java.util.List; import java.util.Objects; import java.util.Optional; import static java.util.Collections.singletonList; import static java.util.Collections.unmodifiableList; @Immutable public final class FilterNode extends PlanNode { private final PlanNode source; private final RowExpression predicate; @JsonCreator public FilterNode( Optional<SourceLocation> sourceLocation, @JsonProperty("id") PlanNodeId id, @JsonProperty("source") PlanNode source, @JsonProperty("predicate") RowExpression predicate) { super(sourceLocation, id); this.source = source; this.predicate = predicate; } /** * Get the predicate (a RowExpression of boolean type) of the FilterNode. * It serves as the criteria to determine whether the incoming rows should be filtered out or not. */ @JsonProperty public RowExpression getPredicate() { return predicate; } /** * FilterNode only expects a single upstream PlanNode. */ @JsonProperty("source") public PlanNode getSource() { return source; } @Override public List<VariableReferenceExpression> getOutputVariables() { return source.getOutputVariables(); } @Override public List<PlanNode> getSources() { return unmodifiableList(singletonList(source)); } @Override public <R, C> R accept(PlanVisitor<R, C> visitor, C context) { return visitor.visitFilter(this, context); } @Override public PlanNode replaceChildren(List<PlanNode> newChildren) { // FilterNode only expects a single upstream PlanNode if (newChildren == null || newChildren.size() != 1) { throw new IllegalArgumentException("Expect exactly one child to replace"); } return new FilterNode(getSourceLocation(), getId(), newChildren.get(0), predicate); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterNode that = (FilterNode) o; return Objects.equals(source, that.source) && Objects.equals(predicate, that.predicate); } @Override public int hashCode() { return Objects.hash(source, predicate); } }
apache-2.0
sheremetat/newrelic-integration
newrelic-report-standalone/src/main/java/com/signalfx/newrelic/report/NewRelicReportModule.java
1225
/** * Copyright (C) 2015 SignalFx, Inc. */ package com.signalfx.newrelic.report; import com.codahale.metrics.MetricRegistry; import com.google.inject.AbstractModule; import com.signalfx.newrelic.client.MetricDataRequest; import com.signalfx.newrelic.process.reporter.Reporter; import com.signalfx.newrelic.report.config.ConnectionConfig; import com.signalfx.newrelic.report.reporter.SignalFxRestReporter; /** * Module configurations for NewRelicReport using given connection config. * * @author 9park */ public class NewRelicReportModule extends AbstractModule { private final ConnectionConfig connectionConfig; private final MetricRegistry metricRegistry; public NewRelicReportModule(ConnectionConfig connectionConfig, MetricRegistry metricRegistry) { this.connectionConfig = connectionConfig; this.metricRegistry = metricRegistry; } @Override protected void configure() { bind(MetricDataRequest.class).toInstance(new MetricDataRequest(connectionConfig.newRelicURL, connectionConfig.newRelicApiKey)); bind(Reporter.class).toInstance(new SignalFxRestReporter(connectionConfig.fxToken)); bind(MetricRegistry.class).toInstance(metricRegistry); } }
apache-2.0
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201311/OperatingSystem.java
2697
/** * OperatingSystem.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201311; /** * Represents an Operating System, such as Linux, Mac OS or Windows. */ public class OperatingSystem extends com.google.api.ads.dfp.v201311.Technology implements java.io.Serializable { public OperatingSystem() { } public OperatingSystem( java.lang.Long id, java.lang.String name, java.lang.String technologyType) { super( id, name, technologyType); } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof OperatingSystem)) return false; OperatingSystem other = (OperatingSystem) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(OperatingSystem.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "OperatingSystem")); } /** * 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
shadowmint/bamboo-leaderboard
src/main/java/faux/mvc/extend/ITemplatePath.java
885
/* * Copyright 2011 iiNet * * 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 faux.mvc.extend; import java.io.InputStream; import faux.mvc.Context; /** Implement this in the app for domain specific template path resolution. */ public interface ITemplatePath { InputStream resolvePath(String controllerId, String viewId, String contentType, Context context); }
apache-2.0
drewwills/confluence-portlet
WikiPortlet/src/main/java/edu/illinois/my/wiki/portlet/http/handler/WikiResponseReceiverFactoryImpl.java
1740
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * Jasig 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 edu.illinois.my.wiki.portlet.http.handler; import org.apache.http.client.ResponseHandler; import com.google.inject.Inject; import com.google.inject.Provider; import edu.illinois.my.names.Username; import edu.illinois.my.wiki.portlet.action.result.ActionResult; import edu.illinois.my.wiki.portlet.action.result.ListingResultFactory; import edu.illinois.my.wiki.services.streaming.ObjectStreamer; final class WikiResponseReceiverFactoryImpl implements WikiResponseReceiverFactory { private final Provider<ObjectStreamer> streamerProvider; @Inject WikiResponseReceiverFactoryImpl(Provider<ObjectStreamer> streamerProvider) { this.streamerProvider = streamerProvider; } @Override public ResponseHandler<ActionResult> create(Username username, ListingResultFactory listingResultFactory) { return new WikiResponseReceiver(username, listingResultFactory, streamerProvider.get()); } }
apache-2.0
opf-attic/ref
tools/fido/0.9.3/java/src/main/java/uk/gov/nationalarchives/pronom/ByteSequenceType.java
5761
package uk.gov.nationalarchives.pronom; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ByteSequenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ByteSequenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element name="SubSequence" type="{http://www.nationalarchives.gov.uk/pronom/SignatureFile}SubSequenceType"/> * &lt;/choice> * &lt;attribute name="Reference"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="BOFoffset"/> * &lt;enumeration value="EOFoffset"/> * &lt;enumeration value="IndirectBOFoffset"/> * &lt;enumeration value="IndirectEOFoffset"/> * &lt;enumeration value="NOoffset"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Endianness"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Big-endian"/> * &lt;enumeration value="Little-endian"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="IndirectOffsetLocation" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;attribute name="IndirectOffsetLength" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ByteSequenceType", propOrder = { "subSequence" }) public class ByteSequenceType { @XmlElement(name = "SubSequence") protected List<SubSequenceType> subSequence; @XmlAttribute(name = "Reference") protected String reference; @XmlAttribute(name = "Endianness") protected String endianness; @XmlAttribute(name = "IndirectOffsetLocation") @XmlSchemaType(name = "anySimpleType") protected String indirectOffsetLocation; @XmlAttribute(name = "IndirectOffsetLength") @XmlSchemaType(name = "anySimpleType") protected String indirectOffsetLength; /** * Gets the value of the subSequence property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the subSequence property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSubSequence().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SubSequenceType } * * */ public List<SubSequenceType> getSubSequence() { if (subSequence == null) { subSequence = new ArrayList<SubSequenceType>(); } return this.subSequence; } /** * Gets the value of the reference property. * * @return * possible object is * {@link String } * */ public String getReference() { return reference; } /** * Sets the value of the reference property. * * @param value * allowed object is * {@link String } * */ public void setReference(String value) { this.reference = value; } /** * Gets the value of the endianness property. * * @return * possible object is * {@link String } * */ public String getEndianness() { return endianness; } /** * Sets the value of the endianness property. * * @param value * allowed object is * {@link String } * */ public void setEndianness(String value) { this.endianness = value; } /** * Gets the value of the indirectOffsetLocation property. * * @return * possible object is * {@link String } * */ public String getIndirectOffsetLocation() { return indirectOffsetLocation; } /** * Sets the value of the indirectOffsetLocation property. * * @param value * allowed object is * {@link String } * */ public void setIndirectOffsetLocation(String value) { this.indirectOffsetLocation = value; } /** * Gets the value of the indirectOffsetLength property. * * @return * possible object is * {@link String } * */ public String getIndirectOffsetLength() { return indirectOffsetLength; } /** * Sets the value of the indirectOffsetLength property. * * @param value * allowed object is * {@link String } * */ public void setIndirectOffsetLength(String value) { this.indirectOffsetLength = value; } }
apache-2.0
consulo/consulo-python
python-impl/src/main/java/com/jetbrains/python/documentation/docstrings/TagBasedDocString.java
7384
/* * Copyright 2000-2014 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.jetbrains.python.documentation.docstrings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.Maps; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.jetbrains.python.psi.StructuredDocString; import com.jetbrains.python.toolbox.Substring; /** * @author yole */ public abstract class TagBasedDocString extends DocStringLineParser implements StructuredDocString { protected final String myDescription; protected final Map<String, Substring> mySimpleTagValues = Maps.newHashMap(); protected final Map<String, Map<Substring, Substring>> myArgTagValues = Maps.newHashMap(); private static final Pattern RE_STRICT_TAG_LINE = Pattern.compile("([a-z]+)(\\s+:class:[^:]*|[^:]*)\\s*:\\s*?(.*)"); private static final Pattern RE_LOOSE_TAG_LINE = Pattern.compile("([a-z]+)\\s+([a-zA-Z_0-9]*)\\s*:?\\s*?([^:]*)"); private static final Pattern RE_ARG_TYPE = Pattern.compile("(.*?)\\s+([a-zA-Z_0-9]+)"); public static String[] PARAM_TAGS = new String[]{ "param", "parameter", "arg", "argument" }; public static String[] PARAM_TYPE_TAGS = new String[]{"type"}; public static String[] VARIABLE_TAGS = new String[]{ "ivar", "cvar", "var" }; public static String[] RAISES_TAGS = new String[]{ "raises", "raise", "except", "exception" }; public static String[] RETURN_TAGS = new String[]{ "return", "returns" }; @Nonnull private final String myTagPrefix; public static String TYPE = "type"; protected TagBasedDocString(@Nonnull Substring docStringText, @Nonnull String tagPrefix) { super(docStringText); myTagPrefix = tagPrefix; final StringBuilder builder = new StringBuilder(); int lineno = 0; while(lineno < getLineCount()) { Substring line = getLine(lineno).trim(); if(line.startsWith(tagPrefix)) { lineno = parseTag(lineno, tagPrefix); } else { builder.append(line.toString()).append("\n"); } lineno++; } myDescription = builder.toString(); } public abstract List<String> getAdditionalTags(); @Nonnull @Override public String getDescription() { return myDescription; } @Override public String getSummary() { final List<String> strings = StringUtil.split(StringUtil.trimLeading(myDescription), "\n", true, false); if(strings.size() > 1) { if(strings.get(1).isEmpty()) { return strings.get(0); } } return ""; } @Nonnull private Map<Substring, Substring> getTagValuesMap(String key) { Map<Substring, Substring> map = myArgTagValues.get(key); if(map == null) { map = Maps.newLinkedHashMap(); myArgTagValues.put(key, map); } return map; } protected int parseTag(int lineno, String tagPrefix) { final Substring lineWithPrefix = getLine(lineno).trimLeft(); if(lineWithPrefix.startsWith(tagPrefix)) { final Substring line = lineWithPrefix.substring(tagPrefix.length()); final Matcher strictTagMatcher = RE_STRICT_TAG_LINE.matcher(line); final Matcher looseTagMatcher = RE_LOOSE_TAG_LINE.matcher(line); Matcher tagMatcher = null; if(strictTagMatcher.matches()) { tagMatcher = strictTagMatcher; } else if(looseTagMatcher.matches()) { tagMatcher = looseTagMatcher; } if(tagMatcher != null) { final Substring tagName = line.getMatcherGroup(tagMatcher, 1); final Substring argName = line.getMatcherGroup(tagMatcher, 2).trim(); final TextRange firstArgLineRange = line.getMatcherGroup(tagMatcher, 3).trim().getTextRange(); final int linesCount = getLineCount(); final int argStart = firstArgLineRange.getStartOffset(); int argEnd = firstArgLineRange.getEndOffset(); while(lineno + 1 < linesCount) { final Substring nextLine = getLine(lineno + 1).trim(); if(nextLine.isEmpty() || nextLine.startsWith(tagPrefix)) { break; } argEnd = nextLine.getTextRange().getEndOffset(); lineno++; } final Substring argValue = new Substring(argName.getSuperString(), argStart, argEnd); final String tagNameString = tagName.toString(); if(argName.isEmpty()) { mySimpleTagValues.put(tagNameString, argValue); } else { if("param".equals(tagNameString) || "parameter".equals(tagNameString) || "arg".equals(tagNameString) || "argument".equals(tagNameString)) { final Matcher argTypeMatcher = RE_ARG_TYPE.matcher(argName); if(argTypeMatcher.matches()) { final Substring type = argName.getMatcherGroup(argTypeMatcher, 1).trim(); final Substring arg = argName.getMatcherGroup(argTypeMatcher, 2); getTagValuesMap(TYPE).put(arg, type); } else { getTagValuesMap(tagNameString).put(argName, argValue); } } else { getTagValuesMap(tagNameString).put(argName, argValue); } } } } return lineno; } protected static List<String> toUniqueStrings(List<?> objects) { final List<String> result = new ArrayList<>(objects.size()); for(Object o : objects) { final String s = o.toString(); if(!result.contains(s)) { result.add(s); } } return result; } @Nullable public Substring getTagValue(String... tagNames) { for(String tagName : tagNames) { final Substring value = mySimpleTagValues.get(tagName); if(value != null) { return value; } } return null; } @Nullable public Substring getTagValue(String tagName, @Nonnull String argName) { final Map<Substring, Substring> argValues = myArgTagValues.get(tagName); return argValues != null ? argValues.get(new Substring(argName)) : null; } @Nullable public Substring getTagValue(String[] tagNames, @Nonnull String argName) { for(String tagName : tagNames) { Map<Substring, Substring> argValues = myArgTagValues.get(tagName); if(argValues != null) { return argValues.get(new Substring(argName)); } } return null; } public List<Substring> getTagArguments(String... tagNames) { for(String tagName : tagNames) { final Map<Substring, Substring> map = myArgTagValues.get(tagName); if(map != null) { return new ArrayList<>(map.keySet()); } } return Collections.emptyList(); } @Nonnull @Override public List<Substring> getParameterSubstrings() { final List<Substring> results = new ArrayList<>(); results.addAll(getTagArguments(PARAM_TAGS)); results.addAll(getTagArguments(PARAM_TYPE_TAGS)); return results; } @Override protected boolean isBlockEnd(int lineNum) { return getLine(lineNum).trimLeft().startsWith(myTagPrefix); } }
apache-2.0
m-m-m/util
collection/src/main/java/net/sf/mmm/util/collection/base/AbstractSortedMapFactory.java
943
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.collection.base; import java.util.SortedMap; import net.sf.mmm.util.collection.api.SortedMapFactory; /** * This is the abstract base implementation of the {@link SortedMapFactory} interface. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.1 */ @SuppressWarnings("rawtypes") public abstract class AbstractSortedMapFactory implements SortedMapFactory { /** * The constructor. */ public AbstractSortedMapFactory() { super(); } @Override public Class<SortedMap> getMapInterface() { return SortedMap.class; } @Override public SortedMap createGeneric() { return create(); } @Override public SortedMap createGeneric(int capacity) { return create(capacity); } }
apache-2.0
erdi/grails-core
grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/commons/GrailsClassTests.java
2404
/* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.commons; import groovy.lang.GroovyClassLoader; import junit.framework.TestCase; /** * @author Steven Devijver */ public class GrailsClassTests extends TestCase { public GrailsClassTests() { super(); } public GrailsClassTests(String name) { super(name); } public void testAbstractGrailsClassNoPackage() throws Exception { GroovyClassLoader cl = new GroovyClassLoader(); Class<?> clazz = cl.parseClass("class TestService { }"); GrailsClass grailsClass = new AbstractGrailsClass(clazz, "Service") {/*empty*/}; assertEquals("TestService", clazz.getName()); assertEquals("Test", grailsClass.getName()); assertEquals("TestService", grailsClass.getFullName()); assertNotNull(grailsClass.newInstance()); } public void testAbstractGrailsClassPackage() throws Exception { GroovyClassLoader cl = new GroovyClassLoader(); Class<?> clazz = cl.parseClass("package test.casey; class TestService { }"); GrailsClass grailsClass = new AbstractGrailsClass(clazz, "Service") {/*empty*/}; assertEquals("test.casey.TestService", clazz.getName()); assertEquals("Test", grailsClass.getName()); assertEquals("test.casey.TestService", grailsClass.getFullName()); assertNotNull(grailsClass.newInstance()); } public void testGrailsClassNonPublicConstructor() throws Exception { GroovyClassLoader cl = new GroovyClassLoader(); Class<?> clazz = cl.parseClass("class ProtectedConstructor { protected ProtectedConstructor() {}}"); GrailsClass grailsClass = new AbstractGrailsClass(clazz, "ProtectedConstructor") {/*empty*/}; assertNotNull(grailsClass.newInstance()); } }
apache-2.0
Jolicost/ChattyTpp
src/chatty/Usericon.java
16851
package chatty; import chatty.gui.HtmlColors; import chatty.util.ImageCache; import java.awt.Color; import java.awt.Graphics; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; import javax.swing.ImageIcon; /** * A single usericon (badge) with an image and information on where (channel) * and for who (user properties) it should be displayed. * * @author tduva */ public class Usericon implements Comparable { private static final Logger LOGGER = Logger.getLogger(Usericon.class.getName()); /** * How long to cache the usericon images (in seconds). */ private static final int CACHE_TIME = 60*60*24*3; private static final Set<String> statusDef = new HashSet<>(Arrays.asList( "$mod", "$sub", "$admin", "$staff", "$turbo", "$broadcaster", "$bot", "$globalmod", "$anymod")); /** * The type determines whether it should replace any of the default icons * (which also assumes they are mainly requested if the user is actually * mod, turbo, etc.) or if it should be shown in addition to the default * icons (addon). */ public enum Type { MOD(0, "Moderator", "MOD", HtmlColors.decode("#34ae0a")), TURBO(1, "Turbo", "TRB", HtmlColors.decode("#6441a5")), BROADCASTER(2, "Broadcaster", "BRC", HtmlColors.decode("#e71818")), STAFF(3, "Staff", "STA", HtmlColors.decode("#200f33")), ADMIN(4, "Admin", "ADM", HtmlColors.decode("#faaf19")), SUB(5, "Subscriber", "SUB", null), ADDON(6, "Addon", "ADD", null), GLOBAL_MOD(7, "Global Moderator", "GLM", HtmlColors.decode("#0c6f20")), BOT(8, "Bot", "BOT", null), UNDEFINED(-1, "Undefined", "UDF", null); public Color color; public String label; public String shortLabel; public int id; Type(int id, String label, String shortLabel, Color color) { this.color = color; this.label = label; this.shortLabel = shortLabel; this.id = id; } public static Type getTypeFromId(int typeId) { for (Type type : values()) { if (type.id == typeId) { return type; } } return UNDEFINED; } } /** * On creation the match type is determined, which means what type of * restriction is set. This is done for easier handling later, so the * restriction doesn't have to be parsed everytime. */ public enum MatchType { CATEGORY, UNDEFINED, ALL, STATUS, NAME, COLOR } /** * The type of icon based on the source. */ public static final int SOURCE_FALLBACK = 0; public static final int SOURCE_TWITCH = 5; public static final int SOURCE_FFZ = 10; public static final int SOURCE_CUSTOM = 20; /** * Fields directly saved from the constructor arguments (or only slightly * modified). */ /** * Which kind of icon (replacing mod, sub, turbo, .. or addon). */ public final Type type; /** * Where the icon comes from (Twitch, FFZ, Custom, ..). */ public final int source; /** * The channel restriction, which determines which channel(s) the icon * should be used for. This doesn't necessarily only contain the channel * itself, but possibly also modifiers. */ public final String channelRestriction; /** * The URL the image is loaded from */ public final URL url; /** * The restriction */ public final String restriction; /** * The filename of a locally loaded custom emoticon. This can be used to * more easily load/save that setting. */ public final String fileName; /** * Data that is derived from other fields and not directly saved from * constructor arguments. */ /** * The image loaded from the given {@literal url} */ public final ImageIcon image; /** * The match type is derived from {@literal id}, to make it easier to check * what to match later. */ public final MatchType matchType; /** * The addressbook category to match (if given) in {@literal id}. */ public final String category; /** * The actual channel from the channel restriction. If no or an invalid * channel is specified in the channel restriction, then this is empty. */ public final String channel; /** * This is {@code true} if the channel restriction should be reversed, which * means all channels BUT the one specified should match. */ public final boolean channelInverse; /** * Color restriction. Maybe be null. */ public final Color colorRestriction; public final String restrictionValue; public final boolean stop; public final boolean first; /** * Creates a new Icon from the Twitch API, which the appropriate default * values for the stuff that isn't specified in the arguments. * * @param type * @param channel * @param urlString * @return */ public static Usericon createTwitchIcon(Type type, String channel, String urlString) { //return createTwitchLikeIcon(type, channel, urlString, SOURCE_TWITCH); return createIconFromUrl(type, channel, urlString, SOURCE_TWITCH, null); } /** * Creates a new icon with the given values, with appropriate default values * for the stuff that isn't specified in the arguments. It determines the * background color based on the default Twitch settings, so it should only * be used for icons that should match that behaviour. * * @param type * @param channel * @param urlString * @param source * @return */ public static Usericon createTwitchLikeIcon(Type type, String channel, String urlString, int source) { return createIconFromUrl(type, channel, urlString, source, getColorFromType(type)); } public static Usericon createIconFromUrl(Type type, String channel, String urlString, int source, Color color) { try { URL url = new URL(Helper.checkHttpUrl(urlString)); Usericon icon = new Usericon(type, channel, url, color, source); return icon; } catch (MalformedURLException ex) { LOGGER.warning("Invalid icon url: " + urlString); } return null; } /** * Creates an icon based on a filename, which is resolved with the image * directory (if necessary). It also takes a restriction parameter and * stuff and sets the other values to appropriate values for custom icons. * * @param type * @param restriction * @param fileName * @param channel * @return */ public static Usericon createCustomIcon(Type type, String restriction, String fileName, String channel) { if (fileName == null) { return null; } try { URL url; if (fileName.startsWith("http")) { url = new URL(fileName); } else { Path path = Paths.get(Chatty.getImageDirectory()).resolve(Paths.get(fileName)); url = path.toUri().toURL(); } Usericon icon = new Usericon(type, channel, url, null, SOURCE_CUSTOM, restriction, fileName); return icon; } catch (MalformedURLException | InvalidPathException ex) { LOGGER.warning("Invalid icon file: " + fileName); } return null; } public static Usericon createFallbackIcon(Type type, URL url) { Usericon icon = new Usericon(type, null, url, getColorFromType(type), SOURCE_FALLBACK); return icon; } /** * Convenience constructor which simply omits the two arguments mainly used * for custom icons. * * @param type * @param channel * @param url * @param color * @param source */ public Usericon(Type type, String channel, URL url, Color color, int source) { this(type, channel, url, color, source, null, null); } /** * Creates a new {@literal Userimage}, which will try to load the image from * the given URL. If the loading fails, the {@literal image} field will be * {@literal null}. * * @param type The type of userimage (Addon, Mod, Sub, etc.) * @param channel The channelRestriction the image applies to * @param url The url to load the image from * @param color The color to use as background * @param source The source of the image (like Twitch, Custom, FFZ) * @param restriction Additional restrictions (like $mod, $sub, $cat) * @param fileName The name of the file to load the icon from (this is used * for further reference, probably only for custom icons) */ public Usericon(Type type, String channel, URL url, Color color, int source, String restriction, String fileName) { this.type = type; this.fileName = fileName; this.source = source; // Channel Restriction if (channel != null) { channel = channel.trim(); channelRestriction = channel; if (channel.startsWith("!")) { channelInverse = true; channel = channel.substring(1); } else { channelInverse = false; } } else { channelRestriction = ""; channelInverse = false; } channel = Helper.toValidChannel(channel); if (channel == null) { channel = ""; } this.channel = channel; this.url = url; if (fileName != null && fileName.startsWith("$")) { image = null; } else { image = addColor(getIcon(url), color); } // Restriction if (restriction != null) { restriction = restriction.trim(); this.restriction = restriction; if (restriction.contains("$stop")) { restriction = restriction.replace("$stop", "").trim(); stop = true; } else { stop = false; } if (restriction.contains("$first")) { restriction = restriction.replace("$first", "").trim(); first = true; } else { first = false; } restrictionValue = restriction; // Check if a category was specified as id if (restriction.startsWith("$cat:") && restriction.length() > 5) { category = restriction.substring(5); } else { category = null; } if (restriction.startsWith("#") && restriction.length() == 7) { colorRestriction = HtmlColors.decode(restriction, null); } else if (restriction.startsWith("$color:") && restriction.length() > 7) { colorRestriction = HtmlColors.decode(restriction.substring(7), null); } else { colorRestriction = null; } // Save the type if (restriction.startsWith("$cat:") && restriction.length() > 5) { matchType = MatchType.CATEGORY; } else if (colorRestriction != null) { matchType = MatchType.COLOR; } else if (statusDef.contains(restriction)) { matchType = MatchType.STATUS; } else if (Helper.validateStream(restriction)) { matchType = MatchType.NAME; } else if (restriction.equals("$all") || restriction.isEmpty()) { matchType = MatchType.ALL; } else { matchType = MatchType.UNDEFINED; } } else { matchType = MatchType.UNDEFINED; category = null; this.restriction = null; restrictionValue = null; colorRestriction = null; stop = false; first = false; } } /** * Loads the icon from the given url. * * @param url The URL to load the icon from * @return The loaded icon or {@literal null} if no URL was specified or the * icon couldn't be loaded */ private ImageIcon getIcon(URL url) { if (url == null) { return null; } //ImageIcon icon = new ImageIcon(url); //ImageIcon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(url)); ImageIcon icon = ImageCache.getImage(url, "usericon", CACHE_TIME); if (icon != null) { return icon; } else { LOGGER.warning("Could not load icon: " + url); } return null; } /** * Adds a background color to the given icon, if an icon and color is * actually given, otherwise the original icon is returned. * * @param icon * @param color * @return */ private ImageIcon addColor(ImageIcon icon, Color color) { if (icon == null || color == null) { return icon; } BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconWidth(), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.setColor(color); g.drawImage(icon.getImage(), 0, 0, color, null); g.dispose(); return new ImageIcon(image); } /** * Used for sorting the default icons in the {@code TreeSet}, which means no * two icons that should both appear in there at the same time can return 0, * because the {@code TreeSet} uses this to determine the order as well as * equality. * * @param o The object to compare this object against * @return */ @Override public int compareTo(Object o) { if (o instanceof Usericon) { Usericon icon = (Usericon)o; if (this.image == null && icon.image == null) { return 0; } else if (this.image == null) { return 1; } else if (icon.image == null) { return -1; } else if (icon.source > source) { return 1; } else if (icon.source < source) { return -1; } else if (icon.type != type) { return icon.type.compareTo(type); } else { return icon.channelRestriction.compareTo(channelRestriction); } } return 0; } @Override public String toString() { return typeToString(type)+"/"+source+"/"+channelRestriction+"/"+restriction+"("+(image != null ? "L" : "E")+")"; } public static String typeToString(Type type) { return type.shortLabel; // switch (type) { // case MOD: return "MOD"; // case ADDON: return "ADD"; // case ADMIN: return "ADM"; // case BROADCASTER: return "BRC"; // case STAFF: return "STA"; // case SUB: return "SUB"; // case TURBO: return "TRB"; // } // return "UDF"; } public static Color getColorFromType(Type type) { return type.color; // switch (type) { // case TYPE_MOD: // return TWITCH_MOD_COLOR; // case TYPE_TURBO: // return TWITCH_TURBO_COLOR; // case TYPE_ADMIN: // return TWITCH_ADMIN_COLOR; // case TYPE_BROADCASTER: // return TWITCH_BROADCASTER_COLOR; // case TYPE_STAFF: // return TWITCH_STAFF_COLOR; // } // return null; } }
apache-2.0
JuleStar/uima-tokens-regex
src/main/java/fr/univnantes/lina/uima/tkregex/model/matchers/CoveredTextStringArrayMatcher.java
674
package fr.univnantes.lina.uima.tkregex.model.matchers; import org.apache.uima.cas.text.AnnotationFS; import java.util.Set; public class CoveredTextStringArrayMatcher extends AbstractAnnotationMatcher { private StringArrayMatcherAspect stringArrayMatcherAspect; public CoveredTextStringArrayMatcher(Op operator, Set<String> values) { this.stringArrayMatcherAspect = new StringArrayMatcherAspect(operator, values); } @Override public boolean matches(AnnotationFS annotation) { return stringArrayMatcherAspect.doMatching(annotation.getCoveredText()); } public StringArrayMatcherAspect getStringArrayMatcherAspect() { return stringArrayMatcherAspect; } }
apache-2.0
faisal-hameed/java-code-bank
habsoft.j2se/habsoft.j2se.datetime/src/main/java/habsoft/j2se/datetime/Java8DateTest.java
1292
package habsoft.j2se.datetime; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Java8DateTest { public static void main(String[] args) { // Print current Date LocalDate cd = LocalDate.now(); System.out.println("Current Date : " + cd); // Yesterday date System.out.println(cd.plusDays(-1)); // Date from values LocalDate dob = LocalDate.of(1990, 1, 1); System.out.println("My DOB : " + dob); // Day System.out.println(dob.getDayOfWeek()); // Date from String String date = "2016-07-01"; DateTimeFormatter fm = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate pd = LocalDate.parse(date, fm); System.out.println("Parsed date : " + pd); // GMT date LocalDate gmt = LocalDate.now(ZoneId.of("GMT+0")); System.out.println("GMT date : " + gmt); // Date after 3 months LocalDate d3m = LocalDate.now().plus(3, ChronoUnit.MONTHS); System.out.println("Date after 3 months : " + d3m); Period d = Period.between(gmt, dob); System.out.println("My age till today : " + d); } }
apache-2.0
cloudbees/groovy-cps
lib/src/main/java/com/cloudbees/groovy/cps/impl/AssignmentBlock.java
2955
package com.cloudbees.groovy.cps.impl; import com.cloudbees.groovy.cps.Block; import com.cloudbees.groovy.cps.Continuation; import com.cloudbees.groovy.cps.Env; import com.cloudbees.groovy.cps.LValue; import com.cloudbees.groovy.cps.LValueBlock; import com.cloudbees.groovy.cps.Next; import com.cloudbees.groovy.cps.sandbox.CallSiteTag; import java.util.Collection; /** * Assignment operator {@code exp=rhs} * * TODO: tuple assignment * * @author Kohsuke Kawaguchi */ public class AssignmentBlock extends CallSiteBlockSupport { private final Block lhsExp,rhsExp; /** * For compound assignment operator (such as ^=), set the operator method here. */ private final String compoundOp; private final SourceLocation loc; public AssignmentBlock(SourceLocation loc, Collection<CallSiteTag> tags, LValueBlock lhsExp, Block rhsExp, String compoundOp) { super(tags); this.loc = loc; this.compoundOp = compoundOp; this.lhsExp = lhsExp.asLValue(); this.rhsExp = rhsExp; } public Next eval(Env e, Continuation k) { return new ContinuationImpl(e,k).then(lhsExp,e,fixLhs); } class ContinuationImpl extends ContinuationGroup { final Continuation k; final Env e; LValue lhs; Object rhs,cur; ContinuationImpl(Env e, Continuation k) { this.e = e; this.k = k; } /** * Computes {@link LValue} */ public Next fixLhs(Object lhs) { this.lhs = (LValue)lhs; if (compoundOp==null) return then(rhsExp,e,assignAndDone); else return ((LValue) lhs).get(fixCur.bind(this)); } /** * Just straight assignment from RHS to LHS, then done */ public Next assignAndDone(Object rhs) { return lhs.set(rhs,k); // just straight assignment } /** * Computed the current value of {@link LValue} for compound assignment. * Evaluate rhs. */ public Next fixCur(Object cur) { this.cur = cur; return then(rhsExp,e,fixRhs); } /** * Evaluated rhs. * Invoke the operator */ public Next fixRhs(Object rhs) { return methodCall(e, loc, assignAndDone, AssignmentBlock.this, this.cur, compoundOp, rhs); } private static final long serialVersionUID = 1L; } static final ContinuationPtr fixLhs = new ContinuationPtr(ContinuationImpl.class,"fixLhs"); static final ContinuationPtr assignAndDone = new ContinuationPtr(ContinuationImpl.class,"assignAndDone"); static final ContinuationPtr fixCur = new ContinuationPtr(ContinuationImpl.class,"fixCur"); static final ContinuationPtr fixRhs = new ContinuationPtr(ContinuationImpl.class,"fixRhs"); private static final long serialVersionUID = 1L; }
apache-2.0
azuki-framework/azuki-crawler
src/main/java/org/azkfw/crawler/schedule/DatetimeSchedule.java
3234
/** * 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.azkfw.crawler.schedule; import java.util.Calendar; import java.util.Date; import org.azkfw.crawler.matcher.DateTimeMatcher; import org.azkfw.parameter.Parameter; /** * このクラスは、指定時間に実行を行うスケジュールクラスです。 * * <p> * パラメータ一覧 * <ul> * <li>pattern - 指定時間(default:*&frasl;10 * * * *)</li> * </ul> * </p> * <p> * パターンサンプル * <ul> * <li>*&frasl;10 * * * * - 10分間隔に実行する</li> * <li>10 0 * * * - 毎日0時10分に実行する</li> * <li>10 0 1 * * - 毎月1日0時10分に実行する</li> * <li>10 0 1 12 * - 毎年12月1日0時10分に実行する</li> * <li>10 0 * * 1 - 毎週月曜0時10分に実行する</li> * </ul> * </p> * * @since 1.0.0 * @version 1.0.0 2014/05/12 * @author Kawakicchi */ public class DatetimeSchedule extends AbstractCrawlerSchedule { private String pattern; private DateTimeMatcher matcher; private String lastMatchString; @Override protected void doSetup() { Parameter p = getParameter(); pattern = p.getString("pattern", "*/10 * * * *"); matcher = new DateTimeMatcher(); matcher.compile(pattern); } @Override protected void doInitialize() { } @Override protected void doRelease() { } @Override public String getOutline() { StringBuilder s = new StringBuilder(); s.append(String.format("日付が「%s」に一致する時実行", pattern)); return s.toString(); } @Override public boolean check() { Calendar cln = Calendar.getInstance(); cln.setTime(new Date()); String str = String.format("%d %d %d %d %d", cln.get(Calendar.MINUTE), cln.get(Calendar.HOUR_OF_DAY), cln.get(Calendar.DAY_OF_MONTH), cln.get(Calendar.MONTH) + 1, cln.get(Calendar.DAY_OF_WEEK)); if (matcher.match(str)) { String matchString = matcher.getMatchString(str); if (null == matchString) { return false; } else if (matchString.equals(lastMatchString)) { return false; } else { info("match " + matchString); lastMatchString = matchString; return true; } } else { return false; } } @Override public boolean isStop() { return false; } @Override public boolean isRun() { return true; } public void sleep() throws InterruptedException { Thread.sleep(1000); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/EbsVolume.java
5495
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticmapreduce.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * EBS block device that's attached to an EC2 instance. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/EbsVolume" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EbsVolume implements Serializable, Cloneable, StructuredPojo { /** * <p> * The device name that is exposed to the instance, such as /dev/sdh. * </p> */ private String device; /** * <p> * The volume identifier of the EBS volume. * </p> */ private String volumeId; /** * <p> * The device name that is exposed to the instance, such as /dev/sdh. * </p> * * @param device * The device name that is exposed to the instance, such as /dev/sdh. */ public void setDevice(String device) { this.device = device; } /** * <p> * The device name that is exposed to the instance, such as /dev/sdh. * </p> * * @return The device name that is exposed to the instance, such as /dev/sdh. */ public String getDevice() { return this.device; } /** * <p> * The device name that is exposed to the instance, such as /dev/sdh. * </p> * * @param device * The device name that is exposed to the instance, such as /dev/sdh. * @return Returns a reference to this object so that method calls can be chained together. */ public EbsVolume withDevice(String device) { setDevice(device); return this; } /** * <p> * The volume identifier of the EBS volume. * </p> * * @param volumeId * The volume identifier of the EBS volume. */ public void setVolumeId(String volumeId) { this.volumeId = volumeId; } /** * <p> * The volume identifier of the EBS volume. * </p> * * @return The volume identifier of the EBS volume. */ public String getVolumeId() { return this.volumeId; } /** * <p> * The volume identifier of the EBS volume. * </p> * * @param volumeId * The volume identifier of the EBS volume. * @return Returns a reference to this object so that method calls can be chained together. */ public EbsVolume withVolumeId(String volumeId) { setVolumeId(volumeId); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDevice() != null) sb.append("Device: ").append(getDevice()).append(","); if (getVolumeId() != null) sb.append("VolumeId: ").append(getVolumeId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof EbsVolume == false) return false; EbsVolume other = (EbsVolume) obj; if (other.getDevice() == null ^ this.getDevice() == null) return false; if (other.getDevice() != null && other.getDevice().equals(this.getDevice()) == false) return false; if (other.getVolumeId() == null ^ this.getVolumeId() == null) return false; if (other.getVolumeId() != null && other.getVolumeId().equals(this.getVolumeId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDevice() == null) ? 0 : getDevice().hashCode()); hashCode = prime * hashCode + ((getVolumeId() == null) ? 0 : getVolumeId().hashCode()); return hashCode; } @Override public EbsVolume clone() { try { return (EbsVolume) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.elasticmapreduce.model.transform.EbsVolumeMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
blackcathacker/kc.preclean
coeus-it/src/test/java/org/kuali/kra/irb/protocol/funding/ProtocolFundingSourceServiceTest.java
36520
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * 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.kuali.kra.irb.protocol.funding; import org.apache.commons.lang3.StringUtils; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.concurrent.Synchroniser; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.matchers.JUnitMatchers; import org.kuali.coeus.common.api.sponsor.SponsorContract; import org.kuali.coeus.common.api.sponsor.SponsorService; import org.kuali.coeus.common.framework.sponsor.Sponsor; import org.kuali.coeus.common.framework.unit.UnitService; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.AwardService; import org.kuali.kra.bo.FundingSourceType; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.institutionalproposal.home.InstitutionalProposal; import org.kuali.kra.institutionalproposal.service.InstitutionalProposalService; import org.kuali.kra.irb.ProtocolDocument; import org.kuali.coeus.propdev.impl.core.DevelopmentProposal; import org.kuali.kra.service.FundingSourceTypeService; import org.kuali.kra.test.infrastructure.KcIntegrationTestBase; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.KRADConstants; import java.util.Collections; import java.util.Map.Entry; import static org.junit.Assert.*; /** * The JUnit test class for <code>{@link ProtocolFundingSourceServiceImpl}</code> * * @author Kuali Research Administration Team (kualidev@oncourse.iu.edu) */ public class ProtocolFundingSourceServiceTest extends KcIntegrationTestBase { private Mockery context = new JUnit4Mockery() {{ setThreadingPolicy(new Synchroniser()); }}; private ProtocolFundingSourceServiceImpl protocolFundingSourceService; private static final String EMPTY_NUMBER = ""; private static final String SPONSOR_NUMBER_BAD = "-1"; private SponsorContract sponsorGood; private static final String SPONSOR_NUMBER_AIR_FORCE = "000108"; private String sponsorNameAirForce; private static final String UNIT_NUMBER_GOOD = "000001"; private static final String UNIT_NAME_GOOD = "University"; private static final String UNIT_NUMBER_BAD = "zzzzz"; private static final String OTHER_NUMBER_GOOD = "otherId"; private static final String OTHER_NAME_GOOD = "otherName"; private static final String DEV_PROPOSAL_NUMBER_GOOD = "1"; private static final String DEV_PROPOSAL_TITLE_GOOD = "DevPropTitle"; private static final String DEV_PROPOSAL_NUMBER_BAD = "zzzzz"; private DevelopmentProposal devProposalGood; private static final String INST_PROPOSAL_NUMBER_GOOD = "00000001"; private static final String INST_PROPOSAL_TITLE_GOOD = "Institutional Proposal Title"; private static final String INST_PROPOSAL_NUMBER_BAD = "zzzzzzzz"; private InstitutionalProposal instProposalGood; private static final String AWARD_NUMBER_GOOD = "000001-00001"; private static final String AWARD_TITLE_GOOD = "AwardTitle"; private static final String AWARD_NUMBER_BAD = "zzzzzz-zzzzz"; private Award awardGood; private static final String SPONSOR_SOURCE_TYPE_ID = "1"; private static final String UNIT_SOURCE_TYPE_ID = "2"; private static final String OTHER_SOURCE_TYPE_ID = "3"; private static final String DEVELOPMENT_PROP_SOURCE_TYPE_ID = "4"; private static final String INSTITUTE_PROP_SOURCE_TYPE_ID = "5"; private static final String AWARD_SOURCE_TYPE_ID = "6"; private static final String PROTOCOL_FUNDING_SOURCE = "protocolHelper.newFundingSource.fundingSource"; private static final String PROTOCOL_FUNDING_SOURCE_NUMBER = "protocolHelper.newFundingSource.fundingSourceNumber"; private static final String PROTOCOL_FUNDING_SOURCE_NAME = "protocolHelper.newFundingSource.fundingSourceName"; private static final String PROTOCOL_FUNDING_SOURCE_TITLE = "protocolHelper.newFundingSource.fundingSourceTitle"; private FundingSourceType fundingSponsorSourceType; private FundingSourceType fundingUnitSourceType; private FundingSourceType fundingOtherSourceType; private FundingSourceType fundingDevProposalSourceType; private FundingSourceType fundingInstProposalSourceType; private FundingSourceType fundingAwardSourceType; /** * Create the mock services and insert them into the protocol auth service. * */ @Before public void setUp() throws Exception { fundingSponsorSourceType = new FundingSourceType(); fundingSponsorSourceType.setFundingSourceTypeCode(FundingSourceType.SPONSOR); fundingSponsorSourceType.setFundingSourceTypeFlag(true); fundingSponsorSourceType.setDescription("Sponsor"); fundingUnitSourceType = new FundingSourceType(); fundingUnitSourceType.setFundingSourceTypeCode(FundingSourceType.UNIT); fundingUnitSourceType.setFundingSourceTypeFlag(true); fundingUnitSourceType.setDescription("Unit"); fundingOtherSourceType= new FundingSourceType(); fundingOtherSourceType.setFundingSourceTypeCode(FundingSourceType.OTHER); fundingOtherSourceType.setFundingSourceTypeFlag(true); fundingOtherSourceType.setDescription("Other"); fundingDevProposalSourceType= new FundingSourceType(); fundingDevProposalSourceType.setFundingSourceTypeCode(FundingSourceType.PROPOSAL_DEVELOPMENT); fundingDevProposalSourceType.setFundingSourceTypeFlag(true); fundingDevProposalSourceType.setDescription("Proposal Development"); fundingInstProposalSourceType= new FundingSourceType(); fundingInstProposalSourceType.setFundingSourceTypeCode(FundingSourceType.INSTITUTIONAL_PROPOSAL); fundingInstProposalSourceType.setFundingSourceTypeFlag(true); fundingInstProposalSourceType.setDescription("Institutional Proposal"); fundingAwardSourceType= new FundingSourceType(); fundingAwardSourceType.setFundingSourceTypeCode(FundingSourceType.AWARD); fundingAwardSourceType.setFundingSourceTypeFlag(true); fundingAwardSourceType.setDescription("Award"); //sponsorGood = new Sponsor(); //sponsorGood.setSponsorName(sponsorNameAirForce); //sponsorGood.setSponsorCode(SPONSOR_NUMBER_AIR_FORCE); sponsorGood = KcServiceLocator.getService(SponsorService.class).getSponsor(SPONSOR_NUMBER_AIR_FORCE); sponsorNameAirForce = sponsorGood.getSponsorName(); devProposalGood = new DevelopmentProposal(); devProposalGood.setTitle(DEV_PROPOSAL_TITLE_GOOD); devProposalGood.setSponsorCode(sponsorGood.getSponsorCode()); instProposalGood = new InstitutionalProposal(); instProposalGood.setTitle(INST_PROPOSAL_TITLE_GOOD); instProposalGood.setSponsorCode(sponsorGood.getSponsorCode()); awardGood = new Award(); awardGood.setTitle(AWARD_TITLE_GOOD); awardGood.setSponsorCode(sponsorGood.getSponsorCode()); } @Test public void testCalculateSponsorFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setSponsorService(getSponsorService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(SPONSOR_SOURCE_TYPE_ID, SPONSOR_NUMBER_AIR_FORCE, null); assertNotNull(fundingSource); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); } @Test public void testCalculateSponsorFundingSourceBadId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setSponsorService(getSponsorService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(SPONSOR_SOURCE_TYPE_ID, SPONSOR_NUMBER_BAD, null); assertNotNull(fundingSource); assertNull(fundingSource.getFundingSourceName()); } @Test public void testCalculateSponsorFundingSourceEmptyId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setSponsorService(getSponsorService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(SPONSOR_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testCalculateUnitFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setUnitService(getUnitService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(UNIT_SOURCE_TYPE_ID, UNIT_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(UNIT_NAME_GOOD)); } @Test public void testCalculateUnitFundingSourceBadId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setUnitService(getUnitService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(UNIT_SOURCE_TYPE_ID, UNIT_NUMBER_BAD, null); assertNotNull(fundingSource); assertNull(fundingSource.getFundingSourceName()); } @Test public void testCalculateUnitFundingSourceEmptyId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); final UnitService unitService = context.mock(UnitService.class); protocolFundingSourceService.setUnitService(unitService); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(UNIT_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testCalculateOtherFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(OTHER_SOURCE_TYPE_ID, OTHER_NUMBER_GOOD, OTHER_NAME_GOOD); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(OTHER_NAME_GOOD)); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceTitle())); } @Test public void testCalculateOtherFundingEmptyId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(OTHER_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testCalculateDevProposalFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(DEVELOPMENT_PROP_SOURCE_TYPE_ID, DEV_PROPOSAL_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); assertTrue(fundingSource.getFundingSourceTitle().equalsIgnoreCase(DEV_PROPOSAL_TITLE_GOOD)); } @Test public void testCalculateDevProposalFundingBadID() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(DEVELOPMENT_PROP_SOURCE_TYPE_ID, DEV_PROPOSAL_NUMBER_BAD, null); assertNotNull(fundingSource); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceName())); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceTitle())); } @Test public void testCalculateDevProposalFundingNegativeEmptyID() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(DEVELOPMENT_PROP_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testCalculateInstProposalFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setInstitutionalProposalService(getInstProposalService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(INSTITUTE_PROP_SOURCE_TYPE_ID, INST_PROPOSAL_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); assertTrue(fundingSource.getFundingSourceTitle().equalsIgnoreCase(INST_PROPOSAL_TITLE_GOOD)); } @Test public void testCalculateInstProposalFundingBadIdGoodNumber() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setInstitutionalProposalService(getInstProposalService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(INSTITUTE_PROP_SOURCE_TYPE_ID, INST_PROPOSAL_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); assertTrue(fundingSource.getFundingSourceTitle().equalsIgnoreCase(INST_PROPOSAL_TITLE_GOOD)); } @Test public void testCalculateInstProposalFundingBadIdBadNumber() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setInstitutionalProposalService(getInstProposalService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(INSTITUTE_PROP_SOURCE_TYPE_ID, INST_PROPOSAL_NUMBER_BAD, null); assertNotNull(fundingSource); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceName())); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceTitle())); } @Test public void testCalculateInstProposalFundingNegativeEmpty() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); protocolFundingSourceService.setInstitutionalProposalService(getInstProposalService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setBusinessObjectService(getBusinessObjectService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(INSTITUTE_PROP_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testCalculateAwardFunding() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setAwardService(getAwardService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setParameterService(getParameterService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(AWARD_SOURCE_TYPE_ID, AWARD_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); assertTrue(fundingSource.getFundingSourceTitle().equalsIgnoreCase(AWARD_TITLE_GOOD)); } @Test public void testCalculateAwardFundingBadIdGoodNumber() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setAwardService(getAwardService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setParameterService(getParameterService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(AWARD_SOURCE_TYPE_ID, AWARD_NUMBER_GOOD, null); assertNotNull(fundingSource); assertNotNull(fundingSource.getFundingSourceName()); assertTrue(fundingSource.getFundingSourceName().equalsIgnoreCase(sponsorNameAirForce)); assertTrue(fundingSource.getFundingSourceTitle().equalsIgnoreCase(AWARD_TITLE_GOOD)); } @Test public void testCalculateAwardFundingBadIdBadNumber() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setAwardService(getAwardService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setParameterService(getParameterService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(AWARD_SOURCE_TYPE_ID, AWARD_NUMBER_BAD, null); assertNotNull(fundingSource); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceName())); assertTrue(StringUtils.isEmpty(fundingSource.getFundingSourceTitle())); } @Test public void testCalculateAwardFundingEmptyId() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setAwardService(getAwardService()); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setParameterService(getParameterService()); ProtocolFundingSource fundingSource = (ProtocolFundingSource) protocolFundingSourceService.updateProtocolFundingSource(AWARD_SOURCE_TYPE_ID, EMPTY_NUMBER, null); assertNull(fundingSource); } @Test public void testIsValidIdForTypeSponsor() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setSponsorService(getSponsorService()); ProtocolFundingSource fundingSource = new ProtocolFundingSource(SPONSOR_NUMBER_AIR_FORCE, FundingSourceType.SPONSOR, null, null); assertTrue(protocolFundingSourceService.isValidIdForType(fundingSource)); fundingSource = new ProtocolFundingSource(SPONSOR_NUMBER_BAD, FundingSourceType.SPONSOR, null, null); assertFalse(protocolFundingSourceService.isValidIdForType(fundingSource)); } @Test public void testIsValidIdForTypeUnit() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setUnitService(getUnitService()); ProtocolFundingSource fundingSource = new ProtocolFundingSource(UNIT_NUMBER_GOOD, FundingSourceType.UNIT, null, null); assertTrue(protocolFundingSourceService.isValidIdForType(fundingSource)); fundingSource = new ProtocolFundingSource(UNIT_NUMBER_BAD, FundingSourceType.UNIT, null, null); assertFalse(protocolFundingSourceService.isValidIdForType(fundingSource)); } @Test public void testIsValidIdForTypeOther() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); ProtocolFundingSource fundingSource = new ProtocolFundingSource(OTHER_SOURCE_TYPE_ID, FundingSourceType.OTHER, "otherName", null); assertTrue(protocolFundingSourceService.isValidIdForType(fundingSource)); fundingSource = new ProtocolFundingSource(OTHER_SOURCE_TYPE_ID, FundingSourceType.OTHER, EMPTY_NUMBER, null); assertTrue(protocolFundingSourceService.isValidIdForType(fundingSource)); } @Test public void testIsValidIdForTypeAward() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setFundingSourceTypeService(getFundingSourceTypeService()); protocolFundingSourceService.setAwardService(getAwardService()); protocolFundingSourceService.setParameterService(getParameterService()); ProtocolFundingSource fundingSource = new ProtocolFundingSource(AWARD_NUMBER_GOOD, FundingSourceType.AWARD, null, null); assertTrue(protocolFundingSourceService.isValidIdForType(fundingSource)); fundingSource = new ProtocolFundingSource(AWARD_NUMBER_BAD, FundingSourceType.AWARD, null, null); assertFalse(protocolFundingSourceService.isValidIdForType(fundingSource)); } @Test public void testGetLookupParameters() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); StringBuilder builder = new StringBuilder(); Entry<String, String> entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.SPONSOR); Assert.assertNotNull(entry); builder.append("sponsorCode:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.UNIT); Assert.assertNotNull(entry); builder.append("unitNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("unitName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.PROPOSAL_DEVELOPMENT); Assert.assertNotNull(entry); builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.INSTITUTIONAL_PROPOSAL); Assert.assertNotNull(entry); builder.append("proposalId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA); builder.append("proposalNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); builder.delete(0, builder.length()); entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.AWARD); Assert.assertNotNull(entry); builder.append("awardId:" + PROTOCOL_FUNDING_SOURCE + Constants.COMMA); builder.append("awardNumber:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsor.sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME + Constants.COMMA); builder.append("title:" + PROTOCOL_FUNDING_SOURCE_TITLE); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); try { entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.OTHER); fail("IllegalArgumentException was not thrown for invalid test case using OTHER"); } catch (IllegalArgumentException e) { //yup } } @Test public void testUpdateLookupParameter() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); Entry<String, String> entry = protocolFundingSourceService.getLookupParameters(FundingSourceType.SPONSOR); Assert.assertNotNull(entry); String fieldConversions = entry.getValue(); StringBuilder builder = new StringBuilder(); builder.append("sponsorCode:" + PROTOCOL_FUNDING_SOURCE_NUMBER + Constants.COMMA); builder.append("sponsorName:" + PROTOCOL_FUNDING_SOURCE_NAME); Assert.assertThat(entry.getValue(), JUnitMatchers.containsString(builder.toString())); String parameter = KRADConstants.METHOD_TO_CALL_BOPARM_LEFT_DEL + KRADConstants.METHOD_TO_CALL_BOPARM_RIGHT_DEL + KRADConstants.METHOD_TO_CALL_PARM1_LEFT_DEL + KRADConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL; String updatedParam = protocolFundingSourceService.updateLookupParameter(parameter, Sponsor.class.getName(), fieldConversions); Assert.assertThat(updatedParam, JUnitMatchers.containsString("(!!" + Sponsor.class.getName() + "!!)(((" + builder.toString() + ")))")); } @Test public void testIsLookupableFundingSource() throws Exception { String badFundingTypeCode = "-99"; protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); assertFalse(protocolFundingSourceService.isLookupable(FundingSourceType.OTHER)); assertFalse(protocolFundingSourceService.isLookupable(badFundingTypeCode)); assertTrue(protocolFundingSourceService.isLookupable(FundingSourceType.INSTITUTIONAL_PROPOSAL)); assertTrue(protocolFundingSourceService.isLookupable(FundingSourceType.UNIT)); assertTrue(protocolFundingSourceService.isLookupable(FundingSourceType.SPONSOR)); assertTrue(protocolFundingSourceService.isLookupable(FundingSourceType.AWARD)); assertTrue(protocolFundingSourceService.isLookupable(FundingSourceType.PROPOSAL_DEVELOPMENT)); } @Test public void testUpdateSourceNameEditable() throws Exception { protocolFundingSourceService = new ProtocolFundingSourceServiceImpl(); protocolFundingSourceService.setParameterService(getParameterService()); assertFalse(protocolFundingSourceService.isEditable(FundingSourceType.INSTITUTIONAL_PROPOSAL)); assertTrue(protocolFundingSourceService.isEditable(FundingSourceType.OTHER)); assertFalse(protocolFundingSourceService.isEditable(FundingSourceType.AWARD)); assertFalse(protocolFundingSourceService.isEditable(FundingSourceType.PROPOSAL_DEVELOPMENT)); assertFalse(protocolFundingSourceService.isEditable(FundingSourceType.SPONSOR)); assertFalse(protocolFundingSourceService.isEditable(FundingSourceType.UNIT)); } protected SponsorService getSponsorService() { final SponsorService sponsorService = context.mock(SponsorService.class); context.checking(new Expectations() {{ allowing(sponsorService).getSponsorName(SPONSOR_NUMBER_AIR_FORCE); will(returnValue(sponsorNameAirForce)); allowing(sponsorService).getSponsorName(SPONSOR_NUMBER_BAD); will(returnValue(null)); }}); return sponsorService; } protected UnitService getUnitService() { final UnitService unitService = context.mock(UnitService.class); context.checking(new Expectations() {{ allowing(unitService).getUnitName(UNIT_NUMBER_GOOD); will(returnValue(UNIT_NAME_GOOD)); allowing(unitService).getUnitName(UNIT_NUMBER_BAD); will(returnValue(null)); }}); return unitService; } protected BusinessObjectService getBusinessObjectService() { final BusinessObjectService businessObjectService = context.mock(BusinessObjectService.class); context.checking(new Expectations() {{ allowing(businessObjectService).findBySinglePrimaryKey(DevelopmentProposal.class, DEV_PROPOSAL_NUMBER_GOOD); will(returnValue(devProposalGood)); allowing(businessObjectService).findBySinglePrimaryKey(DevelopmentProposal.class, DEV_PROPOSAL_NUMBER_BAD); will(returnValue(null)); }}); return businessObjectService; } protected InstitutionalProposalService getInstProposalService() { final InstitutionalProposalService institutionalProposalService = context.mock(InstitutionalProposalService.class); context.checking(new Expectations() {{ allowing(institutionalProposalService).getActiveInstitutionalProposalVersion(INST_PROPOSAL_NUMBER_GOOD); will(returnValue(instProposalGood)); allowing(institutionalProposalService).getActiveInstitutionalProposalVersion(INST_PROPOSAL_NUMBER_BAD); will(returnValue(null)); allowing(institutionalProposalService).getPendingInstitutionalProposalVersion(INST_PROPOSAL_NUMBER_GOOD); will(returnValue(instProposalGood)); allowing(institutionalProposalService).getPendingInstitutionalProposalVersion(INST_PROPOSAL_NUMBER_BAD); will(returnValue(null)); }}); return institutionalProposalService; } protected AwardService getAwardService() { final AwardService awardService = context.mock(AwardService.class); context.checking(new Expectations() {{ allowing(awardService).findAwardsForAwardNumber(AWARD_NUMBER_GOOD); will(returnValue(Collections.singletonList(awardGood))); allowing(awardService).findAwardsForAwardNumber(AWARD_NUMBER_BAD); will(returnValue(Collections.emptyList())); }}); return awardService; } @SuppressWarnings("unchecked") protected ParameterService getParameterService() { final ParameterService parameterService = context.mock(ParameterService.class); context.checking(new Expectations() {{ allowing(parameterService).parameterExists(with(any(Class.class)), with(any(String.class))); will(returnValue(true)); allowing(parameterService).getParameterValueAsBoolean( ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_AWARD_LINK ); will(returnValue(true)); allowing(parameterService).getParameterValueAsBoolean(ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_DEV_PROPOSAL_LINK ); will(returnValue(true)); allowing(parameterService).getParameterValueAsBoolean(ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_PROPOSAL_LINK ); will(returnValue(true)); }}); return parameterService; } protected FundingSourceTypeService getFundingSourceTypeService() { final FundingSourceTypeService service = context.mock(FundingSourceTypeService.class); context.checking(new Expectations() {{ allowing(service).getFundingSourceType(SPONSOR_SOURCE_TYPE_ID); will(returnValue(fundingSponsorSourceType)); allowing(service).getFundingSourceType(UNIT_SOURCE_TYPE_ID); will(returnValue(fundingUnitSourceType)); allowing(service).getFundingSourceType(OTHER_SOURCE_TYPE_ID); will(returnValue(fundingOtherSourceType)); allowing(service).getFundingSourceType(DEVELOPMENT_PROP_SOURCE_TYPE_ID); will(returnValue(fundingDevProposalSourceType)); allowing(service).getFundingSourceType(INSTITUTE_PROP_SOURCE_TYPE_ID); will(returnValue(fundingInstProposalSourceType)); allowing(service).getFundingSourceType(AWARD_SOURCE_TYPE_ID); will(returnValue(fundingAwardSourceType)); }}); return service; } }
apache-2.0
consulo/consulo-android
android/android/src/com/android/tools/idea/gradle/project/compatibility/BuildFileComponentVersionReader.java
4094
/* * 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.android.tools.idea.gradle.project.compatibility; import com.android.tools.idea.gradle.facet.AndroidGradleFacet; import com.android.tools.idea.gradle.parser.BuildFileKey; import com.android.tools.idea.gradle.parser.GradleBuildFile; import com.android.tools.idea.gradle.service.notification.hyperlink.NotificationHyperlink; import com.google.common.base.Splitter; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.pom.Navigatable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; /** * Obtains the version for a component from a build.gradle file, given the component name (e.g. "buildToolsVersion".) */ class BuildFileComponentVersionReader implements ComponentVersionReader { @NotNull private final String myComponentName; @Nullable private final BuildFileKey myKey; BuildFileComponentVersionReader(@NotNull String keyPath) { List<String> segments = Splitter.on('/').splitToList(keyPath); myComponentName = segments.get(segments.size() - 1); myKey = BuildFileKey.findByPath(keyPath); } @Override public boolean appliesTo(@NotNull Module module) { return AndroidGradleFacet.getInstance(module) != null && GradleBuildFile.get(module) != null; } @Override @Nullable public String getComponentVersion(@NotNull Module module) { GradleBuildFile buildFile = GradleBuildFile.get(module); if (buildFile != null && myKey != null) { Object value = buildFile.getValue(myKey); if (value != null) { return value.toString(); } } return null; } @Override @Nullable public FileLocation getVersionSource(@NotNull Module module) { GradleBuildFile buildFile = GradleBuildFile.get(module); if (buildFile != null) { return new FileLocation(buildFile.getFile()); } return null; } @Override @NotNull public List<NotificationHyperlink> getQuickFixes(@NotNull Module module, @Nullable VersionRange expectedVersion, @Nullable FileLocation location) { FileLocation source = location; if (source == null) { source = getVersionSource(module); } if (source != null) { NotificationHyperlink quickFix = new OpenBuildFileHyperlink(module, source); return singletonList(quickFix); } return emptyList(); } @Override public boolean isProjectLevel() { return false; } @Override @NotNull public String getComponentName() { return "'" + myComponentName + "'"; } private static class OpenBuildFileHyperlink extends NotificationHyperlink { @NotNull private final FileLocation myFileLocation; OpenBuildFileHyperlink(@NotNull Module module, @NotNull FileLocation fileLocation) { super("openFile", String.format("Open build.gradle file in module '%1$s'", module.getName())); myFileLocation = fileLocation; } @Override protected void execute(@NotNull Project project) { Navigatable openFile = new OpenFileDescriptor(project, myFileLocation.file, myFileLocation.lineNumber, myFileLocation.column, false); if (openFile.canNavigate()) { openFile.navigate(true); } } } }
apache-2.0
apache/velocity-engine
velocity-engine-core/src/test/java/org/apache/velocity/test/MultipleFileResourcePathTestCase.java
4328
package org.apache.velocity.test; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.test.misc.TestLogger; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; /** * Multiple paths in the file resource loader. * * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @version $Id$ */ public class MultipleFileResourcePathTestCase extends BaseTestCase { /** * Path for templates. This property will override the * value in the default velocity properties file. */ private final static String FILE_RESOURCE_LOADER_PATH1 = TEST_COMPARE_DIR + "/multi/path1"; /** * Path for templates. This property will override the * value in the default velocity properties file. */ private final static String FILE_RESOURCE_LOADER_PATH2 = TEST_COMPARE_DIR + "/multi/path2"; /** * Results relative to the build directory. */ private static final String RESULTS_DIR = TEST_RESULT_DIR + "/multi"; /** * Results relative to the build directory. */ private static final String COMPARE_DIR = TEST_COMPARE_DIR + "/multi/compare"; /** * Default constructor. */ public MultipleFileResourcePathTestCase(String name) { super(name); } public static Test suite () { return new TestSuite(MultipleFileResourcePathTestCase.class); } public void setUp() throws Exception { assureResultsDirectoryExists(RESULTS_DIR); Velocity.reset(); Velocity.addProperty( Velocity.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH1); Velocity.addProperty( Velocity.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH2); Velocity.setProperty( Velocity.RUNTIME_LOG_INSTANCE, new TestLogger()); Velocity.init(); } /** * Runs the test. */ public void testMultipleFileResources () throws Exception { Template template1 = RuntimeSingleton.getTemplate( getFileName(null, "path1", TMPL_FILE_EXT)); Template template2 = RuntimeSingleton.getTemplate( getFileName(null, "path2", TMPL_FILE_EXT)); FileOutputStream fos1 = new FileOutputStream ( getFileName(RESULTS_DIR, "path1", RESULT_FILE_EXT)); FileOutputStream fos2 = new FileOutputStream ( getFileName(RESULTS_DIR, "path2", RESULT_FILE_EXT)); Writer writer1 = new BufferedWriter(new OutputStreamWriter(fos1)); Writer writer2 = new BufferedWriter(new OutputStreamWriter(fos2)); /* * put the Vector into the context, and merge both */ VelocityContext context = new VelocityContext(); template1.merge(context, writer1); writer1.flush(); writer1.close(); template2.merge(context, writer2); writer2.flush(); writer2.close(); if (!isMatch(RESULTS_DIR, COMPARE_DIR, "path1", RESULT_FILE_EXT, CMP_FILE_EXT) || !isMatch(RESULTS_DIR, COMPARE_DIR, "path2", RESULT_FILE_EXT, CMP_FILE_EXT)) { fail("Output incorrect."); } } }
apache-2.0
mariusj/org.openntf.domino
domino/core/src/main/java/org/openntf/domino/ext/ColorObject.java
1163
/** * */ package org.openntf.domino.ext; /** * @author withersp * * OpenNTF Domino extensions to ColorObject * */ public interface ColorObject { /** * Gets the ColorObject's color as a hex value, standard for web development. * * @return String corresponding to the hex value for the color, following RGB format, e.g. * <ul> * <li>000000 for black</li> * <li>FFFFFF for white * <li> * <li>FF0000 for red</li> * <li>0000FF for blue</li> * </ul> * @since org.openntf.domino 1.0.0 */ public String getHex(); /** * Sets a ColorObject to a specific color using hex format, standard for web development. * * @param hex * String corresponding to the hex value for the color, following RGB format, e.g. * <ul> * <li>000000 for black</li> * <li>FFFFFF for white * <li> * <li>FF0000 for red</li> * <li>0000FF for blue</li> * </ul> * @since org.openntf.domino 1.0.0 */ public void setHex(final String hex); }
apache-2.0
sperfect/djuqbox
Mqtt-jooink/src/com/jooink/experiments/mqtt/lowlevel/FakeMqttClient.java
3222
package com.jooink.experiments.mqtt.lowlevel; import java.util.HashSet; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.user.client.Timer; public class FakeMqttClient implements IMqttClient { private String server; private int port; private String clientId; private ConnectionLostHandler connetionLostHandler; private MessageArrivedHandler messageArrivedHandler; private MessageDeliveredHandler messageDeliveredHandler; public FakeMqttClient(String server, int port, String clientId) { this.server = server; this.port = port; this.clientId = clientId; } @Override public void setConnectionLostHandler(ConnectionLostHandler h) { this.connetionLostHandler = h; } @Override public void setMessageHandler(MessageArrivedHandler h) { this.messageArrivedHandler = h; } @Override public void setMessageDeliveredHandler(MessageDeliveredHandler h) { this.messageDeliveredHandler = h; } private int num; private Timer timer = new Timer() { private int last = 0; @Override public void run() { if(messageArrivedHandler == null) return; if(subscribedFilters.isEmpty()) return; if(last >= subscribedFilters.size()) { last = 0; } MqttMessage m = MqttMessage.create(" Fake Message " + (num++) ); m.setDestinationName((String)subscribedFilters.toArray()[last]); messageArrivedHandler.onMessageArrived(m); last++; } }; private static native void call_onSuccess(ConnectOptions o) /*-{ o.onSuccess(); }-*/; @Override public void connect(final ConnectOptions co) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { call_onSuccess(co); timer.scheduleRepeating(1000); } }); } @Override public void disconnect() { timer.cancel(); //:) } HashSet<String> subscribedFilters = new HashSet<String>(); private static native void call_onSubscriptionSuccess(SubscribeOptions o) /*-{ o.onSubscriptionSuccess(); }-*/; @Override public void subscribe(String filter,final SubscribeOptions options) { subscribedFilters.add(filter); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { call_onSubscriptionSuccess(options); } }); } private static native void call_onUnsubscriptionSuccess(UnsubscribeOptions o) /*-{ o.onUnsubscriptionSuccess(); }-*/; @Override public void unsubscribe(String filter, final UnsubscribeOptions options) { subscribedFilters.remove(filter); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { call_onUnsubscriptionSuccess(options); } }); } @Override public void send(final MqttMessage m) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { if(messageDeliveredHandler != null) messageDeliveredHandler.onMessageDelivered(m); //me //XXX actually we should provide a real match for wildcard topics if(subscribedFilters.contains(m.getDestinationName()) && messageArrivedHandler != null) { messageArrivedHandler.onMessageArrived(m); } } }); } }
apache-2.0
caskdata/cdap
cdap-app-fabric/src/main/java/co/cask/cdap/gateway/handlers/meta/RemoteSystemOperationsService.java
4291
/* * Copyright © 2016 Cask Data, 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 co.cask.cdap.gateway.handlers.meta; import co.cask.cdap.api.metrics.MetricsCollectionService; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.discovery.ResolvingDiscoverable; import co.cask.cdap.common.http.CommonNettyHttpServiceBuilder; import co.cask.cdap.common.logging.LoggingContextAccessor; import co.cask.cdap.common.logging.ServiceLoggingContext; import co.cask.cdap.common.metrics.MetricsReporterHook; import co.cask.cdap.proto.id.NamespaceId; import co.cask.http.HttpHandler; import co.cask.http.NettyHttpService; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.AbstractIdleService; import com.google.inject.Inject; import com.google.inject.name.Named; import org.apache.twill.common.Cancellable; import org.apache.twill.discovery.Discoverable; import org.apache.twill.discovery.DiscoveryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; /** * Provides REST endpoints to execute System Operations such as writing to Store, Lineage etc remotely. */ public class RemoteSystemOperationsService extends AbstractIdleService { private static final Logger LOG = LoggerFactory.getLogger(RemoteSystemOperationsService.class); private final DiscoveryService discoveryService; private final NettyHttpService httpService; private Cancellable cancellable; @Inject RemoteSystemOperationsService(CConfiguration cConf, DiscoveryService discoveryService, MetricsCollectionService metricsCollectionService, @Named(Constants.RemoteSystemOpService.HANDLERS_NAME) Set<HttpHandler> handlers) { this.discoveryService = discoveryService; int workerThreads = cConf.getInt(Constants.RemoteSystemOpService.WORKER_THREADS); int execThreads = cConf.getInt(Constants.RemoteSystemOpService.EXEC_THREADS); this.httpService = new CommonNettyHttpServiceBuilder(cConf) .addHttpHandlers(handlers) .setHost(cConf.get(Constants.RemoteSystemOpService.SERVICE_BIND_ADDRESS)) .setHandlerHooks(ImmutableList.of( new MetricsReporterHook(metricsCollectionService, Constants.Service.REMOTE_SYSTEM_OPERATION))) .setWorkerThreadPoolSize(workerThreads) .setExecThreadPoolSize(execThreads) .setConnectionBacklog(20000) .build(); } @Override protected void startUp() throws Exception { LoggingContextAccessor.setLoggingContext(new ServiceLoggingContext(NamespaceId.SYSTEM.getNamespace(), Constants.Logging.COMPONENT_NAME, Constants.Service.REMOTE_SYSTEM_OPERATION)); LOG.info("Starting RemoteSystemOperationService..."); httpService.startAndWait(); cancellable = discoveryService.register(ResolvingDiscoverable.of( new Discoverable(Constants.Service.REMOTE_SYSTEM_OPERATION, httpService.getBindAddress()))); LOG.info("RemoteSystemOperationService started successfully on {}", httpService.getBindAddress()); } @Override protected void shutDown() throws Exception { LOG.info("Stopping RemoteSystemOperationService..."); try { if (cancellable != null) { cancellable.cancel(); } } finally { httpService.stopAndWait(); } } @Override public String toString() { return Objects.toStringHelper(this) .add("bindAddress", httpService.getBindAddress()) .toString(); } public NettyHttpService getHttpService() { return httpService; } }
apache-2.0
psiroky/optaplanner
optaplanner-core/src/main/java/org/optaplanner/core/api/score/buildin/simplelong/SimpleLongScoreHolder.java
1888
/* * Copyright 2013 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.optaplanner.core.api.score.buildin.simplelong; import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.holder.AbstractScoreHolder; import org.kie.internal.event.rule.ActivationUnMatchListener; import org.kie.api.runtime.rule.Match; import org.kie.api.runtime.rule.RuleContext; import org.kie.api.runtime.rule.Session; /** * @see SimpleLongScore */ public class SimpleLongScoreHolder extends AbstractScoreHolder { protected long score; public SimpleLongScoreHolder(boolean constraintMatchEnabled) { super(constraintMatchEnabled); } public long getScore() { return score; } @Deprecated public void setScore(long score) { this.score = score; } // ************************************************************************ // Worker methods // ************************************************************************ public void addConstraintMatch(RuleContext kcontext, final long weight) { score += weight; registerLongConstraintMatch(kcontext, 0, weight, new Runnable() { public void run() { score -= weight; } }); } public Score extractScore() { return SimpleLongScore.valueOf(score); } }
apache-2.0
dahlstrom-g/intellij-community
python/testSrc/com/jetbrains/python/PyNotImportedPackageNameCompletionTest.java
991
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python; import com.jetbrains.python.fixtures.PyTestCase; public class PyNotImportedPackageNameCompletionTest extends PyTestCase { public void testDotAfterPackageName() { final String testName = getTestName(false); myFixture.copyDirectoryToProject(testName, ""); myFixture.configureByFile("main.py"); myFixture.completeBasic(); myFixture.checkResultByFile(testName + "/main.after.py"); } public void testCompletionForAlias() { final String testName = getTestName(false); myFixture.copyDirectoryToProject(testName, ""); myFixture.configureByFile("main.py"); myFixture.completeBasic(); myFixture.checkResultByFile(testName + "/main.after.py"); } @Override protected String getTestDataPath() { return super.getTestDataPath() + "/completion/notImportedPackageName/"; } }
apache-2.0
KRMAssociatesInc/eHMP
ehmp/product/production/soap-handler/src/main/java/us/vistacore/vxsync/term/jlv/JLVDodAllergiesMap.java
8523
package us.vistacore.vxsync.term.jlv; import us.vistacore.vxsync.term.hmp.TermLoadException; import us.vistacore.vxsync.utility.NullChecker; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used to retrieve mapping data from the JLV H2 Database - DOD_ALLERGIES table. * * @author Les.Westberg * */ public class JLVDodAllergiesMap { static final Logger LOG = LoggerFactory.getLogger(JLVDodAllergiesMap.class); private Connection oDBConnection = null; private static final String SQL_SELECT_BY_CHCS_IEN = "SELECT dod_allergies.chcsAllergyIen, " + "dod_allergies.chcsName, " + "dod_allergies.umlsCui, " + "reactants.umlsCode, " + "reactants.umlsText " + "FROM dod_allergies LEFT OUTER JOIN reactants ON dod_allergies.umlscui = reactants.umlscode " + "WHERE dod_allergies.umlsCui IS NOT NULL AND " + "dod_allergies.chcsAllergyIen = ?"; private static final String SQL_SELECT_BY_DOD_NCID = "SELECT dod_allergies.dodNcid, " + "dod_allergies.dodName, " + "dod_allergies.umlsCui, " + "reactants.umlsCode, " + "reactants.umlsText " + "FROM dod_allergies LEFT OUTER JOIN reactants ON dod_allergies.umlscui = reactants.umlscode " + "WHERE dod_allergies.umlsCui IS NOT NULL AND " + "dod_allergies.dodNcid = ?"; public static final int SQL_PARAM_CHCS_IEN = 1; public static final int SQL_PARAM_DOD_NCID = 1; public static final int SQL_FIELD_DOD_ALLERGIES_CHCS_ALLERGY_IEN = 1; public static final int SQL_FIELD_DOD_ALLERGIES_CHCS_DOD_NCID = 1; public static final int SQL_FIELD_DOD_ALLERGIES_CHCS_NAME = 2; public static final int SQL_FIELD_DOD_ALLERGIES_DOD_NAME = 2; public static final int SQL_FIELD_DOD_ALLERGIES_UMLS_CUI = 3; public static final int SQL_FIELD_REACTANTS_UMLS_CODE = 4; public static final int SQL_FIELD_REACTANTS_UMLS_TEXT = 5; public static final String CODE_SYSTEM_UMLS_CUI = "urn:oid:2.16.840.1.113883.6.86"; /** * Cannot call the default constructor... Must call the other one. */ @SuppressWarnings("unused") private JLVDodAllergiesMap() { } /** * Construct an object with the given database connection. * * @param oDBConnection A valid database connection. * @throws TermLoadException This exception is thrown if the database connection is null. */ public JLVDodAllergiesMap(Connection oDBConnection) throws TermLoadException { if (oDBConnection == null) { throw new TermLoadException("The database connection object was null."); } this.oDBConnection = oDBConnection; } /** * This method retrieves the mapped code information for the given CHCS IEN. * * @param sChcsIen The CHCS IEN for the allergy. * @return The UMLS CUI code information obtained from the map. * @throws TermLoadException */ public JLVMappedCode getAllergyUMLSCuiFromChcsIen(String sChcsIen) throws TermLoadException { JLVMappedCode oMappedCode = null; if (NullChecker.isNotNullish(sChcsIen)) { PreparedStatement psSelectStatement = null; ResultSet oResults = null; try { psSelectStatement = this.oDBConnection.prepareStatement(SQL_SELECT_BY_CHCS_IEN); psSelectStatement.setString(SQL_PARAM_CHCS_IEN, sChcsIen); oResults = psSelectStatement.executeQuery(); boolean bHasResult = false; // There should only be one mapping - we will take the first. //----------------------------------------------------------- if (oResults.next()) { JLVMappedCode oTempMappedCode = new JLVMappedCode(); String sUmlsCode = oResults.getString(SQL_FIELD_DOD_ALLERGIES_UMLS_CUI); if (NullChecker.isNotNullish(sUmlsCode)) { oTempMappedCode.setCode(sUmlsCode); bHasResult = true; } String sUmlsText = oResults.getString(SQL_FIELD_REACTANTS_UMLS_TEXT); if (NullChecker.isNotNullish(sUmlsText)) { oTempMappedCode.setDisplayText(sUmlsText); bHasResult = true; } if (bHasResult) { oTempMappedCode.setCodeSystem(CODE_SYSTEM_UMLS_CUI); oMappedCode = oTempMappedCode; } } } catch (SQLException e) { throw new TermLoadException("Failed to read Allergy information from the 'dod_allergies' and 'reactants' table. Error: " + e.getMessage(), e); } finally { TermLoadException exceptionToThrow = null; if (oResults != null) { try { oResults.close(); oResults = null; } catch (SQLException e) { String sErrorMessage = "Failed to close the result set. Error: " + e.getMessage(); LOG.error(sErrorMessage, e); exceptionToThrow = new TermLoadException(sErrorMessage, e); } } if (psSelectStatement != null) { try { psSelectStatement.close(); psSelectStatement = null; } catch (SQLException e) { String sErrorMessage = "Failed to close the prepared statement. Error: " + e.getMessage(); LOG.error(sErrorMessage, e); exceptionToThrow = new TermLoadException(sErrorMessage, e); } } if (exceptionToThrow != null) { throw exceptionToThrow; } } } return oMappedCode; } /** * This method retrieves the mapped code information for the given DOD NCID. * * @param sDodNcid The DOD NCID for the allergy. * @return The UMLS CUI code information obtained from the map. * @throws TermLoadException */ public JLVMappedCode getAllergyUMLSCuiFromDodNcid(String sDodNcid) throws TermLoadException { JLVMappedCode oMappedCode = null; if (NullChecker.isNotNullish(sDodNcid)) { PreparedStatement psSelectStatement = null; ResultSet oResults = null; try { psSelectStatement = this.oDBConnection.prepareStatement(SQL_SELECT_BY_DOD_NCID); psSelectStatement.setString(SQL_PARAM_DOD_NCID, sDodNcid); oResults = psSelectStatement.executeQuery(); boolean bHasResult = false; // There should only be one mapping - we will take the first. //----------------------------------------------------------- if (oResults.next()) { JLVMappedCode oTempMappedCode = new JLVMappedCode(); String sUmlsCode = oResults.getString(SQL_FIELD_DOD_ALLERGIES_UMLS_CUI); if (NullChecker.isNotNullish(sUmlsCode)) { oTempMappedCode.setCode(sUmlsCode); bHasResult = true; } String sUmlsText = oResults.getString(SQL_FIELD_REACTANTS_UMLS_TEXT); if (NullChecker.isNotNullish(sUmlsText)) { oTempMappedCode.setDisplayText(sUmlsText); bHasResult = true; } if (bHasResult) { oTempMappedCode.setCodeSystem(CODE_SYSTEM_UMLS_CUI); oMappedCode = oTempMappedCode; } } } catch (SQLException e) { throw new TermLoadException("Failed to read Allergy information from the 'dod_allergies' and 'reactants' table. Error: " + e.getMessage(), e); } finally { TermLoadException exceptionToThrow = null; if (oResults != null) { try { oResults.close(); oResults = null; } catch (SQLException e) { String sErrorMessage = "Failed to close the result set. Error: " + e.getMessage(); LOG.error(sErrorMessage, e); exceptionToThrow = new TermLoadException(sErrorMessage, e); } } if (psSelectStatement != null) { try { psSelectStatement.close(); psSelectStatement = null; } catch (SQLException e) { String sErrorMessage = "Failed to close the prepared statement. Error: " + e.getMessage(); LOG.error(sErrorMessage, e); exceptionToThrow = new TermLoadException(sErrorMessage, e); } } if (exceptionToThrow != null) { throw exceptionToThrow; } } } return oMappedCode; } }
apache-2.0
kiRach/grails-atmosphere
src/java/com/odelia/grails/plugins/atmosphere/DefaultGrailsAtmosphereHandlerClass.java
508
package com.odelia.grails.plugins.atmosphere; import org.codehaus.groovy.grails.commons.AbstractInjectableGrailsClass; /** * * @author BGoetzmann */ public class DefaultGrailsAtmosphereHandlerClass extends AbstractInjectableGrailsClass implements GrailsAtmosphereHandlerClass, GrailsAtmosphereHandlerClassProperty { public static final String ATMOSPHEREHANDLER = "AtmosphereHandler"; public DefaultGrailsAtmosphereHandlerClass(Class clazz) { super(clazz, ATMOSPHEREHANDLER); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-servermigration/src/main/java/com/amazonaws/services/servermigration/model/LaunchAppResult.java
2298
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.servermigration.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sms-2016-10-24/LaunchApp" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class LaunchAppResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof LaunchAppResult == false) return false; LaunchAppResult other = (LaunchAppResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public LaunchAppResult clone() { try { return (LaunchAppResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
kim-wang-bj/LightAndroidAnnotation
light-android-annotation/src/main/java/com/wq/android/lightannotation/annotations/ArrayById.java
442
/** * */ package com.wq.android.lightannotation.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Wang Qi */ @Documented @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface ArrayById { int value(); }
apache-2.0
msebire/intellij-community
platform/util/src/com/intellij/ui/ColorUtil.java
8764
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * @author max */ package com.intellij.ui; import com.intellij.util.NotNullProducer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; /** * @author max * @author Konstantin Bulenkov */ @SuppressWarnings("UseJBColor") public class ColorUtil { private ColorUtil() { } @NotNull public static Color marker(@NotNull final String name) { return new JBColor(new NotNullProducer<Color>() { @NotNull @Override public Color produce() { throw new AssertionError(name); } }) { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return name; } }; } @NotNull public static Color softer(@NotNull Color color) { if (color.getBlue() > 220 && color.getRed() > 220 && color.getGreen() > 220) return color; final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return Color.getHSBColor(hsb[0], 0.6f * hsb[1], hsb[2]); } @NotNull public static Color darker(@NotNull Color color, int tones) { return hackBrightness(color, tones, 1 / 1.1F); } @NotNull public static Color brighter(@NotNull Color color, int tones) { return hackBrightness(color, tones, 1.1F); } @NotNull public static Color hackBrightness(@NotNull Color color, int howMuch, float hackValue) { return hackBrightness(color.getRed(), color.getGreen(), color.getBlue(), howMuch, hackValue); } @NotNull public static Color hackBrightness(int r, int g, int b, int howMuch, float hackValue) { final float[] hsb = Color.RGBtoHSB(r, g, b, null); float brightness = hsb[2]; for (int i = 0; i < howMuch; i++) { brightness = Math.min(1, Math.max(0, brightness * hackValue)); if (brightness == 0 || brightness == 1) break; } return Color.getHSBColor(hsb[0], hsb[1], brightness); } @NotNull public static Color saturate(@NotNull Color color, int tones) { final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); float saturation = hsb[1]; for (int i = 0; i < tones; i++) { saturation = Math.min(1, saturation * 1.1F); if (saturation == 1) break; } return Color.getHSBColor(hsb[0], saturation, hsb[2]); } @NotNull public static Color desaturate(@NotNull Color color, int tones) { final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); float saturation = hsb[1]; for (int i = 0; i < tones; i++) { saturation = Math.max(0, saturation / 1.1F); if (saturation == 0) break; } return Color.getHSBColor(hsb[0], saturation, hsb[2]); } @NotNull public static Color dimmer(@NotNull final Color color) { NotNullProducer<Color> func = new NotNullProducer<Color>() { @NotNull @Override public Color produce() { float[] rgb = color.getRGBColorComponents(null); float alpha = 0.80f; float rem = 1 - alpha; return new Color(rgb[0] * alpha + rem, rgb[1] * alpha + rem, rgb[2] * alpha + rem); } }; return wrap(color, func); } private static Color wrap(@NotNull Color color, NotNullProducer<Color> func) { return color instanceof JBColor ? new JBColor(func) : func.produce(); } private static int shift(int colorComponent, double d) { final int n = (int)(colorComponent * d); return n > 255 ? 255 : n < 0 ? 0 : n; } @NotNull public static Color shift(@NotNull final Color c, final double d) { NotNullProducer<Color> func = new NotNullProducer<Color>() { @NotNull @Override public Color produce() { return new Color(shift(c.getRed(), d), shift(c.getGreen(), d), shift(c.getBlue(), d), c.getAlpha()); } }; return wrap(c, func); } @NotNull public static Color withAlpha(@NotNull Color c, double a) { return toAlpha(c, (int)(255 * a)); } @NotNull static Color srcOver(@NotNull Color c, @NotNull Color b) { float [] rgba = new float[4]; rgba = c.getRGBComponents(rgba); float[] brgba = new float[4]; brgba = b.getRGBComponents(brgba); float dsta = 1.0f - rgba[3]; // Applying SrcOver rule return new Color(rgba[0]*rgba[3] + dsta*brgba[0], rgba[1]*rgba[3] + dsta*brgba[1], rgba[2]*rgba[3] + dsta*brgba[2], 1.0f); } @NotNull public static Color withPreAlpha(@NotNull Color c, double a) { float [] rgba = new float[4]; rgba = withAlpha(c, a).getRGBComponents(rgba); return new Color(rgba[0]*rgba[3], rgba[1]*rgba[3], rgba[2]*rgba[3], 1.0f); } @NotNull public static Color toAlpha(@Nullable Color color, final int a) { final Color c = color == null ? Color.black : color; NotNullProducer<Color> func = new NotNullProducer<Color>() { @NotNull @Override public Color produce() { return new Color(c.getRed(), c.getGreen(), c.getBlue(), a); } }; return wrap(c, func); } @NotNull public static String toHex(@NotNull final Color c) { return toHex(c, false); } @NotNull public static String toHex(@NotNull final Color c, final boolean withAlpha) { final String R = Integer.toHexString(c.getRed()); final String G = Integer.toHexString(c.getGreen()); final String B = Integer.toHexString(c.getBlue()); final String rgbHex = (R.length() < 2 ? "0" : "") + R + (G.length() < 2 ? "0" : "") + G + (B.length() < 2 ? "0" : "") + B; if (!withAlpha){ return rgbHex; } final String A = Integer.toHexString(c.getAlpha()); return rgbHex + (A.length() < 2 ? "0" : "") + A; } @NotNull public static String toHtmlColor(@NotNull final Color c) { return "#"+toHex(c); } /** * Return Color object from string. The following formats are allowed: * {@code 0xA1B2C3}, * {@code #abc123}, * {@code ABC123}, * {@code ab5}, * {@code #FFF}. * * @param str hex string * @return Color object */ @NotNull public static Color fromHex(@NotNull String str) { int pos = str.startsWith("#") ? 1 : str.startsWith("0x") ? 2 : 0; int len = str.length() - pos; if (len == 3) return new Color(fromHex1(str, pos), fromHex1(str, pos + 1), fromHex1(str, pos + 2), 255); if (len == 4) return new Color(fromHex1(str, pos), fromHex1(str, pos + 1), fromHex1(str, pos + 2), fromHex1(str, pos + 3)); if (len == 6) return new Color(fromHex2(str, pos), fromHex2(str, pos + 2), fromHex2(str, pos + 4), 255); if (len == 8) return new Color(fromHex2(str, pos), fromHex2(str, pos + 2), fromHex2(str, pos + 4), fromHex2(str, pos + 6)); throw new IllegalArgumentException("unsupported length:" + str); } private static int fromHex(@NotNull String str, int pos) { char ch = str.charAt(pos); if (ch >= '0' && ch <= '9') return ch - '0'; if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; throw new IllegalArgumentException("unsupported char at " + pos + ":" + str); } private static int fromHex1(@NotNull String str, int pos) { return 17 * fromHex(str, pos); } private static int fromHex2(@NotNull String str, int pos) { return 16 * fromHex(str, pos) + fromHex(str, pos + 1); } @Nullable public static Color fromHex(@Nullable String str, @Nullable Color defaultValue) { if (str == null) return defaultValue; try { return fromHex(str); } catch (Exception e) { return defaultValue; } } /** * @param c color to check * @return dark or not */ public static boolean isDark(@NotNull Color c) { return ((getLuminance(c) + 0.05) / 0.05) < 4.5; } public static double getLuminance(@NotNull Color color) { return getLinearRGBComponentValue(color.getRed() / 255.0) * 0.2126 + getLinearRGBComponentValue(color.getGreen() / 255.0) * 0.7152 + getLinearRGBComponentValue(color.getBlue() / 255.0) * 0.0722; } public static double getLinearRGBComponentValue(double colorValue) { if (colorValue <= 0.03928) { return colorValue / 12.92; } return Math.pow(((colorValue + 0.055) / 1.055), 2.4); } @NotNull public static Color mix(@NotNull final Color c1, @NotNull final Color c2, double balance) { if (balance <= 0) return c1; if (balance >= 1) return c2; NotNullProducer<Color> func = new MixedColorProducer(c1, c2, balance); return c1 instanceof JBColor || c2 instanceof JBColor ? new JBColor(func) : func.produce(); } }
apache-2.0
mksmbrtsh/LLRPexplorer
src/org/llrp/ltk/generated/enumerations/C1G2KillResultType.java
8300
/* * * This file was generated by LLRP Code Generator * see http://llrp-toolkit.cvs.sourceforge.net/llrp-toolkit/ * for more information * Generated on: Sun Apr 08 14:14:12 EDT 2012; * */ /* * Copyright 2007 ETH Zurich * * 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.llrp.ltk.generated.enumerations; import maximsblog.blogspot.com.llrpexplorer.Logger; import org.jdom2.Content; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.Text; import org.llrp.ltk.generated.LLRPConstants; import org.llrp.ltk.types.LLRPBitList; import org.llrp.ltk.types.LLRPEnumeration; import org.llrp.ltk.types.UnsignedByte; import org.llrp.ltk.types.UnsignedByte; import java.lang.IllegalArgumentException; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; /** * C1G2KillResultType is Enumeration of Type UnsignedByte */ public class C1G2KillResultType extends UnsignedByte implements LLRPEnumeration { public static final int Success = 0; public static final int Zero_Kill_Password_Error = 1; public static final int Insufficient_Power = 2; public static final int Nonspecific_Tag_Error = 3; public static final int No_Response_From_Tag = 4; public static final int Nonspecific_Reader_Error = 5; Logger logger = Logger.getLogger(C1G2KillResultType.class); public C1G2KillResultType() { super(0); } /** * Create new C1G2KillResultType by passing integer value. * * @throws IllegalArgumentException * if the value is not allowed for this enumeration * @param value an Integer value allowed - might check first * with isValidValue it it is an allowed value */ public C1G2KillResultType(int value) { super(value); if (!isValidValue(value)) { throw new IllegalArgumentException("Value not allowed"); } } /** * Create new C1G2KillResultType by passing jdom element. * * @throws IllegalArgumentException * if the value found in element is not allowed * for this enumeration. * @param element - jdom element where the child is a string * that is the name for a value of the enumeration. */ public C1G2KillResultType(final Element element) { this(element.getText()); } /** * Create new C1G2KillResultType by passing a string. * * @throws IllegalArgumentException * if the string does not stand for a valid value. */ public C1G2KillResultType(final String name) { if (!isValidName(name)) { throw new IllegalArgumentException("Name not allowed"); } this.value = getValue(name); signed = false; } /** * Create new C1G2KillResultType by passing LLRPBitList. * * @throws IllegalArgumentException * if the value found in the BitList is not allowed * for this enumeration. * @param list - LLRPBitList */ public C1G2KillResultType(final LLRPBitList list) { decodeBinary(list); if (!isValidValue(new Integer(toInteger()))) { throw new IllegalArgumentException("Value not allowed"); } } /** * set the current value of this enumeration to the * value identified by given string. * * @throws IllegalArgumentException * if the value found for given String is not allowed * for this enumeration. * @param name set this enumeration to hold one of the allowed values */ public final void set(final String name) { if (!isValidName(name)) { throw new IllegalArgumentException("name not allowed"); } this.value = getValue(name); } /** * set the current value of this enumeration to the * value given. * * @throws IllegalArgumentException * if the value is not allowed * for this enumeration. * @param value to be set */ public final void set(final int value) { if (!isValidValue(value)) { throw new IllegalArgumentException("value not allowed"); } this.value = value; } /** * {@inheritDoc} */ public Content encodeXML(final String name, Namespace ns) { Element element = new Element(name, ns); //Element element = new Element(name, Namespace.getNamespace("llrp",LLRPConstants.LLRPNAMESPACE)); element.setContent(new Text(toString())); return element; } /** * {@inheritDoc} */ public String toString() { return getName(toInteger()); } /** * {@inheritDoc} */ public boolean isValidValue(final int value) { switch (value) { case 0: return true; case 1: return true; case 2: return true; case 3: return true; case 4: return true; case 5: return true; default: return false; } } /** * {@inheritDoc} */ public final int getValue(final String name) { if (name.equalsIgnoreCase("Success")) { return 0; } if (name.equalsIgnoreCase("Zero_Kill_Password_Error")) { return 1; } if (name.equalsIgnoreCase("Insufficient_Power")) { return 2; } if (name.equalsIgnoreCase("Nonspecific_Tag_Error")) { return 3; } if (name.equalsIgnoreCase("No_Response_From_Tag")) { return 4; } if (name.equalsIgnoreCase("Nonspecific_Reader_Error")) { return 5; } return -1; } /** * {@inheritDoc} */ public final String getName(final int value) { if (0 == value) { return "Success"; } if (1 == value) { return "Zero_Kill_Password_Error"; } if (2 == value) { return "Insufficient_Power"; } if (3 == value) { return "Nonspecific_Tag_Error"; } if (4 == value) { return "No_Response_From_Tag"; } if (5 == value) { return "Nonspecific_Reader_Error"; } return ""; } /** * {@inheritDoc} */ public boolean isValidName(final String name) { if (name.equals("Success")) { return true; } if (name.equals("Zero_Kill_Password_Error")) { return true; } if (name.equals("Insufficient_Power")) { return true; } if (name.equals("Nonspecific_Tag_Error")) { return true; } if (name.equals("No_Response_From_Tag")) { return true; } if (name.equals("Nonspecific_Reader_Error")) { return true; } return false; } /** * number of bits used to represent this type. * * @return Integer */ public static int length() { return UnsignedByte.length(); } /** * wrapper method for UnsignedIntegers that use BigIntegers to store value * */ private final String getName(final BigInteger value) { logger.warn("C1G2KillResultType must convert BigInteger " + value + " to Integer value " + value.intValue()); return getName(value.intValue()); } /** * wrapper method for UnsignedIntegers that use BigIntegers to store value * */ private final boolean isValidValue(final BigInteger value) { logger.warn("C1G2KillResultType must convert BigInteger " + value + " to Integer value " + value.intValue()); return isValidValue(value.intValue()); } }
apache-2.0
ventilb/stagediver.fx-database
database-hibernate/src/main/java/de/iew/stagediver/fx/database/hibernate/HBConnectionProvider.java
4864
/* * Copyright 2012-2014 Manuel Schulze <manuel_schulze@i-entwicklung.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.iew.stagediver.fx.database.hibernate; import de.iew.stagediver.fx.database.services.ConnectionService; import de.iew.stagediver.fx.database.services.exception.ConnectException; import de.iew.stagediver.fx.database.services.exception.ConnectionReleaseException; import de.qaware.sdfx.lookup.Lookup; import org.apache.commons.lang.StringUtils; import org.hibernate.HibernateException; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.Configurable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; /** * Implements a hibernate connection provider to act as a bridge between our own {@link ConnectionService} and * hibernate. * <p> * Currently it requires to configure database, username and password. In the future it's planned to only work with * database profiles which are configured in the underlying connection service framework. * </p> * <p> * To use this connection provider you must use the following properties in your {@code hibernate.cfg.xml}. * </p> * <pre> * {@code * <property name="connection.provider_class">de.iew.stagediver.fx.database.hibernate.HBConnectionProvider</property> * <property name="de.iew.stagediver.fx.database.hibernate.database">example_db</property> * <property name="de.iew.stagediver.fx.database.hibernate.username">foo</property> * <property name="de.iew.stagediver.fx.database.hibernate.password">bar</property> * } * </pre> * * @author <a href="mailto:manuel_schulze@i-entwicklung.de">Manuel Schulze</a> * @see <a href="http://jeff.familyyu.net/2011/09/08/upgrading-hibernate-3-3-2-to-hibernate-4-0-0/">http://jeff.familyyu.net/2011/09/08/upgrading-hibernate-3-3-2-to-hibernate-4-0-0/</a> * @since 19.01.14 - 15:56 */ public class HBConnectionProvider implements ConnectionProvider, Configurable { private static Logger log = LoggerFactory.getLogger(HBConnectionProvider.class); private static final Lookup LOOKUP = new Lookup(HBConnectionProvider.class); private static final String PREFIX = "de.iew.stagediver.fx.database.hibernate."; public static final String IEW_DATABASE = PREFIX + "database"; public static final String IEW_DATABASE_USERNAME = PREFIX + "username"; public static final String IEW_DATABASE_PASSWORD = PREFIX + "password"; private String database; private String username; private String password; @Override public void configure(Map configurationValues) { log.debug("HBConnectionProvider.configure({})", configurationValues); this.database = (String) configurationValues.get(IEW_DATABASE); this.username = (String) configurationValues.get(IEW_DATABASE_USERNAME); this.password = (String) configurationValues.get(IEW_DATABASE_PASSWORD); verify(); } protected void verify() { final boolean databaseOk = StringUtils.isNotBlank(this.database); if (!(databaseOk)) { throw new HibernateException("Configuration error: database name is required"); } } @Override public Connection getConnection() throws SQLException { try { final ConnectionService connectionService = LOOKUP.lookup(ConnectionService.class); return connectionService.checkoutBuildInDatabaseConnection(this.database, this.username, this.password); } catch (ConnectException e) { throw new SQLException(e); } } @Override public void closeConnection(Connection conn) throws SQLException { log.debug("HBConnectionProvider.closeConnection({})", conn); final ConnectionService connectionService = LOOKUP.lookup(ConnectionService.class); try { connectionService.releaseConnection(conn); } catch (ConnectionReleaseException e) { throw new SQLException(e); } } @Override public boolean supportsAggressiveRelease() { return false; } @Override public boolean isUnwrappableAs(Class unwrapType) { return false; } @Override public <T> T unwrap(Class<T> unwrapType) { return null; } }
apache-2.0
turf00/spring-jms-extras
src/main/java/com/bvb/spring/jms/listener/config/PauseConfigBuilder.java
4216
package com.bvb.spring.jms.listener.config; import java.util.concurrent.TimeUnit; /** * Build a {@link PauseConfig}. */ public class PauseConfigBuilder { private Long throttleDeliveryForMs; private Long throttleRelaxEveryMs; private Long delayConsumptionForMs; private Integer throttleMaxConcurrent; /** * Get a new instance of the builder to use. * @return the builder. */ public static PauseConfigBuilder newBuilder() { return new PauseConfigBuilder(); } /** * Throttle delivery for a period in seconds. * @param delaySeconds the length of time to throttle by. * @return the builder. */ public PauseConfigBuilder withThrottleDeliveryForXSeconds(long delaySeconds) { this.throttleDeliveryForMs = TimeUnit.SECONDS.toMillis(delaySeconds); return this; } /** * Throttle delivery for a period in minutes. * @param delayMinutes the length of time in minutes to throttle by. * @return the builder. */ public PauseConfigBuilder withThrottleDeliveryForXMinutes(int delayMinutes) { this.throttleDeliveryForMs = TimeUnit.MINUTES.toMillis(delayMinutes); return this; } /** * Throttle delivery for a period in milliseconds. * @param delayMs the length of time in milliseconds to throttle by. * @return the builder. */ public PauseConfigBuilder withThrottleDeliveryForXMs(long delayMs) { this.throttleDeliveryForMs = delayMs; return this; } /** * The throttling will be relaxed gradually, specify how often this should occur. The minimum value allowed here is * 1 minute. * @param relaxSeconds the number of seconds between relaxing the throttle. * @return the builder. */ public PauseConfigBuilder withThrottleRelaxEveryXSeconds(long relaxSeconds) { this.throttleRelaxEveryMs = TimeUnit.SECONDS.toMillis(relaxSeconds); return this; } /** * The throttling will be relaxed gradually, specify how often this should occur. The minimum value allowed here is * 1 minute. * @param relaxSeconds the number of seconds between relaxing the throttle. * @return the builder. */ public PauseConfigBuilder withThrottleRelaxEveryXMinutes(long relaxMinutes) { this.throttleRelaxEveryMs = TimeUnit.MINUTES.toMillis(relaxMinutes); return this; } /** * Set the max concurrent consumers to use when throttling. This is the initial throttled value and then the * throttling is relaxed gradually. * @param maxConcurrent the max number of concurrent values to use. * @return the builder. */ public PauseConfigBuilder withThrottleMaxConcurrency(int maxConcurrent) { this.throttleMaxConcurrent = maxConcurrent; return this; } /** * Delay consumption of messages for this length of time in milliseconds. * @param delayConsumptionForMs delay for these milliseconds. * @return the builder. */ public PauseConfigBuilder withDelayConsumptionForXMs(long delayConsumptionForMs) { this.delayConsumptionForMs = delayConsumptionForMs; return this; } /** * Delay consumption of messages for this length of time in seconds. * @param delaySeconds the number of seconds to delay by. * @return the builder. */ public PauseConfigBuilder withDelayConsumptionForXSeconds(long delaySeconds) { this.delayConsumptionForMs = TimeUnit.SECONDS.toMillis(delaySeconds); return this; } /** * Delay consumption of messages for a period of minutes. * @param delayMinutes the number of minutes to delay consumption by. * @return the builder. */ public PauseConfigBuilder withDelayConsumptionForXMinutes(int delayMinutes) { this.delayConsumptionForMs = TimeUnit.MINUTES.toMillis(delayMinutes); return this; } public PauseConfig build() { return new PauseConfig(delayConsumptionForMs, throttleDeliveryForMs, throttleRelaxEveryMs, throttleMaxConcurrent); } }
apache-2.0
pdf4j/icepdf4
viewer/src/main/java/org/icepdf/ri/common/views/PageViewDecorator.java
5579
/* * Copyright 2006-2012 ICEsoft Technologies 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.icepdf.ri.common.views; import org.icepdf.core.util.Defs; import org.icepdf.core.util.ColorUtil; import org.icepdf.core.views.PageViewComponent; import javax.swing.*; import java.awt.*; import java.util.logging.Logger; import java.util.logging.Level; /** * <p>The PageViewDecorator class adds a page border and shadow to all of the page * views defined in the corg.icepdf.core.views.swing package. This class can * easily be modified for extended for custom page decorations.</p> * <p/> * <p>By default the this class paints with the following colors:</p> * <ul> * <li>paper color - default color is white, can be changed using the system * property org.icepdf.core.views.page.paper.color * </li> * <li>paper border color - default color is black, can be changed using the * system property org.icepdf.core.views.page.border.color</li> * <li>paper shadow color - default color is darkGrey, can be changed using the * system property org.icepdf.core.views.page.shadow.color</li> * </ul> * <p>All color values can be set using the hex rgb values. * eg. black=000000 or white=FFFFFFF. </p> * * @since 2.5 */ public class PageViewDecorator extends JComponent { private static final Logger log = Logger.getLogger(PageViewDecorator.class.toString()); protected JComponent pageViewComponent; protected static final int SHADOW_SIZE = 3; protected Dimension preferredSize = new Dimension(); private static Color pageBorderColor; private static Color pageShadowColor; private static Color pageColor; static { // sets the shadow colour of the decorator. try { String color = Defs.sysProperty( "org.icepdf.core.views.page.shadow.color", "#333333"); int colorValue = ColorUtil.convertColor(color); pageShadowColor = new Color( colorValue >= 0? colorValue : Integer.parseInt("333333", 16 )); } catch (NumberFormatException e) { if (log.isLoggable(Level.WARNING)) { log.warning("Error reading page shadow colour"); } } // background colours for paper, border and shadow. try { String color = Defs.sysProperty( "org.icepdf.core.views.page.paper.color", "#FFFFFF"); int colorValue = ColorUtil.convertColor(color); pageColor = new Color( colorValue >= 0? colorValue : Integer.parseInt("FFFFFF", 16 )); } catch (NumberFormatException e) { if (log.isLoggable(Level.WARNING)) { log.warning("Error reading page paper color."); } } // border colour for the page decoration. try { String color = Defs.sysProperty( "org.icepdf.core.views.page.border.color", "#000000"); int colorValue = ColorUtil.convertColor(color); pageBorderColor = new Color( colorValue >= 0? colorValue : Integer.parseInt("000000", 16 )); } catch (NumberFormatException e) { if (log.isLoggable(Level.WARNING)) { log.warning("Error reading page paper color."); } } } public PageViewDecorator(JComponent pageViewComponent) { setLayout(new GridLayout(1, 1, 0, 0)); this.pageViewComponent = pageViewComponent; Dimension size = pageViewComponent.getPreferredSize(); preferredSize.setSize(size.width + SHADOW_SIZE, size.height + SHADOW_SIZE); add(pageViewComponent); } public Dimension getPreferredSize() { Dimension size = pageViewComponent.getPreferredSize(); preferredSize.setSize(size.width + SHADOW_SIZE, size.height + SHADOW_SIZE); return preferredSize; } /** * Paints a default a black border and dark gray shadow for the given page. * * @param g java graphic context which is decorated with page graphics. */ public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; Point location = pageViewComponent.getLocation(); Dimension size = pageViewComponent.getPreferredSize(); // paper g2d.setColor(pageColor); g2d.fillRect(location.x, location.y, size.width, size.height); // paper shadow g2d.setColor(pageShadowColor); g2d.fillRect(location.x + SHADOW_SIZE, location.y + size.height, size.width - SHADOW_SIZE, SHADOW_SIZE); g2d.fillRect(location.x + size.width, location.y + SHADOW_SIZE, SHADOW_SIZE, size.height); super.paint(g); // paper border g2d.setColor(pageBorderColor); g2d.drawRect(location.x, location.y, size.width, size.height); } public PageViewComponent getPageViewComponent() { return (PageViewComponent) pageViewComponent; } }
apache-2.0
yaohuiwu/CAM
cam-core/src/main/java/org/cam/core/parser/antlr/PermissionBaseVisitor.java
5007
// Generated from /home/wuyaohui/code/pekall/server/CBAM/cam-core/src/main/antlr/Permission.g4 by ANTLR 4.4.1-dev package org.cam.core.parser.antlr; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; /** * This class provides an empty implementation of {@link PermissionVisitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public class PermissionBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements PermissionVisitor<T> { /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitAndExpr(@NotNull PermissionParser.AndExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitCriteria(@NotNull PermissionParser.CriteriaContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitEntity(@NotNull PermissionParser.EntityContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitInnerObject(@NotNull PermissionParser.InnerObjectContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitPermission(@NotNull PermissionParser.PermissionContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitList(@NotNull PermissionParser.ListContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitLiteralList(@NotNull PermissionParser.LiteralListContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitParentExpr(@NotNull PermissionParser.ParentExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitOrExpr(@NotNull PermissionParser.OrExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitCompExpr(@NotNull PermissionParser.CompExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIdAlias(@NotNull PermissionParser.IdAliasContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitScalarVariable(@NotNull PermissionParser.ScalarVariableContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitQueryList(@NotNull PermissionParser.QueryListContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitValue(@NotNull PermissionParser.ValueContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitAction(@NotNull PermissionParser.ActionContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitObjectType(@NotNull PermissionParser.ObjectTypeContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitInExpr(@NotNull PermissionParser.InExprContext ctx) { return visitChildren(ctx); } }
apache-2.0
open-o/nfvo
drivers/vnfm/svnfm/ericsson/vnfmdriver/VnfmdriverService/service/src/main/java/org/openo/nfvo/vnfmdriver/activator/impl/ServiceMSBManagerImpl.java
3028
/* * Copyright (c) 2017 Ericsson (China) Communication Co. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openo.nfvo.vnfmdriver.activator.impl; import java.util.Map; import net.sf.json.JSONObject; import org.openo.baseservice.roa.util.restclient.RestfulResponse; import org.openo.nfvo.vnfmdriver.activator.inf.InfServiceMSBManager; import org.openo.nfvo.vnfmdriver.common.constant.Constant; import org.openo.nfvo.vnfmdriver.common.restfulutil.HttpRestfulAPIUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <br> * <p> * </p> * * @author * @version NFVO 0.5 Feb 15, 2017 */ public class ServiceMSBManagerImpl implements InfServiceMSBManager { private static final Logger LOG = LoggerFactory.getLogger(ServiceMSBManagerImpl.class.getName()); /** * <br> * * @param paramsMap * @param driverInfo * @return * @since NFVO 0.5 */ public int register(Map<String, String> paramsMap, JSONObject driverInfo) { LOG.info("Ericsson VNFM Driver Register...", ServiceMSBManagerImpl.class); int ret = Constant.DRIVER_REGISTER_NG; RestfulResponse rsp = HttpRestfulAPIUtil.getRemoteResponse(paramsMap, driverInfo.toString()); if(null == rsp) { LOG.error("Ericsson VNFM Driver Register Failed", ServiceMSBManagerImpl.class); return ret; } if(rsp.getStatus() == Constant.HTTP_INNERERROR) { LOG.info("MSB Internal Error, Wait and Repeat to Register", ServiceMSBManagerImpl.class); ret = Constant.DRIVER_REGISTER_REPEAT; } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { LOG.info("Register Param is Invalid", ServiceMSBManagerImpl.class); ret = Constant.DRIVER_REGISTER_NG; } else if(rsp.getStatus() == Constant.HTTP_CREATED) { LOG.info("Register Successfully", ServiceMSBManagerImpl.class); ret = Constant.DRIVER_REGISTER_OK; } else { LOG.error("Unknown Result, Please Check it", ServiceMSBManagerImpl.class); ret = Constant.DRIVER_REGISTER_NG; } return ret; } /** * <br> * * @param paramsMap * @param driverInfo * @return * @since NFVO 0.5 */ public int unRegister(Map<String, String> paramsMap, JSONObject driverInfo) { LOG.info("Ericsson VNFM Driver Unregister...", ServiceMSBManagerImpl.class); return Constant.DRIVER_UNREGISTER_OK; } }
apache-2.0
softelnet/sponge
sponge-api/src/main/java/org/openksavi/sponge/kb/KnowledgeBaseConstants.java
2230
/* * Copyright 2016-2017 The Sponge authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openksavi.sponge.kb; /** * Knowledge base constants. */ public final class KnowledgeBaseConstants { /** Initialization function name. */ public static final String FUN_ON_INIT = "onInit"; /** On before load function name. */ public static final String FUN_ON_BEFORE_LOAD = "onBeforeLoad"; /** On load function name. */ public static final String FUN_ON_LOAD = "onLoad"; /** On after load function name. */ public static final String FUN_ON_AFTER_LOAD = "onAfterLoad"; /** On startup function name. */ public static final String FUN_ON_STARTUP = "onStartup"; /** On run function name. */ public static final String FUN_ON_RUN = "onRun"; /** On shutdown function name. */ public static final String FUN_ON_SHUTDOWN = "onShutdown"; /** Before reload function name. */ public static final String FUN_ON_BEFORE_RELOAD = "onBeforeReload"; /** After reload function name. */ public static final String FUN_ON_AFTER_RELOAD = "onAfterReload"; /** The engine operations variable name. */ public static final String VAR_ENGINE_OPERATIONS = "sponge"; /** Logger name prefix. */ public static final String LOGGER_NAME_PREFIX = "sponge.kb"; /** Global logger name. */ public static final String GLOBAL_LOGGER_NAME = "global"; /** Plugin logger name. */ public static final String PLUGIN_LOGGER_NAME = "plugin"; /** Abstract processor class name prefix. */ public static final String ABSTRACT_PROCESSOR_CLASS_NAME_PREFIX = "Abstract"; private KnowledgeBaseConstants() { // } }
apache-2.0
suhanlee/Android-Block
FileUploadUsingRetrofit/libfileupload/src/androidTest/java/com/devsh/libfileupload/ApplicationTest.java
354
package com.devsh.libfileupload; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/DeleteBucketResultJsonUnmarshaller.java
2851
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lightsail.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteBucketResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteBucketResultJsonUnmarshaller implements Unmarshaller<DeleteBucketResult, JsonUnmarshallerContext> { public DeleteBucketResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteBucketResult deleteBucketResult = new DeleteBucketResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return deleteBucketResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("operations", targetDepth)) { context.nextToken(); deleteBucketResult.setOperations(new ListUnmarshaller<Operation>(OperationJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return deleteBucketResult; } private static DeleteBucketResultJsonUnmarshaller instance; public static DeleteBucketResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteBucketResultJsonUnmarshaller(); return instance; } }
apache-2.0
geronimo-iia/restexpress
restexpress-common/src/test/java/org/restexpress/query/QueryOrderTest.java
2532
/** * 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. * */ /* Copyright 2012, Strategic Gains, 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.restexpress.query; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.restexpress.query.OrderCallback; import org.restexpress.query.OrderComponent; import org.restexpress.query.QueryOrder; /** * @author toddf * @since Jul 27, 2012 */ public class QueryOrderTest { @Test public void shouldAddSortCriteria() { final QueryOrder o = new QueryOrder(); assertFalse(o.isSorted()); o.addSort("name", "-zip"); assertTrue(o.isSorted()); o.iterate(new OrderCallback() { int i = 0; @Override public void orderBy(final OrderComponent component) { if (i == 0) { assertEquals("name", component.getFieldName()); assertTrue(component.isAscending()); } else if (i == 1) { assertEquals("zip", component.getFieldName()); assertTrue(component.isDescending()); } else { fail("Called too many times"); } ++i; } }); } }
apache-2.0
aosp-mirror/platform_frameworks_support
room/rxjava2/src/main/java/androidx/room/EmptyResultSetException.java
1103
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room; /** * Thrown by Room when the query needs to return a result (e.g. in a Single&lt;T> query) but the * returned result set from the database is empty. */ public class EmptyResultSetException extends RuntimeException { /** * Constructs a new EmptyResultSetException with the exception. * @param message The SQL query which didn't return any results. */ public EmptyResultSetException(String message) { super(message); } }
apache-2.0
suninformation/ymate-payment-v2
ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/base/AliPayBaseResponse.java
1882
/* * Copyright 2007-2017 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 net.ymate.payment.alipay.base; import com.alibaba.fastjson.annotation.JSONField; import net.ymate.payment.alipay.IAliPayResponse; /** * @author 刘镇 (suninformation@163.com) on 17/6/11 下午10:00 * @version 1.0 */ public abstract class AliPayBaseResponse implements IAliPayResponse { private String code; private String msg; @JSONField(name = "sub_code") private String subCode; @JSONField(name = "sub_msg") private String subMsg; private String sign; @Override public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String getSubCode() { return subCode; } public void setSubCode(String subCode) { this.subCode = subCode; } @Override public String getSubMsg() { return subMsg; } public void setSubMsg(String subMsg) { this.subMsg = subMsg; } @Override public String getSign() { return sign; } @Override public void setSign(String sign) { this.sign = sign; } }
apache-2.0
cmoulliard/apiman
distro/karaf/test/src/test/java/io/apiman/osgi/pax/testing/util/WebListenerImpl.java
696
package io.apiman.osgi.pax.testing.util; import org.ops4j.pax.web.service.spi.WebEvent; import org.ops4j.pax.web.service.spi.WebListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WebListenerImpl implements WebListener { protected Logger log = LoggerFactory.getLogger(getClass()); private boolean event; public void webEvent(WebEvent webEvent) { log.info("Got event: " + webEvent); if (webEvent.getType() == WebEvent.DEPLOYED) { this.event = true; } else if (webEvent.getType() == WebEvent.UNDEPLOYED) { this.event = false; } } public boolean gotEvent() { return event; } }
apache-2.0
PurelyApplied/geode
geode-core/src/main/java/org/apache/geode/internal/admin/remote/RegionSizeRequest.java
2709
/* * 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.geode.internal.admin.remote; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.internal.Assert; /** * A message that is sent to a particular app vm to request all the subregions of a given parent * region. */ public class RegionSizeRequest extends RegionAdminRequest implements Cancellable { private transient boolean cancelled; private transient RegionSizeResponse resp; /** * Returns a <code>ObjectNamesRequest</code> to be sent to the specified recipient. */ public static RegionSizeRequest create() { RegionSizeRequest m = new RegionSizeRequest(); return m; } /** * Must return a proper response to this request. * */ @Override protected AdminResponse createResponse(DistributionManager dm) { Assert.assertTrue(this.getSender() != null); CancellationRegistry.getInstance().registerMessage(this); resp = RegionSizeResponse.create(dm, this.getSender()); if (cancelled) { return null; } resp.calcSize(this.getRegion(dm.getSystem())); if (cancelled) { return null; } CancellationRegistry.getInstance().deregisterMessage(this); return resp; } public RegionSizeRequest() { friendlyName = "Fetch region size"; } @Override public synchronized void cancel() { cancelled = true; if (resp != null) { resp.cancel(); } } @Override public int getDSFID() { return REGION_SIZE_REQUEST; } @Override public void toData(DataOutput out) throws IOException { super.toData(out); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); } @Override public String toString() { return "RegionSizeRequest from " + getRecipient() + " region=" + getRegionName(); } }
apache-2.0
u2ware/spring-data-rest-u2ware
spring-data-rest-u2ware-browser-demo/src/main/java/io/github/u2ware/browser/demo/onetoone/bar/Bar.java
399
package io.github.u2ware.browser.demo.onetoone.bar; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import io.github.u2ware.browser.demo.basic.auto.Auto; @Entity public class Bar { @Id @GeneratedValue public Long id; public String barValue; @OneToOne public Auto auto; }
apache-2.0
MegatronKing/SVG-Android
svg-iconlibs/hardware/src/main/java/com/github/megatronking/svg/iconlibs/ic_scanner.java
2445
package com.github.megatronking.svg.iconlibs; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import com.github.megatronking.svg.support.SVGRenderer; /** * AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * SVG-Generator. It should not be modified by hand. */ public class ic_scanner extends SVGRenderer { public ic_scanner(Context context) { super(context); mAlpha = 1.0f; mWidth = dip2px(24.0f); mHeight = dip2px(24.0f); } @Override public void render(Canvas canvas, int w, int h, ColorFilter filter) { final float scaleX = w / 24.0f; final float scaleY = h / 24.0f; mPath.reset(); mRenderPath.reset(); mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); mFinalPathMatrix.postScale(scaleX, scaleY); mPath.moveTo(19.8f, 10.7f); mPath.lineTo(4.2f, 5.0f); mPath.rLineTo(-0.7f, 1.9f); mPath.lineTo(17.6f, 12.0f); mPath.lineTo(5.0f, 12.0f); mPath.rCubicTo(-1.1f, 0.0f, -2.0f, 0.9f, -2.0f, 2.0f); mPath.rLineTo(0f, 4.0f); mPath.rCubicTo(0.0f, 1.1f, 0.9f, 2.0f, 2.0f, 2.0f); mPath.rLineTo(14.0f, 0f); mPath.rCubicTo(1.1f, 0.0f, 2.0f, -0.9f, 2.0f, -2.0f); mPath.rLineTo(0f, -5.5f); mPath.rCubicTo(0.0f, -0.8f, -0.5f, -1.6f, -1.2f, -1.8f); mPath.close(); mPath.moveTo(19.8f, 10.7f); mPath.moveTo(7.0f, 17.0f); mPath.lineTo(5.0f, 17.0f); mPath.rLineTo(0f, -2.0f); mPath.rLineTo(2.0f, 0f); mPath.rLineTo(0f, 2.0f); mPath.close(); mPath.moveTo(7.0f, 17.0f); mPath.rMoveTo(12.0f, 0.0f); mPath.lineTo(9.0f, 17.0f); mPath.rLineTo(0f, -2.0f); mPath.rLineTo(10.0f, 0f); mPath.rLineTo(0f, 2.0f); mPath.close(); mPath.moveTo(19.0f, 17.0f); mRenderPath.addPath(mPath, mFinalPathMatrix); if (mFillPaint == null) { mFillPaint = new Paint(); mFillPaint.setStyle(Paint.Style.FILL); mFillPaint.setAntiAlias(true); } mFillPaint.setColor(applyAlpha(-16777216, 1.0f)); mFillPaint.setColorFilter(filter); canvas.drawPath(mRenderPath, mFillPaint); } }
apache-2.0
ZhaoKaiQiang/JianDan_OkHttp
app/src/main/java/com/socks/jiandan/okhttp/parser/FreshNewsParser.java
959
package com.socks.jiandan.okhttp.parser; import android.support.annotation.Nullable; import com.socks.jiandan.model.FreshNews; import com.socks.jiandan.okhttp.OkHttpBaseParser; import com.squareup.okhttp.Response; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; /** * Created by zhaokaiqiang on 15/11/22. */ public class FreshNewsParser extends OkHttpBaseParser<ArrayList<FreshNews>> { @Nullable public ArrayList<FreshNews> parse(Response response) { code = wrapperCode(response.code()); if (!response.isSuccessful()) return null; try { String body = response.body().string(); JSONObject resultObj = new JSONObject(body); JSONArray postsArray = resultObj.optJSONArray("posts"); return FreshNews.parse(postsArray); } catch (Exception e) { e.printStackTrace(); return null; } } }
apache-2.0
zhangzuoqiang/summer
src/test/java/li/mongo/BaseTest.java
415
package li.mongo; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * BaseTest * * @author li (limingwei@mail.com) * @version 1 (2014年1月21日 下午3:51:55) */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring.xml") public class BaseTest {}
apache-2.0
haraldmaida/AbacusSFX
src/main/java/eu/hansolo/enzo/common/BrushedMetalPaint.java
7444
/* * Copyright (c) 2015 by Gerrit Grunwald * * 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 eu.hansolo.enzo.common; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelWriter; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Shape; import java.util.Random; import java.util.stream.IntStream; /** * Created by * User: hansolo * Date: 01.03.13 * Time: 11:16 */ public class BrushedMetalPaint { private int radius; private double amount; private int color; private double shine; private boolean monochrome; private Random randomNumbers; // ******************** Constructors ************************************** public BrushedMetalPaint() { this(Color.rgb(136, 136, 136), 5, 0.1, true, 0.3); } public BrushedMetalPaint(final Color COLOR) { this(COLOR, 5, 0.1, true, 0.3); } public BrushedMetalPaint(final Color COLOR, final int RADIUS, final double AMOUNT, final boolean MONOCHROME, final double SHINE) { color = getIntFromColor(COLOR); radius = RADIUS; amount = AMOUNT; monochrome = MONOCHROME; shine = SHINE; } // ******************** Methods ******************************************* public Image getImage(final double W, final double H) { final int WIDTH = (int) W; final int HEIGHT = (int) H; WritableImage DESTINATION = new WritableImage(WIDTH, HEIGHT); final int[] IN_PIXELS = new int[WIDTH]; final int[] OUT_PIXELS = new int[WIDTH]; randomNumbers = new Random(0); final int ALPHA = color & 0xff000000; final int RED = (color >> 16) & 0xff; final int GREEN = (color >> 8) & 0xff; final int BLUE = color & 0xff; IntStream.range(0, HEIGHT).parallel().forEachOrdered( y -> { IntStream.range(0, WIDTH).parallel().forEachOrdered( x -> { int tr = RED; int tg = GREEN; int tb = BLUE; if (shine != 0) { int f = (int) (255 * shine * Math.sin((double) x / WIDTH * Math.PI)); tr += f; tg += f; tb += f; } if (monochrome) { int n = (int) (255 * (2 * randomNumbers.nextFloat() - 1) * amount); IN_PIXELS[x] = ALPHA | (clamp(tr + n) << 16) | (clamp(tg + n) << 8) | clamp(tb + n); } else { IN_PIXELS[x] = ALPHA | (random(tr) << 16) | (random(tg) << 8) | random(tb); } } ); if (radius != 0) { blur(IN_PIXELS, OUT_PIXELS, WIDTH, radius); setRGB(DESTINATION, 0, y, OUT_PIXELS); } else { setRGB(DESTINATION, 0, y, IN_PIXELS); } } ); return DESTINATION; } public ImageView getImageView(final double W, final double H, final Shape CLIP) { final Image IMAGE = getImage(W, H); final ImageView IMAGE_VIEW = new ImageView(IMAGE); IMAGE_VIEW.setClip(CLIP); return IMAGE_VIEW; } public ImagePattern apply(final Shape SHAPE) { double x = SHAPE.getLayoutBounds().getMinX(); double y = SHAPE.getLayoutBounds().getMinY(); double width = SHAPE.getLayoutBounds().getWidth(); double height = SHAPE.getLayoutBounds().getHeight(); return new ImagePattern(getImage(width, height), x, y, width, height, false); } public void blur(final int[] IN, final int[] OUT, final int WIDTH, final int RADIUS) { final int WIDTH_MINUS_1 = WIDTH - 1; final int R2 = 2 * RADIUS + 1; int tr = 0, tg = 0, tb = 0; for (int i = -RADIUS; i <= RADIUS; i++) { int rgb = IN[mod(i, WIDTH)]; tr += (rgb >> 16) & 0xff; tg += (rgb >> 8) & 0xff; tb += rgb & 0xff; } for (int x = 0; x < WIDTH; x++) { OUT[x] = 0xff000000 | ((tr / R2) << 16) | ((tg / R2) << 8) | (tb / R2); int i1 = x + RADIUS + 1; if (i1 > WIDTH_MINUS_1) { i1 = mod(i1, WIDTH); } int i2 = x - RADIUS; if (i2 < 0) { i2 = mod(i2, WIDTH); } int rgb1 = IN[i1]; int rgb2 = IN[i2]; tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16; tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8; tb += (rgb1 & 0xff) - (rgb2 & 0xff); } } public void setRadius(final int RADIUS) { radius = RADIUS; } public int getRadius() { return radius; } public void setAmount(final double AMOUNT) { amount = AMOUNT; } public double getAmount() { return amount; } public void setColor(final int COLOR) { color = COLOR; } public int getColor() { return color; } public void setMonochrome(final boolean MONOCHROME) { monochrome = MONOCHROME; } public boolean isMonochrome() { return monochrome; } public void setShine(final double SHINE) { shine = SHINE; } public double getShine() { return shine; } private int random(int x) { x += (int) (255 * (2 * randomNumbers.nextFloat() - 1) * amount); if (x < 0) { x = 0; } else if (x > 0xff) { x = 0xff; } return x; } private int clamp(final int C) { int ret = C; if (C < 0) { ret = 0; } if (C > 255) { ret = 255; } return ret; } private int mod(int a, final int B) { final int N = a / B; a -= N * B; if (a < 0) { return a + B; } return a; } private void setRGB(final WritableImage IMAGE, final int X, final int Y, final int[] PIXELS) { final PixelWriter RASTER = IMAGE.getPixelWriter(); for (int x = 0 ; x < PIXELS.length ; x++) { RASTER.setColor(X + x, Y, Color.rgb((PIXELS[x] >> 16) & 0xFF, (PIXELS[x] >> 8) & 0xFF, (PIXELS[x] &0xFF))); } } private int getIntFromColor(final Color COLOR) { String hex = COLOR.toString(); StringBuilder intValue = new StringBuilder(10); intValue.append(hex.substring(8, 10)); intValue.append(hex.substring(2, 8)); return (int) Long.parseLong(intValue.toString(), 16); } }
apache-2.0
liqk2014/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java
921
package org.cnodejs.android.md.ui.activity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.TextView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.util.DocumentUtils; import butterknife.Bind; import butterknife.ButterKnife; public class LicenseActivity extends BaseActivity { @Bind(R.id.license_toolbar) protected Toolbar toolbar; @Bind(R.id.license_tv_license) protected TextView tvLicense; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_license); ButterKnife.bind(this); toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); tvLicense.setText(DocumentUtils.getString(this, R.raw.open_source)); } }
apache-2.0
nakamura5akihito/opensec-oval
src/main/java/io/opensec/oval/model/independent/FileHashState.java
5642
/** * Opensec OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2015 Akihito Nakamura * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opensec.oval.model.independent; import io.opensec.oval.model.ComponentType; import io.opensec.oval.model.ElementRef; import io.opensec.oval.model.Family; import io.opensec.oval.model.definitions.EntityStateStringType; import io.opensec.oval.model.definitions.StateType; import java.util.ArrayList; import java.util.Collection; /** * The filehash state contains entities that are used to check the file path, * name, and the different hashes associated with a specific file. * * @author Akihito Nakamura, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> * @deprecated Deprecated as of version 5.8: * Replaced by the filehash58 state and * will be removed in a future version of the language. */ @Deprecated public class FileHashState extends StateType { private EntityStateStringType filepath; //{0..1} private EntityStateStringType path; //{0..1} private EntityStateStringType filename; //{0..1} private EntityStateStringType md5; //{0..1} private EntityStateStringType sha1; //{0..1} private EntityStateWindowsViewType windows_view; //{0..1} /** * Constructor. */ public FileHashState() { this( null, 0 ); } public FileHashState( final String id, final int version ) { this( id, version, null ); } public FileHashState( final String id, final int version, final String comment ) { super( id, version, comment ); // _oval_platform_type = OvalPlatformType.independent; // _oval_component_type = OvalComponentType.filehash; _oval_family = Family.INDEPENDENT; _oval_component = ComponentType.FILEHASH; } /** */ public void setFilepath( final EntityStateStringType filepath ) { this.filepath = filepath; } public EntityStateStringType getFilepath() { return filepath; } /** */ public void setPath( final EntityStateStringType path ) { this.path = path; } public EntityStateStringType getPath() { return path; } /** */ public void setFilename( final EntityStateStringType filename ) { this.filename = filename; } public EntityStateStringType getFilename() { return filename; } /** */ public void setMd5( final EntityStateStringType md5 ) { this.md5 = md5; } public EntityStateStringType getMd5() { return md5; } /** */ public void setSha1( final EntityStateStringType sha1 ) { this.sha1 = sha1; } public EntityStateStringType getSha1() { return sha1; } /** */ public void setWindowsView( final EntityStateWindowsViewType windows_view ) { this.windows_view = windows_view; } public EntityStateWindowsViewType getWindowsView() { return windows_view; } //********************************************************************* // DefinitionsElement //********************************************************************* @Override public Collection<ElementRef> ovalGetElementRef() { Collection<ElementRef> ref_list = new ArrayList<ElementRef>(); ref_list.add( getFilepath() ); ref_list.add( getPath() ); ref_list.add( getFilename() ); ref_list.add( getMd5() ); ref_list.add( getSha1() ); ref_list.add( getWindowsView() ); return ref_list; } //************************************************************** // java.lang.Object //************************************************************** @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals( final Object obj ) { if (!(obj instanceof FileHashState)) { return false; } return super.equals( obj ); } @Override public String toString() { return "filehash_state[" + super.toString() + ", filepath=" + getFilepath() + ", path=" + getPath() + ", filename=" + getFilename() + ", md5=" + getMd5() + ", sha1=" + getSha1() + ", windows_view=" + getWindowsView() + "]"; } } // FileHashState
apache-2.0
danke-sra/GearVRf
GVRf/Framework/src/org/gearvrf/bulletphysics/dynamics/constraintsolver/SolverConstraint.java
1999
/* * Java port of Bullet (c) 2008 Martin Dvorak <jezek2@advel.cz> * * Bullet Continuous Collision Detection and Physics Library * Copyright (c) 2003-2008 Erwin Coumans http://www.bulletphysics.com/ * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package org.gearvrf.bulletphysics.dynamics.constraintsolver; import javax.vecmath.Vector3f; /** * 1D constraint along a normal axis between bodyA and bodyB. It can be combined * to solve contact and friction constraints. * * @author jezek2 */ public class SolverConstraint { public final Vector3f relpos1CrossNormal = new Vector3f(); public final Vector3f contactNormal = new Vector3f(); public final Vector3f relpos2CrossNormal = new Vector3f(); public final Vector3f angularComponentA = new Vector3f(); public final Vector3f angularComponentB = new Vector3f(); public float appliedPushImpulse; public float appliedImpulse; public int solverBodyIdA; public int solverBodyIdB; public float friction; public float restitution; public float jacDiagABInv; public float penetration; public SolverConstraintType constraintType; public int frictionIndex; public Object originalContactPoint; }
apache-2.0
U-QASAR/u-qasar.platform
src/main/java/eu/uqasar/web/dashboard/widget/testlinkwidget/TestLinkWidgetView.java
3490
package eu.uqasar.web.dashboard.widget.testlinkwidget; /* * #%L * U-QASAR * %% * Copyright (C) 2012 - 2015 U-QASAR 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 * * 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 java.util.ArrayList; import java.util.Date; import java.util.List; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.wicket.markup.html.image.ContextImage; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import ro.fortsoft.wicket.dashboard.Widget; import ro.fortsoft.wicket.dashboard.web.WidgetView; import com.googlecode.wickedcharts.wicket6.highcharts.Chart; import eu.uqasar.model.measure.TestLinkMetricMeasurement; import eu.uqasar.service.dataadapter.TestLinkDataService; public class TestLinkWidgetView extends WidgetView { private TestLinkDataService TDT; /** * */ private static final long serialVersionUID = -1947241458043860995L; private final String period; private final String individualMetric; public TestLinkWidgetView(String id, IModel<Widget> model) { super(id, model); final TestLinkWidget testLinkWidget = (TestLinkWidget) model.getObject(); try { InitialContext ic = new InitialContext(); TDT = (TestLinkDataService) ic.lookup("java:module/TestLinkDataService"); } catch (NamingException e) { e.printStackTrace(); } if(testLinkWidget.getSettings().get("period")!=null){ period = testLinkWidget.getSettings().get("period"); } else { period = "Latest"; } if(testLinkWidget.getSettings().get("project") != null && !testLinkWidget.getSettings().get("project").isEmpty()){ String name = testLinkWidget.getSettings().get("project"); } LoadableDetachableModel<List<TestLinkMetricMeasurement>> metricsData = new LoadableDetachableModel<List<TestLinkMetricMeasurement>>() { private static final long serialVersionUID = -8120427341331851718L; @Override protected List<TestLinkMetricMeasurement> load() { Date latestSnapshotDate = TDT.getLatestDate(); if (latestSnapshotDate != null) { if(period.compareToIgnoreCase("Latest") == 0){ return TDT.getMeasurementsForProjectByLatestDate("UQASAR"); }else{ return TDT.getMeasurementsForProjectByPeriod("UQASAR", period); } } else { return new ArrayList<>(); } } }; Chart chart; individualMetric = testLinkWidget.getSettings().get("individualMetric"); if( individualMetric !=null){ chart = new Chart("chart", testLinkWidget.getChartOptionsDifferently(metricsData.getObject(),individualMetric )); } else { chart = new Chart("chart", testLinkWidget.getChartOptions(metricsData.getObject())); } // Add TestLink image add(new ContextImage("img", "assets/img/testlink.png")); add(chart); } }
apache-2.0
syntelos/gwtcc
src/com/google/gwt/dev/util/arg/ArgHandlerEnableGeneratorResultCaching.java
1489
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.dev.util.arg; import com.google.gwt.util.tools.ArgHandlerFlag; /** * An ArgHandler to provide the -XenableGeneratorResultCaching flag. * * Note: This is no longer needed since generator result caching is now enabled by default. * It's left here for an interim period, so that uses of the flag can be removed. * TODO(jbrosenberg): remove this after interim period. */ public class ArgHandlerEnableGeneratorResultCaching extends ArgHandlerFlag { public ArgHandlerEnableGeneratorResultCaching() { } @Override public String getPurpose() { return "Enables generator result caching, for those generators that implement it"; } @Override public String getTag() { return "-XenableGeneratorResultCaching"; } @Override public boolean isUndocumented() { return true; } @Override public boolean setFlag() { return true; } }
apache-2.0
pojosontheweb/woko
core/src/main/java/woko/inmemory/InMemoryWokoInitListener.java
1223
/* * Copyright 2001-2012 Remi Vankeisbelck * * 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 woko.inmemory; import woko.WokoInitListener; import woko.persistence.ObjectStore; import woko.users.UserManager; import java.util.Arrays; /** * In-mem init listener. Not for production use. */ @Deprecated public class InMemoryWokoInitListener extends WokoInitListener { @Override protected ObjectStore createObjectStore() { return new InMemoryObjectStore(); } @Override protected UserManager createUserManager() { InMemoryUserManager um = new InMemoryUserManager(); um.addUser("wdevel", "wdevel", Arrays.asList("developer")); return um; } }
apache-2.0
phax/ph-oton
ph-oton-datatables/src/main/java/com/helger/photon/uictrls/datatables/plugins/DataTablesPluginResponsive.java
5594
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.uictrls.datatables.plugins; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.ValueEnforcer; import com.helger.commons.collection.impl.CommonsArrayList; import com.helger.commons.collection.impl.ICommonsList; import com.helger.commons.state.ETriState; import com.helger.html.css.DefaultCSSClassProvider; import com.helger.html.css.ICSSClassProvider; import com.helger.html.hc.IHCConversionSettingsToNode; import com.helger.html.jscode.IJSExpression; import com.helger.html.jscode.JSAnonymousFunction; import com.helger.html.jscode.JSArray; import com.helger.html.jscode.JSAssocArray; import com.helger.html.jscode.JSExpr; import com.helger.photon.app.html.PhotonCSS; import com.helger.photon.app.html.PhotonJS; import com.helger.photon.uictrls.datatables.DataTables; import com.helger.photon.uictrls.datatables.EDataTablesCSSPathProvider; import com.helger.photon.uictrls.datatables.EDataTablesJSPathProvider; import com.helger.photon.uictrls.datatables.column.DataTablesColumnDef; public class DataTablesPluginResponsive extends AbstractDataTablesPlugin { public static final String PLUGIN_NAME = "responsive"; public static final ICSSClassProvider CSS_CLASS_ALL = DefaultCSSClassProvider.create ("all"); public static final ICSSClassProvider CSS_CLASS_CONTROL = DefaultCSSClassProvider.create ("control"); public static final ICSSClassProvider CSS_CLASS_NONE = DefaultCSSClassProvider.create ("none"); public static final ICSSClassProvider CSS_CLASS_NEVER = DefaultCSSClassProvider.create ("never"); private ICommonsList <DTPResponsiveBreakpoint> m_aBreakpoints; private ETriState m_eDetails = ETriState.UNDEFINED; /** function renderer( api, rowIdx ) */ private JSAnonymousFunction m_aDetailsRenderer; private IJSExpression m_aDetailsTarget; private EDTPResponsiveType m_eDetailsType; public DataTablesPluginResponsive () { super (PLUGIN_NAME); } @Nonnull public DataTablesPluginResponsive addBreakpoint (@Nonnull final DTPResponsiveBreakpoint aBreakpoint) { ValueEnforcer.notNull (aBreakpoint, "Breakpoint"); if (m_aBreakpoints == null) m_aBreakpoints = new CommonsArrayList <> (); m_aBreakpoints.add (aBreakpoint); return this; } @Nonnull public DataTablesPluginResponsive setDetails (@Nonnull final ETriState eDetails) { ValueEnforcer.notNull (eDetails, "Details"); m_eDetails = eDetails; return this; } @Nonnull public DataTablesPluginResponsive setDetailsRenderer (@Nullable final JSAnonymousFunction aDetailsRenderer) { m_aDetailsRenderer = aDetailsRenderer; return this; } @Nonnull public DataTablesPluginResponsive setDetailsTarget (final int nDetailsTarget) { return setDetailsTarget (JSExpr.lit (nDetailsTarget)); } @Nonnull public DataTablesPluginResponsive setDetailsTarget (final String sDetailsTarget) { return setDetailsTarget (JSExpr.lit (sDetailsTarget)); } @Nonnull public DataTablesPluginResponsive setDetailsTarget (@Nullable final IJSExpression aDetailsTarget) { m_aDetailsTarget = aDetailsTarget; return this; } @Nonnull public DataTablesPluginResponsive setDetailsType (@Nullable final EDTPResponsiveType eDetailsType) { m_eDetailsType = eDetailsType; return this; } @Override public void finalizeDataTablesSettings (@Nonnull final DataTables aDT) { // Source: // https://github.com/DataTables/Responsive/issues/8 for (final DataTablesColumnDef aColumnDef : aDT.columnDefs ()) if (!aColumnDef.isVisible ()) aColumnDef.addClass (CSS_CLASS_NEVER); } @Nullable public IJSExpression getInitParams () { final JSAssocArray ret = new JSAssocArray (); if (m_aBreakpoints != null) { final JSArray aArray = new JSArray (); for (final DTPResponsiveBreakpoint aBreakpoint : m_aBreakpoints) aArray.add (aBreakpoint.getAsJS ()); ret.add ("breakpoints", aArray); } final JSAssocArray aDetails = new JSAssocArray (); { if (m_aDetailsRenderer != null) aDetails.add ("renderer", m_aDetailsRenderer); if (m_aDetailsTarget != null) aDetails.add ("target", m_aDetailsTarget); if (m_eDetailsType != null) aDetails.add ("type", m_eDetailsType.getName ()); } if (!aDetails.isEmpty ()) ret.add ("details", aDetails); else if (m_eDetails.isDefined ()) ret.add ("details", m_eDetails.getAsBooleanValue (true)); if (ret.isEmpty ()) { // No properties present return JSExpr.TRUE; } return ret; } @Override public void registerExternalResources (final IHCConversionSettingsToNode aConversionSettings) { PhotonJS.registerJSIncludeForThisRequest (EDataTablesJSPathProvider.DATATABLES_RESPONSIVE); PhotonCSS.registerCSSIncludeForThisRequest (EDataTablesCSSPathProvider.DATATABLES_RESPONSIVE); } }
apache-2.0
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java
2030
package io.dwak.holohackernews.app; import android.content.Context; import com.bugsnag.android.Bugsnag; import com.facebook.stetho.Stetho; import com.orm.SugarApp; import io.dwak.holohackernews.app.dagger.component.AppComponent; import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent; import io.dwak.holohackernews.app.dagger.module.AppModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; public class HackerNewsApplication extends SugarApp { private static boolean mDebug = BuildConfig.DEBUG; private static HackerNewsApplication sInstance; private Context mContext; private static AppComponent sAppComponent; private static AppModule sAppModule; @Override public void onCreate() { super.onCreate(); if (sInstance == null) { sInstance = this; } if("release".equals(BuildConfig.BUILD_TYPE)){ Bugsnag.init(this); } mContext = getApplicationContext(); Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp( Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector( Stetho.defaultInspectorModulesProvider(this)) .build()); sAppModule = new AppModule(this); sAppComponent = DaggerAppComponent.builder() .appModule(sAppModule) .build(); sAppComponent.inject(this); LocalDataManager.initialize(mContext); } public static boolean isDebug() { return mDebug; } public static HackerNewsApplication getInstance() { return sInstance; } public Context getContext() { return mContext; } public static AppComponent getAppComponent() { return sAppComponent; } public static AppModule getAppModule(){ return sAppModule; } }
apache-2.0
googleads/authorized-buyers-marketplace-api-samples
java/src/main/java/com/google/api/services/samples/authorizedbuyers/marketplace/v1/buyers/clients/users/DeactivateClientUsers.java
4752
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.clients.users; import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace; import com.google.api.services.authorizedbuyersmarketplace.v1.model.ClientUser; import com.google.api.services.authorizedbuyersmarketplace.v1.model.DeactivateClientUserRequest; import com.google.api.services.samples.authorizedbuyers.marketplace.Utils; import java.io.IOException; import java.security.GeneralSecurityException; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; /** * This sample illustrates how to deactivate a client user for the given buyer, client, and user ID. * * <p>Deactivating a client user allows one to temporarily remove a given client user from accessing * the Authorized Buyers UI on behalf of a client. Access can be restored by calling * buyers.clients.users.activate. * * <p>Note that a client user in the "INVITED" state can not be deactivated, and attempting to * deactivate it will result in an error response. */ public class DeactivateClientUsers { public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) { Integer accountId = parsedArgs.getInt("account_id"); String clientId = parsedArgs.getString("client_id"); String clientUserId = parsedArgs.getString("client_user_id"); String name = String.format("buyers/%d/clients/%s/users/%s", accountId, clientId, clientUserId); ClientUser clientUser = null; try { clientUser = marketplaceClient .buyers() .clients() .users() .deactivate(name, new DeactivateClientUserRequest()) .execute(); } catch (IOException ex) { System.out.printf("Marketplace API returned error response:%n%s", ex); System.exit(1); } System.out.printf("Deactivated client user with name \"%s\":%n", name); Utils.printClientUser(clientUser); } public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("DeactivateClientUsers") .build() .defaultHelp(true) .description(("Deactivate a client user with the given buyer, client, and user ID.")); parser .addArgument("-a", "--account_id") .help( "The resource ID of the buyers resource under which the parent client was created. " + "This will be used to construct the name used as a path parameter for the " + "users.deactivate request.") .required(true) .type(Integer.class); parser .addArgument("-c", "--client_id") .help( "The resource ID of the buyers.clients resource under which the client user was" + " created. This will be used to construct the name used as a path parameter for" + " the users.deactivate request.") .required(true); parser .addArgument("-u", "--client_user_id") .help( "The resource ID of the buyers.clients.users resource that is being deactivated. " + "This will be used to construct the name used as a path parameter for the " + "users.deactivate request.") .required(true); Namespace parsedArgs = null; try { parsedArgs = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } AuthorizedBuyersMarketplace client = null; try { client = Utils.getMarketplaceClient(); } catch (IOException ex) { System.out.printf("Unable to create Marketplace API service:%n%s", ex); System.out.println("Did you specify a valid path to a service account key file?"); System.exit(1); } catch (GeneralSecurityException ex) { System.out.printf("Unable to establish secure HttpTransport:%n%s", ex); System.exit(1); } execute(client, parsedArgs); } }
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/restapi/security/RestApiLoginFilter.java
17018
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.restapi.security; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.olat.admin.user.delete.service.UserDeletionManager; import org.olat.basesecurity.AuthHelper; import org.olat.basesecurity.BaseSecurityModule; import org.olat.core.CoreSpringFactory; import org.olat.core.commons.persistence.DBFactory; import org.olat.core.gui.UserRequest; import org.olat.core.gui.UserRequestImpl; import org.olat.core.helpers.Settings; import org.olat.core.id.Identity; import org.olat.core.id.Roles; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.core.logging.activity.ThreadLocalUserActivityLoggerInstaller; import org.olat.core.util.SessionInfo; import org.olat.core.util.StringHelper; import org.olat.core.util.UserSession; import org.olat.core.util.WebappHelper; import org.olat.core.util.i18n.I18nManager; import org.olat.core.util.session.UserSessionManager; import org.olat.login.auth.OLATAuthManager; import org.olat.restapi.RestModule; import com.oreilly.servlet.Base64Decoder; /** * * Description:<br> * Filter which protects the REST Api. * * <P> * Initial Date: 7 apr. 2010 <br> * @author srosse, stephane.rosse@frentix.com */ public class RestApiLoginFilter implements Filter { private static OLog log = Tracing.createLoggerFor(RestApiLoginFilter.class); private static final String BASIC_AUTH_REALM = "OLAT Rest API"; private static List<String> openUrls; private static List<String> alwaysEnabledUrls; private static List<String> ipProtectedUrls; private static String LOGIN_URL; /** * The survive time of the session used by token based authentication. For every request * is a new session created. */ private static int TOKEN_BASED_SESSION_TIMEOUT = 120; @Override public void init(FilterConfig filterConfig) { // } @Override public void destroy() { // } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException { if(request instanceof HttpServletRequest) { try { HttpServletRequest httpRequest = (HttpServletRequest)request; HttpServletResponse httpResponse = (HttpServletResponse)response; String requestURI = httpRequest.getRequestURI(); RestModule restModule = (RestModule)CoreSpringFactory.getBean("restModule"); if(restModule == null || !restModule.isEnabled() && !isRequestURIAlwaysEnabled(requestURI)) { httpResponse.sendError(403); return; } // initialize tracing with request, this allows debugging information as IP, User-Agent. Tracing.setUreq(httpRequest); I18nManager.attachI18nInfoToThread(httpRequest); ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(httpRequest); UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSessionIfAlreadySet(httpRequest); if(uress != null && uress.isAuthenticated()) { //use the available session followSession(httpRequest, httpResponse, chain); } else { if(isRequestURIInLoginSpace(requestURI)) { followForAuthentication(requestURI, uress, httpRequest, httpResponse, chain); } else if(isRequestURIInOpenSpace(requestURI)) { followWithoutAuthentication(httpRequest, httpResponse, chain); } else if( isRequestURIInIPProtectedSpace(requestURI, httpRequest, restModule)) { upgradeIpAuthentication(httpRequest, httpResponse); followWithoutAuthentication(httpRequest, httpResponse, chain); } else if (isRequestTokenValid(httpRequest)) { String token = httpRequest.getHeader(RestSecurityHelper.SEC_TOKEN); followToken(token, httpRequest, httpResponse, chain); } else if (isBasicAuthenticated(httpRequest, httpResponse, requestURI)) { followBasicAuthenticated(request, response, chain); } else { httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + BASIC_AUTH_REALM + "\""); httpResponse.sendError(401); } } } catch (Exception e) { log.error("", e); } finally { ThreadLocalUserActivityLoggerInstaller.resetUserActivityLogger(); I18nManager.remove18nInfoFromThread(); Tracing.setUreq(null); DBFactory.getInstance().commitAndCloseSession(); } } else { throw new ServletException("Only accept HTTP Request"); } } private boolean isBasicAuthenticated(HttpServletRequest request, HttpServletResponse response, String requestURI) { String authHeader = request.getHeader("Authorization"); if (authHeader != null) { StringTokenizer st = new StringTokenizer(authHeader); if (st.hasMoreTokens()) { String basic = st.nextToken(); // We only handle HTTP Basic authentication if (basic.equalsIgnoreCase("Basic")) { String credentials = st.nextToken(); String userPass = Base64Decoder.decode(credentials); // The decoded string is in the form "userID:password". int p = userPass.indexOf(":"); if (p != -1) { String username = userPass.substring(0, p); String password = userPass.substring(p + 1); OLATAuthManager olatAuthenticationSpi = CoreSpringFactory.getImpl(OLATAuthManager.class); Identity identity = olatAuthenticationSpi.authenticate(null, username, password); if(identity == null) { return false; } UserRequest ureq = null; try{ //upon creation URL is checked for ureq = new UserRequestImpl(requestURI, request, response); } catch(NumberFormatException nfe) { return false; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); int loginStatus = AuthHelper.doHeadlessLogin(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier(), ureq, true); if (loginStatus == AuthHelper.LOGIN_OK) { //fxdiff: FXOLAT-268 update last login date and register active user UserDeletionManager.getInstance().setIdentityAsActiv(identity); //Forge a new security token RestSecurityBean securityBean = (RestSecurityBean)CoreSpringFactory.getBean(RestSecurityBean.class); String token = securityBean.generateToken(identity, request.getSession()); response.setHeader(RestSecurityHelper.SEC_TOKEN, token); } return true; } } } } return false; } private void followBasicAuthenticated(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { chain.doFilter(request, response); } private boolean isRequestTokenValid(HttpServletRequest request) { String token = request.getHeader(RestSecurityHelper.SEC_TOKEN); RestSecurityBean securityBean = CoreSpringFactory.getImpl(RestSecurityBean.class); return securityBean.isTokenRegistrated(token, request.getSession(true)); } private boolean isRequestURIInLoginSpace(String requestURI) { String loginUrl = getLoginUrl(); if(loginUrl != null && requestURI.startsWith(loginUrl)) { return true; } return false; } private boolean isRequestURIInOpenSpace(String requestURI) { List<String> uris = getOpenURIs(); if(uris == null) return false; for(String openURI : uris) { if(requestURI.startsWith(openURI)) { return true; } } return false; } private boolean isRequestURIInIPProtectedSpace(String requestURI, HttpServletRequest httpRequest, RestModule restModule) { List<String> uris = getIPProtectedURIs(); if(uris == null) return false; for(String openURI : uris) { if(requestURI.startsWith(openURI)) { String remoteAddr = httpRequest.getRemoteAddr(); if(StringHelper.containsNonWhitespace(remoteAddr)) { return restModule.getIpsWithSystemAccess().contains(remoteAddr); } } } return false; } private boolean isRequestURIAlwaysEnabled(String requestURI) { List<String> uris = getAlwaysEnabledURIs(); if(uris == null) return false; for(String openURI : uris) { if(requestURI.startsWith(openURI)) { return true; } } return false; } private void followForAuthentication(String requestURI, UserSession uress, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { //create a session for login without security check if(uress == null) { uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(request); } UserRequest ureq = null; try{ //upon creation URL is checked for ureq = new UserRequestImpl(requestURI, request, response); } catch(NumberFormatException nfe) { response.sendError(401); return; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); chain.doFilter(request, response); } private void followWithoutAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSessionIfAlreadySet(request); if(uress != null && uress.isAuthenticated()) { //is authenticated by session cookie, follow its current session followSession(request, response, chain); return; } String token = request.getHeader(RestSecurityHelper.SEC_TOKEN); RestSecurityBean securityBean = (RestSecurityBean)CoreSpringFactory.getBean(RestSecurityBean.class); if(StringHelper.containsNonWhitespace(token) && securityBean.isTokenRegistrated(token, request.getSession(true))) { //is authenticated by token, follow its current token followToken(token, request, response, chain); return; } //fxdiff FXOLAT-113: business path in DMZ UserRequest ureq = null; try{ //upon creation URL is checked for String requestURI = request.getRequestURI(); ureq = new UserRequestImpl(requestURI, request, response); } catch(NumberFormatException nfe) { response.sendError(401); return; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); //no authentication, but no authentication needed, go further chain.doFilter(request, response); } private void upgradeIpAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { UserSessionManager sessionManager = CoreSpringFactory.getImpl(UserSessionManager.class); UserSession usess = sessionManager.getUserSessionIfAlreadySet(request); if(usess == null) { usess = sessionManager.getUserSession(request.getSession(true)); } if(usess.getIdentity() == null) { usess.setRoles(new Roles(false, false, false, false, false, false, false)); String remoteAddr = request.getRemoteAddr(); SessionInfo sinfo = new SessionInfo(new Long(-1), "REST", request.getSession()); sinfo.setFirstname("REST"); sinfo.setLastname(remoteAddr); sinfo.setFromIP(remoteAddr); sinfo.setFromFQN(remoteAddr); try { InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr()); if (iaddr.length > 0) sinfo.setFromFQN(iaddr[0].getHostName()); } catch (UnknownHostException e) { // ok, already set IP as FQDN } sinfo.setAuthProvider("IP"); sinfo.setUserAgent(request.getHeader("User-Agent")); sinfo.setSecure(request.isSecure()); sinfo.setREST(true); sinfo.setWebModeFromUreq(null); // set session info for this session usess.setSessionInfo(sinfo); } UserRequest ureq = null; try{ //upon creation URL is checked for String requestURI = request.getRequestURI(); ureq = new UserRequestImpl(requestURI, request, response); ureq.getUserSession().putEntryInNonClearedStore(RestSecurityHelper.SYSTEM_MARKER, Boolean.TRUE); } catch(NumberFormatException nfe) { response.sendError(401); return; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); } private void followToken(String token, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { HttpSession session = request.getSession(true); session.setMaxInactiveInterval(TOKEN_BASED_SESSION_TIMEOUT); UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(session); if(uress != null) { UserRequest ureq = null; try{ //upon creation URL is checked for String requestURI = request.getRequestURI(); ureq = new UserRequestImpl(requestURI, request, response); } catch(Exception e) { response.sendError(500); return; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); RestSecurityBean securityBean = (RestSecurityBean)CoreSpringFactory.getBean(RestSecurityBean.class); Identity identity = securityBean.getIdentity(token); int loginStatus = AuthHelper.doHeadlessLogin(identity, BaseSecurityModule.getDefaultAuthProviderIdentifier(), ureq, true); if(loginStatus == AuthHelper.LOGIN_OK) { response.setHeader(RestSecurityHelper.SEC_TOKEN, securityBean.renewToken(token)); synchronized(uress) { chain.doFilter(request, response); } } else response.sendError(401); } else response.sendError(401); } private void followSession(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { UserSession uress = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSessionIfAlreadySet(request); if(uress != null && uress.isAuthenticated()) { UserRequest ureq = null; try{ //upon creation URL is checked for String requestURI = request.getRequestURI(); ureq = new UserRequestImpl(requestURI, request, response); } catch(NumberFormatException nfe) { response.sendError(401); return; } request.setAttribute(RestSecurityHelper.SEC_USER_REQUEST, ureq); synchronized(uress) { chain.doFilter(request, response); } } else { response.sendError(401); } } private boolean isWebappHelperInitiated() { if(Settings.isJUnitTest()) { return true; } return WebappHelper.getServletContextPath() != null; } private String getLoginUrl() { if(LOGIN_URL == null && isWebappHelperInitiated()) { String context = (Settings.isJUnitTest() ? "/olat" : WebappHelper.getServletContextPath() + RestSecurityHelper.SUB_CONTEXT); LOGIN_URL = context + "/auth"; } return LOGIN_URL; } private List<String> getAlwaysEnabledURIs() { if(alwaysEnabledUrls == null && isWebappHelperInitiated() ) { String context = (Settings.isJUnitTest() ? "/olat" : WebappHelper.getServletContextPath() + RestSecurityHelper.SUB_CONTEXT); List<String > urls = new ArrayList<String>(); urls.add(context + "/i18n"); urls.add(context + "/api"); urls.add(context + "/ping"); urls.add(context + "/openmeetings"); urls.add(context + "/system"); alwaysEnabledUrls = urls; } return alwaysEnabledUrls; } private List<String> getOpenURIs() { if(openUrls == null && isWebappHelperInitiated()) { String context = (Settings.isJUnitTest() ? "/olat" : WebappHelper.getServletContextPath() + RestSecurityHelper.SUB_CONTEXT); List<String > urls = new ArrayList<String>(); urls.add(context + "/i18n"); urls.add(context + "/api"); urls.add(context + "/ping"); urls.add(context + "/application.wadl"); urls.add(context + "/application.html"); urls.add(context + "/wadl"); urls.add(context + "/registration"); urls.add(context + "/openmeetings"); openUrls = urls; } return openUrls; } private List<String> getIPProtectedURIs() { if(ipProtectedUrls == null && isWebappHelperInitiated()) { String context = (Settings.isJUnitTest() ? "/olat" : WebappHelper.getServletContextPath() + RestSecurityHelper.SUB_CONTEXT); List<String > urls = new ArrayList<String>(); urls.add(context + "/system"); ipProtectedUrls = urls; } return ipProtectedUrls; } }
apache-2.0
iWay7/Helpers
helpers/src/main/java/site/iway/helpers/BitmapSourceResource.java
769
package site.iway.helpers; public class BitmapSourceResource extends BitmapSource { int resourceId; public BitmapSourceResource(int resId, BitmapFilter filter) { super(filter); resourceId = resId; } public BitmapSourceResource(int resId) { super(null); resourceId = resId; } public int getResourceId() { return resourceId; } @Override public boolean isValid() { return resourceId >= 0; } @Override public boolean equals(Object o) { if (o instanceof BitmapSourceResource) { BitmapSourceResource other = (BitmapSourceResource) o; return filter == other.filter && resourceId == other.resourceId; } return false; } }
apache-2.0
jessemull/MicroFlex
src/test/java/com/github/jessemull/microflex/stat/statinteger/MeanIntegerTest.java
24956
/** * 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 --------------------------------- */ package com.github.jessemull.microflex.stat.statinteger; /* ------------------------------ Dependencies ------------------------------ */ import static org.junit.Assert.*; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.TreeMap; import java.util.Map; import java.util.Random; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.Precision; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.github.jessemull.microflex.integerflex.plate.PlateInteger; import com.github.jessemull.microflex.integerflex.plate.WellInteger; import com.github.jessemull.microflex.integerflex.plate.WellSetInteger; import com.github.jessemull.microflex.integerflex.stat.MeanInteger; import com.github.jessemull.microflex.util.RandomUtil; /** * This class tests the methods in the mean integer class. * @author Jesse L. Mull * @update Updated Oct 18, 2016 * @address http://www.jessemull.com * @email hello@jessemull.com */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MeanIntegerTest { /* ---------------------------- Local Fields -----------------------------*/ /* Minimum and maximum values for random well and lists */ private static int minValue = 0; // Minimum integer value for wells private static int maxValue = 100; // Maximum integer value for wells private static Random random = new Random(); // Generates random integers private static int precision = 10; // Precision for double results /* The addition operation */ private static MeanInteger mean = new MeanInteger(); /* Random objects and numbers for testing */ private static int rows = 5; private static int columns = 4; private static int length = 5; private static int lengthIndices = 10; private static int plateNumber = 10; private static int plateNumberIndices = 5; private static PlateInteger[] array = new PlateInteger[plateNumber]; private static PlateInteger[] arrayIndices = new PlateInteger[plateNumberIndices]; /* Value of false redirects System.err */ private static boolean error = true; private static PrintStream originalOut = System.out; /** * Generates random objects and numbers for testing. */ @BeforeClass public static void setUp() { if(error) { System.setErr(new PrintStream(new OutputStream() { public void write(int x) {} })); } for(int j = 0; j < array.length; j++) { PlateInteger plate = RandomUtil.randomPlateInteger( rows, columns, minValue, maxValue, length, "Plate1-" + j); array[j] = plate; } for(int j = 0; j < arrayIndices.length; j++) { PlateInteger plateIndices = RandomUtil.randomPlateInteger( rows, columns, minValue, maxValue, lengthIndices, "Plate1-" + j); arrayIndices[j] = plateIndices; } } /** * Toggles system error. */ @AfterClass public static void restoreErrorOut() { System.setErr(originalOut); } /* ---------------------------- Constructors -----------------------------*/ /** * Tests the default constructor. */ @Test public void testConstructor() { MeanInteger test = new MeanInteger(); assertNotNull(test); } /* ---------------- Well statistics for all plate wells ----------------- */ /** * Tests the plate statistics method. */ @Test public void testPlate() { for(PlateInteger plate : array) { Map<WellInteger, Double> resultMap = new TreeMap<WellInteger, Double>(); Map<WellInteger, Double> returnedMap = mean.plate(plate); for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } DescriptiveStatistics stat = new DescriptiveStatistics(input); double result = stat.getMean(); resultMap.put(well, result); } for(WellInteger well : plate) { double result = Precision.round(resultMap.get(well), precision); double returned = Precision.round(returnedMap.get(well), precision); assertTrue(result == returned); } } } /** * Tests the plate statistics method using the values between the indices. */ @Test public void testPlateIndices() { for(PlateInteger plate : arrayIndices) { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); Map<WellInteger, Double> resultMap = new TreeMap<WellInteger, Double>(); Map<WellInteger, Double> returnedMap = mean.plate(plate, begin, end - begin); for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } DescriptiveStatistics stat = new DescriptiveStatistics(ArrayUtils.subarray(input, begin, end)); double result = stat.getMean(); resultMap.put(well, result); } for(WellInteger well : plate) { double result = Precision.round(resultMap.get(well), precision); double returned = Precision.round(returnedMap.get(well), precision); assertTrue(result == returned); } } } /* --------------------- Aggregated plate statistics ------------------- */ /** * Tests the aggregated plate statistics method. */ @Test public void testAggregatedPlate() { for(PlateInteger plate : array) { List<Double> resultList = new ArrayList<Double>(); double aggregatedReturned = Precision.round(mean.platesAggregated(plate), precision); for(WellInteger well : plate) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double resultAggregated = Precision.round(statAggregated.getMean(), precision); assertTrue(resultAggregated == aggregatedReturned); } } /** * Tests the aggregated plate statistics method using a collection. */ @Test public void testAggregatedPlateCollection() { List<PlateInteger> collection = Arrays.asList(array); Map<PlateInteger, Double> aggregatedReturnedMap = mean.platesAggregated(collection); Map<PlateInteger, Double> aggregatedResultMap = new TreeMap<PlateInteger, Double>(); for(PlateInteger plate : collection) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : plate) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(plate, aggregatedResult); } for(PlateInteger plate : collection) { double result = Precision.round(aggregatedResultMap.get(plate), precision); double returned = Precision.round(aggregatedReturnedMap.get(plate), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using an array. */ @Test public void testAggregatedPlateArray() { Map<PlateInteger, Double> aggregatedReturnedMap = mean.platesAggregated(array); Map<PlateInteger, Double> aggregatedResultMap = new TreeMap<PlateInteger, Double>(); for(PlateInteger plate : array) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : plate) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(plate, aggregatedResult); } for(PlateInteger plate : array) { double result = Precision.round(aggregatedResultMap.get(plate), precision); double returned = Precision.round(aggregatedReturnedMap.get(plate), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using the values between the indices. */ @Test public void testAggregatedPlateIndices() { for(PlateInteger plate : arrayIndices) { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); List<Double> resultList = new ArrayList<Double>(); double aggregatedReturned = Precision.round(mean.platesAggregated(plate, begin, end - begin), precision); for(WellInteger well : plate) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = Precision.round(statAggregated.getMean(), precision); assertTrue(aggregatedResult == aggregatedReturned); } } /** * Tests the aggregated plate statistics method using the values between the indices of * the collection. */ @Test public void testAggregatedPlateCollectionIndices() { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); List<PlateInteger> collection = Arrays.asList(arrayIndices); Map<PlateInteger, Double> aggregatedReturnedMap = mean.platesAggregated(collection, begin, end - begin); Map<PlateInteger, Double> aggregatedResultMap = new TreeMap<PlateInteger, Double>(); for(PlateInteger plate : collection) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : plate) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double resultAggregated = statAggregated.getMean(); aggregatedResultMap.put(plate, resultAggregated); } for(PlateInteger plate : collection) { double result = Precision.round(aggregatedResultMap.get(plate), precision); double returned = Precision.round(aggregatedReturnedMap.get(plate), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using the values between the indices of * the array. */ @Test public void testAggregatedPlateArrayIndices() { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); Map<PlateInteger, Double> aggregatedReturnedMap = mean.platesAggregated(arrayIndices, begin, end - begin); Map<PlateInteger, Double> aggregatedResultMap = new TreeMap<PlateInteger, Double>(); for(PlateInteger plate : arrayIndices) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : plate) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(plate, aggregatedResult); } for(PlateInteger plate : arrayIndices) { double result = Precision.round(aggregatedResultMap.get(plate), precision); double returned = Precision.round(aggregatedReturnedMap.get(plate), precision); assertTrue(result == returned); } } /* --------------- Well statistics for all wells in a set -------------- */ /** * Tests set calculation. */ @Test public void testSet() { for(PlateInteger plate : array) { Map<WellInteger, Double> resultMap = new TreeMap<WellInteger, Double>(); Map<WellInteger, Double> returnedMap = mean.set(plate.dataSet()); for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } DescriptiveStatistics stat = new DescriptiveStatistics(input); double result = stat.getMean(); resultMap.put(well, result); } for(WellInteger well : plate) { double result = Precision.round(resultMap.get(well), precision); double returned = Precision.round(returnedMap.get(well), precision); assertTrue(result == returned); } } } /** * Tests set calculation using indices. */ @Test public void testSetIndices() { for(PlateInteger plate : arrayIndices) { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); Map<WellInteger, Double> resultMap = new TreeMap<WellInteger, Double>(); Map<WellInteger, Double> returnedMap = mean.set(plate.dataSet(), begin, end - begin); for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } DescriptiveStatistics stat = new DescriptiveStatistics(ArrayUtils.subarray(input, begin, end)); double result = stat.getMean(); resultMap.put(well, result); } for(WellInteger well : plate) { double result = Precision.round(resultMap.get(well), precision); double returned = Precision.round(returnedMap.get(well), precision); assertTrue(result == returned); } } } /* ---------------------- Aggregated set statistics -------------------- */ /** * Tests the aggregated plate statistics method. */ @Test public void testAggregatedSet() { for(PlateInteger plate : array) { List<Double> resultList = new ArrayList<Double>(); double aggregatedReturned = Precision.round(mean.setsAggregated(plate.dataSet()), precision); for(WellInteger well : plate) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double resultAggregated = Precision.round(statAggregated.getMean(), precision); assertTrue(resultAggregated == aggregatedReturned); } } /** * Tests the aggregated plate statistics method using a collection. */ @Test public void testAggregatedSetCollection() { List<WellSetInteger> collection = new ArrayList<WellSetInteger>(); for(PlateInteger plate : array) { collection.add(plate.dataSet()); } Map<WellSetInteger, Double> aggregatedReturnedMap = mean.setsAggregated(collection); Map<WellSetInteger, Double> aggregatedResultMap = new TreeMap<WellSetInteger, Double>(); for(WellSetInteger set : collection) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : set) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(set, aggregatedResult); } for(WellSetInteger set : collection) { double result = Precision.round(aggregatedResultMap.get(set), precision); double returned = Precision.round(aggregatedReturnedMap.get(set), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using an array. */ @Test public void testAggregatedSetArray() { WellSetInteger[] setArray = new WellSetInteger[array.length]; for(int i = 0; i < setArray.length; i++) { setArray[i] = array[i].dataSet(); } Map<WellSetInteger, Double> aggregatedReturnedMap = mean.setsAggregated(setArray); Map<WellSetInteger, Double> aggregatedResultMap = new TreeMap<WellSetInteger, Double>(); for(WellSetInteger set : setArray) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : set) { resultList.addAll(well.toDouble()); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(set, aggregatedResult); } for(WellSetInteger set : setArray) { double result = Precision.round(aggregatedResultMap.get(set), precision); double returned = Precision.round(aggregatedReturnedMap.get(set), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using the values between the indices. */ @Test public void testAggregatedSetIndices() { for(PlateInteger plate : arrayIndices) { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); List<Double> resultList = new ArrayList<Double>(); double aggregatedReturned = Precision.round(mean.setsAggregated(plate.dataSet(), begin, end - begin), precision); for(WellInteger well : plate) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double resultAggregated = Precision.round(statAggregated.getMean(), precision); assertTrue(resultAggregated == aggregatedReturned); } } /** * Tests the aggregated plate statistics method using the values between the indices of * the collection. */ @Test public void testAggregatedSetCollectionIndices() { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); List<WellSetInteger> collection = new ArrayList<WellSetInteger>(); for(PlateInteger plate : arrayIndices) { collection.add(plate.dataSet()); } Map<WellSetInteger, Double> aggregatedReturnedMap = mean.setsAggregated(collection, begin, end - begin); Map<WellSetInteger, Double> aggregatedResultMap = new TreeMap<WellSetInteger, Double>(); for(WellSetInteger set : collection) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : set) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(set, aggregatedResult); } for(WellSetInteger set : collection) { double result = Precision.round(aggregatedResultMap.get(set), precision); double returned = Precision.round(aggregatedReturnedMap.get(set), precision); assertTrue(result == returned); } } /** * Tests the aggregated plate statistics method using the values between the indices of * the array. */ @Test public void testAggregatedSetArrayIndices() { int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); WellSetInteger[] setArrayIndices = new WellSetInteger[arrayIndices.length]; for(int i = 0; i < setArrayIndices.length; i++) { setArrayIndices[i] = arrayIndices[i].dataSet(); } Map<WellSetInteger, Double> aggregatedReturnedMap = mean.setsAggregated(setArrayIndices, begin, end - begin); Map<WellSetInteger, Double> aggregatedResultMap = new TreeMap<WellSetInteger, Double>(); for(WellSetInteger set : setArrayIndices) { List<Double> resultList = new ArrayList<Double>(); for(WellInteger well : set) { resultList.addAll(well.toDouble().subList(begin, end)); } double[] inputAggregated = new double[resultList.size()]; for(int i = 0; i < resultList.size(); i++) { inputAggregated[i] = resultList.get(i); } DescriptiveStatistics statAggregated = new DescriptiveStatistics(inputAggregated); double aggregatedResult = statAggregated.getMean(); aggregatedResultMap.put(set, aggregatedResult); } for(WellSetInteger plate : setArrayIndices) { double result = Precision.round(aggregatedResultMap.get(plate), precision); double returned = Precision.round(aggregatedReturnedMap.get(plate), precision); assertTrue(result == returned); } } /* -------------------------- Well statistics -------------------------- */ /** * Tests well calculation. */ @Test public void testWell() { for(PlateInteger plate : array) { for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } DescriptiveStatistics stat = new DescriptiveStatistics(input); double result = Precision.round(stat.getMean(), precision); double returned = Precision.round(mean.well(well), precision); assertTrue(result == returned); } } } /** * Tests well calculation using indices. */ @Test public void testWellIndices() { for(PlateInteger plate : arrayIndices) { for(WellInteger well : plate) { double[] input = new double[well.size()]; int index = 0; for(double bd : well) { input[index++] = bd;; } int size = arrayIndices[0].first().size(); int begin = random.nextInt(size - 5); int end = (begin + 4) + random.nextInt(size - (begin + 4) + 1); DescriptiveStatistics stat = new DescriptiveStatistics(ArrayUtils.subarray(input, begin, end)); double result = Precision.round(stat.getMean(), precision); double returned = Precision.round(mean.well(well, begin, end - begin), precision); assertTrue(result == returned); } } } }
apache-2.0