repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
alexruiz/fest-assert-1.x | src/test/java/org/fest/assertions/BooleanAssert_constructorsForPrimitiveAndWrapper_Test.java | 1281 | /*
* Created on Apr 15, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.assertions;
/**
* Tests for {@link BooleanAssert#BooleanAssert(boolean)} and {@link BooleanAssert#BooleanAssert(Boolean)}.
*
* @author Ansgar Konermann
* @author Alex Ruiz
*/
public class BooleanAssert_constructorsForPrimitiveAndWrapper_Test extends
GenericAssert_constructorsForPrimitiveAndWrapper_TestCase<BooleanAssert, Boolean> {
@Override
protected Class<BooleanAssert> assertionType() {
return BooleanAssert.class;
}
@Override
protected Class<?> primitiveType() {
return boolean.class;
}
@Override
protected Class<Boolean> primitiveWrapperType() {
return Boolean.class;
}
}
| apache-2.0 |
krotscheck/storm-toolkit | storm-toolkit-core/src/main/java/net/krotscheck/stk/stream/package-info.java | 683 | /*
* Copyright (c) 2015 Michael Krotscheck
*
* 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.
*/
/**
* Schema management components.
*/
package net.krotscheck.stk.stream;
| apache-2.0 |
Qi4j/qi4j-libraries | rest-server/src/main/java/org/qi4j/library/rest/server/api/constraint/InteractionConstraint.java | 915 | /**
*
* Copyright 2009-2011 Rickard Öberg AB
*
* 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.qi4j.library.rest.server.api.constraint;
import org.qi4j.library.rest.server.api.ObjectSelection;
/**
* JAVADOC
*/
public interface InteractionConstraint<ANNOTATION extends java.lang.annotation.Annotation>
{
boolean isValid(ANNOTATION annotation, ObjectSelection objectSelection );
}
| apache-2.0 |
McLeodMoores/starling | projects/analytics/src/main/java/com/opengamma/analytics/financial/credit/obligor/definition/IndividualClearingMember.java | 2148 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.credit.obligor.definition;
import com.opengamma.analytics.financial.credit.obligor.CreditRating;
import com.opengamma.analytics.financial.credit.obligor.CreditRatingFitch;
import com.opengamma.analytics.financial.credit.obligor.CreditRatingMoodys;
import com.opengamma.analytics.financial.credit.obligor.CreditRatingStandardAndPoors;
import com.opengamma.analytics.financial.credit.obligor.Region;
import com.opengamma.analytics.financial.credit.obligor.Sector;
/**
* Class to define an Individual Clearing Member of a CCP (an extension of the Obligor class).
*
* @deprecated Deprecated
*/
@Deprecated
public class IndividualClearingMember extends Obligor {
// ----------------------------------------------------------------------------------------------------------------------------------------
public IndividualClearingMember(
final String obligorTicker,
final String obligorShortName,
final String obligorREDCode,
final CreditRating compositeRating,
final CreditRating impliedRating,
final CreditRatingMoodys moodysCreditRating,
final CreditRatingStandardAndPoors standardAndPoorsCreditRating,
final CreditRatingFitch fitchCreditRating,
final boolean hasDefaulted,
final Sector sector,
final Region region,
final String country) {
// ----------------------------------------------------------------------------------------------------------------------------------------
super(obligorTicker, obligorShortName, obligorREDCode, compositeRating, impliedRating, moodysCreditRating, standardAndPoorsCreditRating, fitchCreditRating,
hasDefaulted, sector, region, country);
// ----------------------------------------------------------------------------------------------------------------------------------------
}
// ----------------------------------------------------------------------------------------------------------------------------------------
}
| apache-2.0 |
dongjunpeng/whale | src/main/java/com/buterfleoge/whale/log/interceptor/LogPointcut.java | 3099 | package com.buterfleoge.whale.log.interceptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
*
* 外部服务代理切点定义
*
* @author xiezhenzong
*
*/
public class LogPointcut extends StaticMethodMatcherPointcut {
private static final String SPLITOR = ",";
private static final Object OBJ = new Object();
/**
* 需要代理的方法集合,把map当作set用
*/
private Map<String, Object> proxyMethods = new ConcurrentHashMap<String, Object>();
/**
* 构造代理的切面
*
* @param service 需要代理的接口的方法
* @param serviceMethodSet method set
* @param serviceMethods method
*/
public LogPointcut(String service, Set<String> serviceMethodSet, String serviceMethods) {
addServiceMethod(service);
addMethodSet(serviceMethodSet);
addMethods(serviceMethods);
if (proxyMethods.isEmpty()) {
throw new IllegalArgumentException("No any proxy method!");
}
}
/**
* 从外部服务的接口中添加要代理的方法
*
* @param service 外部服务的接口
*/
private void addServiceMethod(String service) {
try {
Class<?> clazz = Class.forName(service);
if (!clazz.isInterface()) {
throw new IllegalArgumentException("Must be a interface, service: " + service);
}
Method[] methods = clazz.getMethods();
if (methods.length > 0) {
for (Method method : methods) {
proxyMethods.put(method.getName(), OBJ);
}
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Can't load class: " + service);
}
}
/**
*
* 从集合配置中添加要代理的方法
*
* @param serviceMethodSet 需要代理的方法集合
*/
private void addMethodSet(Set<String> serviceMethodSet) {
if (!CollectionUtils.isEmpty(serviceMethodSet)) {
for (String method : serviceMethodSet) {
proxyMethods.put(method, OBJ);
}
}
}
/**
* 从配置中添加需要代理的方法,可以用","来分隔
*
* @param serviceMethods 需要代理的方法
*/
private void addMethods(String serviceMethods) {
if (!StringUtils.isEmpty(serviceMethods)) {
String[] methods = serviceMethods.split(SPLITOR);
for (String method : methods) {
proxyMethods.put(method, OBJ);
}
}
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return proxyMethods.containsKey(method.getName());
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/internal/SdkPredicate.java | 975 | /*
* Copyright 2010-2019 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.internal;
/**
* Similar to Predicate functional interface in Java 8
*/
public abstract class SdkPredicate<T> {
/**
* Evaluates this predicate on the given argument
*
* @param t
* The input argument
* @return true if the input argument matches the predicate, otherwise false
*/
public abstract boolean test(T t);
}
| apache-2.0 |
evenjn/yarn | src/main/java/org/github/evenjn/yarn/RingFunction.java | 1589 | /**
*
* Copyright 2017 Marco Trevisan
*
* 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.github.evenjn.yarn;
import org.github.evenjn.lang.Rook;
/**
* <p>
* Returns an object associated to the argument object after passing the
* responsibility to close associated resources to the argument
* {@link org.github.evenjn.lang.Rook Rook}.
* </p>
*
* <p>
* This interface is part of package {@link org.github.evenjn.yarn Yarn}.
* </p>
*
* @param <I>
* The type of input objects.
* @param <O>
* The type of output objects.
* @since 1.0
*/
@FunctionalInterface
public interface RingFunction<I, O> {
/**
* <p>
* {@code get} returns an object associated to the argument object after
* passing the responsibility to close associated resources to the argument
* {@link org.github.evenjn.lang.Rook Rook}.
* </p>
*
* @param rook
* A {@link org.github.evenjn.lang.Rook Rook}.
* @param object
* An input object.
* @return An output object.
* @since 1.0
*/
O apply( Rook rook, I object );
}
| apache-2.0 |
Eventasia/eventasia | eventasia-store-dynamodb/src/main/java/com/github/eventasia/dynamodb/EventasiaDynamoDBConfig.java | 1530 | package com.github.eventasia.dynamodb;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class EventasiaDynamoDBConfig {
private DynamoDB dynamoDB;
private DynamoDBMapper mapper;
@Value("${eventasia.dynamodb.region}")
private String region;
@Value("${eventasia.dynamodb.accessKey}")
private String accessKey;
@Value("${eventasia.dynamodb.secretKey}")
private String secretKey;
@PostConstruct
public void connect(){
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonDynamoDB client = AmazonDynamoDBAsyncClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
.build();
dynamoDB = new DynamoDB(client);
mapper = new DynamoDBMapper(client);
}
public DynamoDB getDynamoDB() {
return dynamoDB;
}
public DynamoDBMapper getMapper() {
return mapper;
}
}
| apache-2.0 |
McLeodMoores/starling | projects/engine/src/main/java/com/opengamma/engine/function/NoOpFunction.java | 1712 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.function;
import java.util.Set;
import com.google.common.collect.Sets;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.cache.MissingOutput;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
/**
* A no-op function. This will never be selected during graph construction, but can be present in an execution plan as a placeholder for a suppressed function.
* <p>
* This should be present in all function repositories with its preferred identifier.
*/
public final class NoOpFunction extends IntrinsicFunction {
/**
* Shared instance.
*/
public static final NoOpFunction INSTANCE = new NoOpFunction();
/**
* Preferred identifier this function will be available in a repository as.
*/
public static final String UNIQUE_ID = "No-op";
public NoOpFunction() {
super(UNIQUE_ID);
}
// FunctionInvoker
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) {
final Set<ComputedValue> result = Sets.newHashSetWithExpectedSize(desiredValues.size());
for (final ValueRequirement desiredValue : desiredValues) {
result.add(new ComputedValue(new ValueSpecification(desiredValue.getValueName(), target.toSpecification(), desiredValue.getConstraints()),
MissingOutput.SUPPRESSED));
}
return result;
}
}
| apache-2.0 |
gbif/checklistbank | checklistbank-cli/src/main/java/org/gbif/checklistbank/kryo/URISerializer.java | 1207 | /*
* 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.gbif.checklistbank.kryo;
import java.net.URI;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
public class URISerializer extends Serializer<URI> {
public URISerializer() {
setImmutable(true);
}
@Override
public void write(final Kryo kryo, final Output output, final URI uri) {
output.writeString(uri.toString());
}
@Override
public URI read(final Kryo kryo, final Input input, final Class<URI> uriClass) {
return URI.create(input.readString());
}
} | apache-2.0 |
Shivam101/SachinApp-Android | src/com/shivamb7/sachinapp/ImageTask.java | 924 | package com.shivamb7.sachinapp;
import java.io.IOException;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
class ImageTask extends AsyncTask<Void, Void, Void>
{
Context c;
ProgressDialog pd;
public ImageTask(Context ctx)
{
this.c=ctx;
}
@Override
protected void onPreExecute()
{
pd=ProgressDialog.show(c, "Please Wait", "Setting Wallpaper...");
}
protected void onPostExecute(Void result)
{
pd.dismiss();
Toast.makeText(c, "Wallpaper set successfully", Toast.LENGTH_SHORT).show();
}
protected Void doInBackground(Void... params) {
WallpaperManager wm1=WallpaperManager.getInstance(c);
try {
wm1.setBitmap(ImageFrag1.bmg1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
} | apache-2.0 |
vladimir-bukhtoyarov/bucket4j | bucket4j-core/src/main/java/io/github/bucket4j/distributed/proxy/generic/compare_and_swap/AsyncCompareAndSwapOperation.java | 1955 | /*-
* ========================LICENSE_START=================================
* Bucket4j
* %%
* Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package io.github.bucket4j.distributed.proxy.generic.compare_and_swap;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Describes the set of operations that {@link AbstractCompareAndSwapBasedProxyManager} typically performs in reaction to user request.
* The typical flow is following:
* <ol>
* <li>getStateData - {@link #getStateData()}</li>
* <li>compareAndSwap - {@link #compareAndSwap(byte[], byte[])}</li>
* <li>Return to first step if CAS was unsuccessful</li>
* </ol>
*/
public interface AsyncCompareAndSwapOperation {
/**
* Reads data if it exists
*
* @return persisted data or empty optional if data not exists
*/
CompletableFuture<Optional<byte[]>> getStateData();
/**
* Compares and swap data associated with key
*
* @param originalData previous bucket state(can be null).
* @param newData new bucket state
*
* @return {@code true} if data changed, {@code false} if another parallel transaction achieved success instead of current transaction
*/
CompletableFuture<Boolean> compareAndSwap(byte[] originalData, byte[] newData);
}
| apache-2.0 |
cherrymathew/evend | android/test/src/foo/fruitfox/data/test/TalkDataTest.java | 3196 | package foo.fruitfox.data.test;
import junit.framework.TestCase;
import org.joda.time.DateTime;
import foo.fruitfox.data.TalkData;
public class TalkDataTest extends TestCase {
TalkData talkData;
public TalkDataTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
this.talkData = new TalkData("Title 1", "2015-01-01");
}
public void testTalkDataConstructor1() {
TalkData testTalkData = new TalkData();
assertEquals("title did not match", "", testTalkData.getTitle());
}
public void testTalkDataConstructor2() {
TalkData testTalkData = new TalkData("Title");
assertEquals("title did not match", "Title", testTalkData.getTitle());
}
public void testTalkDataConstructor3() {
TalkData testTalkData = new TalkData("Title", "2015-01-01");
assertEquals("title did not match", "Title", testTalkData.getTitle());
assertEquals("date did not match", "2015-01-01",
testTalkData.getDate("yyyy-MM-dd"));
}
public void testTalkDataMemberTile() {
String title = "Example Title";
talkData.setTitle(title);
assertEquals("title did not match", title, talkData.getTitle());
}
public void testTalkDataMemberDescription() {
String description = "Example Description";
talkData.setDescription(description);
assertEquals("description did not match", description,
talkData.getDescription());
}
public void testTalkDataMemberType() {
String type = "Example Type";
talkData.setType(type);
assertEquals("type did not match", type, talkData.getType());
}
public void testTalkDataMemberDuration() {
String duration = "120 min";
talkData.setDuration(duration);
assertEquals("duration did not match", "120 min",
talkData.getDuration());
}
public void testTalkDataMemberLocation() {
String location = "Example location";
talkData.setLocation(location);
assertEquals("location did not match", "Example location",
talkData.getLocation());
}
public void testTalkDataMemberEditLink() {
String editLink = "http://www.google.com/";
talkData.setEditLink(editLink);
assertEquals("editLink did not much", editLink, talkData.getEditLink());
}
public void testTalkDataMemberViewLink() {
String viewLink = "http://www.google.com";
talkData.setViewLink(viewLink);
assertEquals("viewLink did not match", viewLink, talkData.getViewLink());
}
public void testTalkDataMemberDate() {
DateTime date = new DateTime("2015-01-01");
talkData.setDate(date);
assertEquals("date object did not match", date, talkData.getDate());
assertEquals("date value did not match", date.toString("yyyy-MM-dd"),
talkData.getDate().toString("yyyy-MM-dd"));
}
public void testTalkDataMethodGetDate() {
DateTime date = new DateTime("2015-01-01");
String dateString = "2015-01-01";
String pattern = "yyyy-MM-dd";
talkData.setDate(date);
assertEquals("date value did not match", dateString,
talkData.getDate(pattern));
}
public void testTalkDataMethodSetDate() {
String date = "2015-01-01";
String pattern = "yyyy-MM-dd";
talkData.setDate(pattern, date);
assertEquals("date value did not match", date, talkData.getDate()
.toString(pattern));
}
}
| apache-2.0 |
felipejm/Scaffold | core/src/main/java/br/com/joffer/scaffold/generator/JavaProjectGenerator.java | 353 | package br.com.joffer.scaffold.generator;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Service
@Component
public class JavaProjectGenerator extends BasicGenerator {
private String[] basicDirs = new String[] { "src/main/java",
"src/main/resources","src/test/java","src/test/resources" };
}
| apache-2.0 |
Haulmont/GoogleMapsVaadin7 | googlemaps/src/main/java/com/vaadin/tapio/googlemaps/client/events/doubleclick/CircleDoubleClickListener.java | 279 | package com.vaadin.tapio.googlemaps.client.events.doubleclick;
import com.vaadin.tapio.googlemaps.client.overlays.GoogleMapCircle;
/**
* @author korotkov
* @version $Id$
*/
public interface CircleDoubleClickListener {
void circleDoubleClicked(GoogleMapCircle circle);
}
| apache-2.0 |
kisskys/incubator-asterixdb-hyracks | hyracks/hyracks-storage-am-lsm-common/src/main/java/org/apache/hyracks/storage/am/lsm/common/impls/LSMOperationType.java | 988 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.lsm.common.impls;
public enum LSMOperationType {
SEARCH,
MODIFICATION,
FORCE_MODIFICATION,
FLUSH,
MERGE,
REPLICATE
}
| apache-2.0 |
googleapis/java-aiplatform | proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/UpdateModelDeploymentMonitoringJobRequestOrBuilder.java | 7239 | /*
* 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
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/job_service.proto
package com.google.cloud.aiplatform.v1;
public interface UpdateModelDeploymentMonitoringJobRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.UpdateModelDeploymentMonitoringJobRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The model monitoring configuration which replaces the resource on the
* server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ModelDeploymentMonitoringJob model_deployment_monitoring_job = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the modelDeploymentMonitoringJob field is set.
*/
boolean hasModelDeploymentMonitoringJob();
/**
*
*
* <pre>
* Required. The model monitoring configuration which replaces the resource on the
* server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ModelDeploymentMonitoringJob model_deployment_monitoring_job = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The modelDeploymentMonitoringJob.
*/
com.google.cloud.aiplatform.v1.ModelDeploymentMonitoringJob getModelDeploymentMonitoringJob();
/**
*
*
* <pre>
* Required. The model monitoring configuration which replaces the resource on the
* server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ModelDeploymentMonitoringJob model_deployment_monitoring_job = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.aiplatform.v1.ModelDeploymentMonitoringJobOrBuilder
getModelDeploymentMonitoringJobOrBuilder();
/**
*
*
* <pre>
* Required. The update mask is used to specify the fields to be overwritten in the
* ModelDeploymentMonitoringJob resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* For the objective config, the user can either provide the update mask for
* model_deployment_monitoring_objective_configs or any combination of its
* nested fields, such as:
* model_deployment_monitoring_objective_configs.objective_config.training_dataset.
* Updatable fields:
* * `display_name`
* * `model_deployment_monitoring_schedule_config`
* * `model_monitoring_alert_config`
* * `logging_sampling_strategy`
* * `labels`
* * `log_ttl`
* * `enable_monitoring_pipeline_logs`
* . and
* * `model_deployment_monitoring_objective_configs`
* . or
* * `model_deployment_monitoring_objective_configs.objective_config.training_dataset`
* * `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config`
* * `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
boolean hasUpdateMask();
/**
*
*
* <pre>
* Required. The update mask is used to specify the fields to be overwritten in the
* ModelDeploymentMonitoringJob resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* For the objective config, the user can either provide the update mask for
* model_deployment_monitoring_objective_configs or any combination of its
* nested fields, such as:
* model_deployment_monitoring_objective_configs.objective_config.training_dataset.
* Updatable fields:
* * `display_name`
* * `model_deployment_monitoring_schedule_config`
* * `model_monitoring_alert_config`
* * `logging_sampling_strategy`
* * `labels`
* * `log_ttl`
* * `enable_monitoring_pipeline_logs`
* . and
* * `model_deployment_monitoring_objective_configs`
* . or
* * `model_deployment_monitoring_objective_configs.objective_config.training_dataset`
* * `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config`
* * `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
com.google.protobuf.FieldMask getUpdateMask();
/**
*
*
* <pre>
* Required. The update mask is used to specify the fields to be overwritten in the
* ModelDeploymentMonitoringJob resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* For the objective config, the user can either provide the update mask for
* model_deployment_monitoring_objective_configs or any combination of its
* nested fields, such as:
* model_deployment_monitoring_objective_configs.objective_config.training_dataset.
* Updatable fields:
* * `display_name`
* * `model_deployment_monitoring_schedule_config`
* * `model_monitoring_alert_config`
* * `logging_sampling_strategy`
* * `labels`
* * `log_ttl`
* * `enable_monitoring_pipeline_logs`
* . and
* * `model_deployment_monitoring_objective_configs`
* . or
* * `model_deployment_monitoring_objective_configs.objective_config.training_dataset`
* * `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config`
* * `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder();
}
| apache-2.0 |
ketralnis/elephant-bird | src/java/com/twitter/elephantbird/util/HadoopUtils.java | 2107 | package com.twitter.elephantbird.util;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Various Hadoop specific utilities.
*/
public class HadoopUtils {
private static final Logger LOG = LoggerFactory.getLogger(HadoopUtils.class);
/**
* MapReduce counters are available only with {@link TaskInputOutputContext},
* but most interfaces use super classes, though the actual obejct is a
* subclass (e.g. Mapper.Context). <br> <br>
*
* This utility method checks the type and returns the appropriate counter.
* In the rare (may be unexpected) case where ctx is not a
* TaskInputOutputContext, a dummy counter is returned after printing
* a warning.
*/
public static Counter getCounter(JobContext ctx, String group, String counter) {
if (ctx instanceof TaskInputOutputContext<?, ?, ?, ?>) {
return ((TaskInputOutputContext<?, ?, ?, ?>)ctx).getCounter(group, counter);
}
String name = group + ":" + counter;
LOG.warn("Context is not a TaskInputOutputContext. "
+ "will return a dummy counter for '" + name + "'");
return new Counter(name, name) {};
}
/**
* A helper to set configuration to class name.
* Throws a RuntimeExcpetion if the
* configuration is already set to a different class name.
*/
public static void setInputFormatClass(Configuration conf,
String configKey,
Class<?> clazz) {
String existingClass = conf.get(configKey);
String className = clazz.getName();
if (existingClass != null && !existingClass.equals(className)) {
throw new RuntimeException(
"Already registered a different thriftClass for "
+ configKey
+ ". old: " + existingClass
+ " new: " + className);
} else {
conf.set(configKey, className);
}
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0091.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_0091 {
}
| apache-2.0 |
unlimitedggames/gdxjam-ugg | core/src/com/ugg/gdxjam/model/enums/VelocityType.java | 140 | package com.ugg.gdxjam.model.enums;
/**
* Created by Jose Cuellar on 07/01/2016.
*/
public enum VelocityType {
Linear,
Impulse
}
| apache-2.0 |
google/or-tools | examples/contrib/StiglerMIP.java | 12315 | /*
* Copyright 2017 Darian Sastre darian.sastre@minimaxlabs.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.
*
* ************************************************************************
*
* This model was created by Hakan Kjellerstrand (hakank@gmail.com)
*
* Java version by Darian Sastre (darian.sastre@minimaxlabs.com)
*/
package com.google.ortools.contrib;
import com.google.ortools.Loader;
import com.google.ortools.linearsolver.MPConstraint;
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class StiglerMIP {
private static void solve(String solverType) {
System.out.println("---- StiglerMIP with " + solverType);
MPSolver solver = MPSolver.createSolver(solverType);
if (solver == null)
return;
double infinity = MPSolver.infinity();
/** invariants */
double days = 365.25;
int nutrientsCount = 9;
int commoditiesCount = 77;
String[] nutrients = {
"calories", // Calories, unit = 1000
"protein", // Protein, unit = grams
"calcium", // Calcium, unit = grams
"iron", // Iron, unit = milligrams
"vitaminA", // Vitamin A, unit = 1000 International Units
"thiamine", // Thiamine, Vit. B1, unit = milligrams
"riboflavin", // Riboflavin, Vit. B2, unit = milligrams
"niacin", // Niacin (Nicotinic Acid), unit = milligrams
"ascorbicAcid" // Ascorbic Acid, Vit. C, unit = milligrams
};
String[] commodities = {"Wheat Flour (Enriched), 10 lb.", "Macaroni, 1 lb.",
"Wheat Cereal (Enriched), 28 oz.", "Corn Flakes, 8 oz.", "Corn Meal, 1 lb.",
"Hominy Grits, 24 oz.", "Rice, 1 lb.", "Rolled Oats, 1 lb.",
"White Bread (Enriched), 1 lb.", "Whole Wheat Bread, 1 lb.", "Rye Bread, 1 lb.",
"Pound Cake, 1 lb.", "Soda Crackers, 1 lb.", "Milk, 1 qt.",
"Evaporated Milk (can), 14.5 oz.", "Butter, 1 lb.", "Oleomargarine, 1 lb.", "Eggs, 1 doz.",
"Cheese (Cheddar), 1 lb.", "Cream, 1/2 pt.", "Peanut Butter, 1 lb.", "Mayonnaise, 1/2 pt.",
"Crisco, 1 lb.", "Lard, 1 lb.", "Sirloin Steak, 1 lb.", "Round Steak, 1 lb.",
"Rib Roast, 1 lb.", "Chuck Roast, 1 lb.", "Plate, 1 lb.", "Liver (Beef), 1 lb.",
"Leg of Lamb, 1 lb.", "Lamb Chops (Rib), 1 lb.", "Pork Chops, 1 lb.",
"Pork Loin Roast, 1 lb.", "Bacon, 1 lb.", "Ham - smoked, 1 lb.", "Salt Pork, 1 lb.",
"Roasting Chicken, 1 lb.", "Veal Cutlets, 1 lb.", "Salmon, Pink (can), 16 oz.",
"Apples, 1 lb.", "Bananas, 1 lb.", "Lemons, 1 doz.", "Oranges, 1 doz.",
"Green Beans, 1 lb.", "Cabbage, 1 lb.", "Carrots, 1 bunch", "Celery, 1 stalk",
"Lettuce, 1 head", "Onions, 1 lb.", "Potatoes, 15 lb.", "Spinach, 1 lb.",
"Sweet Potatoes, 1 lb.", "Peaches (can), No. 2 1/2", "Pears (can), No. 2 1/2,",
"Pineapple (can), No. 2 1/2", "Asparagus (can), No. 2", "Grean Beans (can), No. 2",
"Pork and Beans (can), 16 oz.", "Corn (can), No. 2", "Peas (can), No. 2",
"Tomatoes (can), No. 2", "Tomato Soup (can), 10 1/2 oz.", "Peaches, Dried, 1 lb.",
"Prunes, Dried, 1 lb.", "Raisins, Dried, 15 oz.", "Peas, Dried, 1 lb.",
"Lima Beans, Dried, 1 lb.", "Navy Beans, Dried, 1 lb.", "Coffee, 1 lb.", "Tea, 1/4 lb.",
"Cocoa, 8 oz.", "Chocolate, 8 oz.", "Sugar, 10 lb.", "Corn Sirup, 24 oz.",
"Molasses, 18 oz.", "Strawberry Preserve, 1 lb."};
// price and weight per unit correspond to the two first columns
double[][] data = {{36.0, 12600.0, 44.7, 1411.0, 2.0, 365.0, 0.0, 55.4, 33.3, 441.0, 0.0},
{14.1, 3217.0, 11.6, 418.0, 0.7, 54.0, 0.0, 3.2, 1.9, 68.0, 0.0},
{24.2, 3280.0, 11.8, 377.0, 14.4, 175.0, 0.0, 14.4, 8.8, 114.0, 0.0},
{7.1, 3194.0, 11.4, 252.0, 0.1, 56.0, 0.0, 13.5, 2.3, 68.0, 0.0},
{4.6, 9861.0, 36.0, 897.0, 1.7, 99.0, 30.9, 17.4, 7.9, 106.0, 0.0},
{8.5, 8005.0, 28.6, 680.0, 0.8, 80.0, 0.0, 10.6, 1.6, 110.0, 0.0},
{7.5, 6048.0, 21.2, 460.0, 0.6, 41.0, 0.0, 2.0, 4.8, 60.0, 0.0},
{7.1, 6389.0, 25.3, 907.0, 5.1, 341.0, 0.0, 37.1, 8.9, 64.0, 0.0},
{7.9, 5742.0, 15.6, 488.0, 2.5, 115.0, 0.0, 13.8, 8.5, 126.0, 0.0},
{9.1, 4985.0, 12.2, 484.0, 2.7, 125.0, 0.0, 13.9, 6.4, 160.0, 0.0},
{9.2, 4930.0, 12.4, 439.0, 1.1, 82.0, 0.0, 9.9, 3.0, 66.0, 0.0},
{24.8, 1829.0, 8.0, 130.0, 0.4, 31.0, 18.9, 2.8, 3.0, 17.0, 0.0},
{15.1, 3004.0, 12.5, 288.0, 0.5, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{11.0, 8867.0, 6.1, 310.0, 10.5, 18.0, 16.8, 4.0, 16.0, 7.0, 177.0},
{6.7, 6035.0, 8.4, 422.0, 15.1, 9.0, 26.0, 3.0, 23.5, 11.0, 60.0},
{20.8, 1473.0, 10.8, 9.0, 0.2, 3.0, 44.2, 0.0, 0.2, 2.0, 0.0},
{16.1, 2817.0, 20.6, 17.0, 0.6, 6.0, 55.8, 0.2, 0.0, 0.0, 0.0},
{32.6, 1857.0, 2.9, 238.0, 1.0, 52.0, 18.6, 2.8, 6.5, 1.0, 0.0},
{24.2, 1874.0, 7.4, 448.0, 16.4, 19.0, 28.1, 0.8, 10.3, 4.0, 0.0},
{14.1, 1689.0, 3.5, 49.0, 1.7, 3.0, 16.9, 0.6, 2.5, 0.0, 17.0},
{17.9, 2534.0, 15.7, 661.0, 1.0, 48.0, 0.0, 9.6, 8.1, 471.0, 0.0},
{16.7, 1198.0, 8.6, 18.0, 0.2, 8.0, 2.7, 0.4, 0.5, 0.0, 0.0},
{20.3, 2234.0, 20.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{9.8, 4628.0, 41.7, 0.0, 0.0, 0.0, 0.2, 0.0, 0.5, 5.0, 0.0},
{39.6, 1145.0, 2.9, 166.0, 0.1, 34.0, 0.2, 2.1, 2.9, 69.0, 0.0},
{36.4, 1246.0, 2.2, 214.0, 0.1, 32.0, 0.4, 2.5, 2.4, 87.0, 0.0},
{29.2, 1553.0, 3.4, 213.0, 0.1, 33.0, 0.0, 0.0, 2.0, 0.0, 0.0},
{22.6, 2007.0, 3.6, 309.0, 0.2, 46.0, 0.4, 1.0, 4.0, 120.0, 0.0},
{14.6, 3107.0, 8.5, 404.0, 0.2, 62.0, 0.0, 0.9, 0.0, 0.0, 0.0},
{26.8, 1692.0, 2.2, 333.0, 0.2, 139.0, 169.2, 6.4, 50.8, 316.0, 525.0},
{27.6, 1643.0, 3.1, 245.0, 0.1, 20.0, 0.0, 2.8, 3.0, 86.0, 0.0},
{36.6, 1239.0, 3.3, 140.0, 0.1, 15.0, 0.0, 1.7, 2.7, 54.0, 0.0},
{30.7, 1477.0, 3.5, 196.0, 0.2, 80.0, 0.0, 17.4, 2.7, 60.0, 0.0},
{24.2, 1874.0, 4.4, 249.0, 0.3, 37.0, 0.0, 18.2, 3.6, 79.0, 0.0},
{25.6, 1772.0, 10.4, 152.0, 0.2, 23.0, 0.0, 1.8, 1.8, 71.0, 0.0},
{27.4, 1655.0, 6.7, 212.0, 0.2, 31.0, 0.0, 9.9, 3.3, 50.0, 0.0},
{16.0, 2835.0, 18.8, 164.0, 0.1, 26.0, 0.0, 1.4, 1.8, 0.0, 0.0},
{30.3, 1497.0, 1.8, 184.0, 0.1, 30.0, 0.1, 0.9, 1.8, 68.0, 46.0},
{42.3, 1072.0, 1.7, 156.0, 0.1, 24.0, 0.0, 1.4, 2.4, 57.0, 0.0},
{13.0, 3489.0, 5.8, 705.0, 6.8, 45.0, 3.5, 1.0, 4.9, 209.0, 0.0},
{4.4, 9072.0, 5.8, 27.0, 0.5, 36.0, 7.3, 3.6, 2.7, 5.0, 544.0},
{6.1, 4982.0, 4.9, 60.0, 0.4, 30.0, 17.4, 2.5, 3.5, 28.0, 498.0},
{26.0, 2380.0, 1.0, 21.0, 0.5, 14.0, 0.0, 0.5, 0.0, 4.0, 952.0},
{30.9, 4439.0, 2.2, 40.0, 1.1, 18.0, 11.1, 3.6, 1.3, 10.0, 1993.0},
{7.1, 5750.0, 2.4, 138.0, 3.7, 80.0, 69.0, 4.3, 5.8, 37.0, 862.0},
{3.7, 8949.0, 2.6, 125.0, 4.0, 36.0, 7.2, 9.0, 4.5, 26.0, 5369.0},
{4.7, 6080.0, 2.7, 73.0, 2.8, 43.0, 188.5, 6.1, 4.3, 89.0, 608.0},
{7.3, 3915.0, 0.9, 51.0, 3.0, 23.0, 0.9, 1.4, 1.4, 9.0, 313.0},
{8.2, 2247.0, 0.4, 27.0, 1.1, 22.0, 112.4, 1.8, 3.4, 11.0, 449.0},
{3.6, 11844.0, 5.8, 166.0, 3.8, 59.0, 16.6, 4.7, 5.9, 21.0, 1184.0},
{34.0, 16810.0, 14.3, 336.0, 1.8, 118.0, 6.7, 29.4, 7.1, 198.0, 2522.0},
{8.1, 4592.0, 1.1, 106.0, 0.0, 138.0, 918.4, 5.7, 13.8, 33.0, 2755.0},
{5.1, 7649.0, 9.6, 138.0, 2.7, 54.0, 290.7, 8.4, 5.4, 83.0, 1912.0},
{16.8, 4894.0, 3.7, 20.0, 0.4, 10.0, 21.5, 0.5, 1.0, 31.0, 196.0},
{20.4, 4030.0, 3.0, 8.0, 0.3, 8.0, 0.8, 0.8, 0.8, 5.0, 81.0},
{21.3, 3993.0, 2.4, 16.0, 0.4, 8.0, 2.0, 2.8, 0.8, 7.0, 399.0},
{27.7, 1945.0, 0.4, 33.0, 0.3, 12.0, 16.3, 1.4, 2.1, 17.0, 272.0},
{10.0, 5386.0, 1.0, 54.0, 2.0, 65.0, 53.9, 1.6, 4.3, 32.0, 431.0},
{7.1, 6389.0, 7.5, 364.0, 4.0, 134.0, 3.5, 8.3, 7.7, 56.0, 0.0},
{10.4, 5452.0, 5.2, 136.0, 0.2, 16.0, 12.0, 1.6, 2.7, 42.0, 218.0},
{13.8, 4109.0, 2.3, 136.0, 0.6, 45.0, 34.9, 4.9, 2.5, 37.0, 370.0},
{8.6, 6263.0, 1.3, 63.0, 0.7, 38.0, 53.2, 3.4, 2.5, 36.0, 1253.0},
{7.6, 3917.0, 1.6, 71.0, 0.6, 43.0, 57.9, 3.5, 2.4, 67.0, 862.0},
{15.7, 2889.0, 8.5, 87.0, 1.7, 173.0, 86.8, 1.2, 4.3, 55.0, 57.0},
{9.0, 4284.0, 12.8, 99.0, 2.5, 154.0, 85.7, 3.9, 4.3, 65.0, 257.0},
{9.4, 4524.0, 13.5, 104.0, 2.5, 136.0, 4.5, 6.3, 1.4, 24.0, 136.0},
{7.9, 5742.0, 20.0, 1367.0, 4.2, 345.0, 2.9, 28.7, 18.4, 162.0, 0.0},
{8.9, 5097.0, 17.4, 1055.0, 3.7, 459.0, 5.1, 26.9, 38.2, 93.0, 0.0},
{5.9, 7688.0, 26.9, 1691.0, 11.4, 792.0, 0.0, 38.4, 24.6, 217.0, 0.0},
{22.4, 2025.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.1, 50.0, 0.0},
{17.4, 652.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.3, 42.0, 0.0},
{8.6, 2637.0, 8.7, 237.0, 3.0, 72.0, 0.0, 2.0, 11.9, 40.0, 0.0},
{16.2, 1400.0, 8.0, 77.0, 1.3, 39.0, 0.0, 0.9, 3.4, 14.0, 0.0},
{51.7, 8773.0, 34.9, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{13.7, 4996.0, 14.7, 0.0, 0.5, 74.0, 0.0, 0.0, 0.0, 5.0, 0.0},
{13.6, 3752.0, 9.0, 0.0, 10.3, 244.0, 0.0, 1.9, 7.5, 146.0, 0.0},
{20.5, 2213.0, 6.4, 11.0, 0.4, 7.0, 0.2, 0.2, 0.4, 3.0, 0.0}};
// recommended daily nutritional allowance
double[] allowance = {3.0, 70.0, 0.8, 12.0, 5.0, 1.8, 2.7, 18.0, 75.0};
/** variables */
MPVariable[] x = solver.makeNumVarArray(commoditiesCount, 0, 1000);
MPVariable[] xCost = solver.makeNumVarArray(commoditiesCount, 0, 1000);
MPVariable[] quant = solver.makeNumVarArray(commoditiesCount, 0, 1000);
MPVariable totalCost = solver.makeNumVar(0, 1000, "total_cost");
/** constraints & objective */
MPObjective obj = solver.objective();
MPConstraint[] costConstraint = new MPConstraint[2 * commoditiesCount];
MPConstraint[] quantConstraint = new MPConstraint[2 * commoditiesCount];
MPConstraint totalCostConstraint = solver.makeConstraint(0, 0);
for (int i = 0; i < commoditiesCount; i++) {
totalCostConstraint.setCoefficient(x[i], days);
costConstraint[i] = solver.makeConstraint(0, 0);
costConstraint[i].setCoefficient(x[i], days);
costConstraint[i].setCoefficient(xCost[i], -1);
quantConstraint[i] = solver.makeConstraint(0, 0);
quantConstraint[i].setCoefficient(x[i], days * 100 / data[i][0]);
quantConstraint[i].setCoefficient(quant[i], -1);
obj.setCoefficient(x[i], 1);
}
totalCostConstraint.setCoefficient(totalCost, -1);
MPConstraint[] nutrientConstraint = new MPConstraint[nutrientsCount];
for (int i = 0; i < nutrientsCount; i++) {
nutrientConstraint[i] = solver.makeConstraint(allowance[i], infinity);
for (int j = 0; j < commoditiesCount; j++) {
nutrientConstraint[i].setCoefficient(x[j], data[j][i + 2]);
}
}
final MPSolver.ResultStatus resultStatus = solver.solve();
/** printing */
if (resultStatus != MPSolver.ResultStatus.OPTIMAL) {
System.err.println("The problem does not have an optimal solution!");
}
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("Min cost: " + df.format(obj.value()));
System.out.println("Total cost: " + df.format(totalCost.solutionValue()));
for (int i = 0; i < commoditiesCount; i++) {
if (x[i].solutionValue() > 0) {
System.out.println(commodities[i] + ": " + df.format(xCost[i].solutionValue()) + " "
+ df.format(quant[i].solutionValue()));
}
}
}
public static void main(String[] args) {
Loader.loadNativeLibraries();
solve("SCIP");
solve("CBC");
solve("GLPK");
}
}
| apache-2.0 |
Talend/components | components/components-salesforce/components-salesforce-definition/src/main/java/org/talend/components/salesforce/datastore/SalesforceDatastoreProperties.java | 5252 | //============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.salesforce.datastore;
import static org.talend.daikon.properties.presentation.Widget.widget;
import static org.talend.daikon.properties.property.PropertyFactory.newProperty;
import static org.talend.daikon.properties.property.PropertyFactory.newString;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.api.properties.ComponentBasePropertiesImpl;
import org.talend.components.common.datastore.DatastoreProperties;
import org.talend.components.salesforce.SalesforceConnectionProperties;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.presentation.Widget;
import org.talend.daikon.properties.property.Property;
public class SalesforceDatastoreProperties extends ComponentBasePropertiesImpl implements DatastoreProperties {
public static final String CONFIG_FILE_lOCATION_KEY = "org.talend.component.salesforce.config.file";
/** Properties file key for endpoint storage. */
public static final String ENDPOINT_PROPERTY_KEY = "endpoint";
private static final Logger LOG = LoggerFactory.getLogger(SalesforceDatastoreProperties.class);
public Property<String> userId = newProperty("userId").setRequired();
public Property<String> password = newProperty("password").setRequired().setFlags(
EnumSet.of(Property.Flags.ENCRYPT, Property.Flags.SUPPRESS_LOGGING));
public Property<String> securityKey = newProperty("securityKey").setRequired().setFlags(
EnumSet.of(Property.Flags.ENCRYPT, Property.Flags.SUPPRESS_LOGGING));
public Property<String> endpoint = newString("endpoint").setRequired();
private Properties salesforceProperties = null;
public SalesforceDatastoreProperties(String name) {
super(name);
}
@Override
public void setupProperties() {
super.setupProperties();
loadEndPoint();
}
@Override
public void setupLayout() {
super.setupLayout();
Form mainForm = Form.create(this, Form.MAIN);
mainForm.addRow(endpoint);
mainForm.addRow(userId);
mainForm.addRow(widget(password).setWidgetType(Widget.HIDDEN_TEXT_WIDGET_TYPE));
mainForm.addRow(widget(securityKey).setWidgetType(Widget.HIDDEN_TEXT_WIDGET_TYPE));
}
/**
* Load Dataprep user Salesforce properties file for endpoint & timeout default values.
*
* @return a {@link Properties} objet (maybe empty) but never null.
*/
public Properties getSalesforceProperties() {
if (salesforceProperties == null) {
salesforceProperties = new Properties();
String config_file = System.getProperty(CONFIG_FILE_lOCATION_KEY);
try (InputStream is = config_file != null ? (new FileInputStream(config_file)) : null) {
if (is == null) {
LOG.warn("not found the property file, will use the default value for endpoint and timeout");
} else {
salesforceProperties.load(is);
}
} catch (IOException e) {
LOG.warn("not found the property file, will use the default value for endpoint and timeout", e);
}
}
return salesforceProperties;
}
/**
* Load the Salesforce endpoint, if necessary either from the user specified property file or from the default
* hardcoded value.
*/
private void loadEndPoint() {
if (endpoint == null || endpoint.getValue() == null) {
salesforceProperties = getSalesforceProperties();
String endpointProp = salesforceProperties.getProperty(ENDPOINT_PROPERTY_KEY);
if (endpointProp != null && !endpointProp.isEmpty()) {
if (endpointProp.contains(SalesforceConnectionProperties.RETIRED_ENDPOINT)) {
// FIXME : is this code still up to date ? if so, have we documented it for our customers ?
endpointProp = endpointProp.replaceFirst(SalesforceConnectionProperties.RETIRED_ENDPOINT,
SalesforceConnectionProperties.ACTIVE_ENDPOINT);
}
endpoint.setValue(endpointProp);
} else {
endpoint.setValue(SalesforceConnectionProperties.URL);
}
}
}
/**
* Return the datastore endpoint, loading a default value if no value is present.
*
* @return the datastore endpoint value.
*/
public String getEndPoint() {
loadEndPoint();
return endpoint.getValue();
}
}
| apache-2.0 |
slipperyseal/pimpmylight | src/main/java/net/catchpole/pimpmylight/model/RailwaySignal.java | 1400 | package net.catchpole.pimpmylight.model;
// Copyright 2014 catchpole.net
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RailwaySignal implements Iterable<Light> {
private List<Light> lightList = new ArrayList<Light>();
public RailwaySignal() {
}
public RailwaySignal(RailwaySignal railwaySignal, Light replaceLight) {
for (Light light : railwaySignal) {
lightList.add(light.getName().equals(replaceLight.getName()) ? replaceLight : light);
}
}
public void addLight(Light light) {
lightList.add(light);
}
@Override
public Iterator<Light> iterator() {
return lightList.iterator();
}
public String toString() {
return this.getClass().getSimpleName() + ' ' + lightList;
}
}
| apache-2.0 |
consulo/consulo-groovy | groovy-psi/src/main/java/org/jetbrains/plugins/groovy/config/GroovyConfigUtils.java | 7177 | /*
* Copyright 2000-2013 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 org.jetbrains.plugins.groovy.config;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import icons.JetgroovyIcons;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.util.GroovyUtils;
import org.jetbrains.plugins.groovy.util.LibrariesUtil;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.regex.Pattern;
/**
* @author ilyas
*/
public abstract class GroovyConfigUtils extends AbstractConfigUtils
{
@NonNls
private static final Pattern GROOVY_ALL_JAR_PATTERN = Pattern.compile("groovy-all-(.*)\\.jar");
private static GroovyConfigUtils myGroovyConfigUtils;
@NonNls
public static final String GROOVY_JAR_PATTERN_NOVERSION = "groovy\\.jar";
@NonNls
public static final String GROOVY_JAR_PATTERN = "groovy-(\\d.*)\\.jar";
public static final String NO_VERSION = "<no version>";
public static final String GROOVY1_7 = "1.7";
public static final String GROOVY1_8 = "1.8";
public static final String GROOVY2_0 = "2.0";
public static final String GROOVY2_1 = "2.1";
public static final String GROOVY2_2 = "2.2";
public static final String GROOVY2_2_2 = "2.2.2";
public static final String GROOVY2_3 = "2.3";
GroovyConfigUtils()
{
}
public static GroovyConfigUtils getInstance()
{
if(myGroovyConfigUtils == null)
{
myGroovyConfigUtils = new GroovyConfigUtils()
{
{
STARTER_SCRIPT_FILE_NAME = "groovy";
}
};
}
return myGroovyConfigUtils;
}
@Nonnull
public static File[] getGroovyAllJars(@Nonnull String path)
{
return GroovyUtils.getFilesInDirectoryByPattern(path, GROOVY_ALL_JAR_PATTERN);
}
public static boolean matchesGroovyAll(@Nonnull String name)
{
return GROOVY_ALL_JAR_PATTERN.matcher(name).matches() && !name.contains("src") && !name.contains("doc");
}
@Nonnull
public String getSDKVersion(@Nonnull final String path)
{
String groovyJarVersion = getSDKJarVersion(path + "/lib", GROOVY_JAR_PATTERN, MANIFEST_PATH);
if(groovyJarVersion == null)
{
groovyJarVersion = getSDKJarVersion(path + "/lib", GROOVY_JAR_PATTERN_NOVERSION, MANIFEST_PATH);
}
if(groovyJarVersion == null)
{
groovyJarVersion = getSDKJarVersion(path + "/lib", GROOVY_ALL_JAR_PATTERN, MANIFEST_PATH);
}
if(groovyJarVersion == null)
{
groovyJarVersion = getSDKJarVersion(path + "/embeddable", GROOVY_ALL_JAR_PATTERN, MANIFEST_PATH);
}
if(groovyJarVersion == null)
{
groovyJarVersion = getSDKJarVersion(path, GROOVY_ALL_JAR_PATTERN, MANIFEST_PATH);
}
return groovyJarVersion == null ? UNDEFINED_VERSION : groovyJarVersion;
}
public boolean isSDKLibrary(Library library)
{
if(library == null)
{
return false;
}
return LibrariesUtil.getGroovyLibraryHome(library.getFiles(OrderRootType.CLASSES)) != null;
}
@Nullable
public String getSDKVersion(@Nonnull final Module module)
{
return CachedValuesManager.getManager(module.getProject()).getCachedValue(module,
new CachedValueProvider<String>()
{
@Override
public Result<String> compute()
{
final String path = LibrariesUtil.getGroovyHomePath(module);
if(path == null)
{
return Result.create(null, ProjectRootManager.getInstance(module.getProject()));
}
return Result.create(getSDKVersion(path), ProjectRootManager.getInstance(module.getProject()));
}
});
}
public boolean isVersionAtLeast(PsiElement psiElement, String version)
{
return isVersionAtLeast(psiElement, version, true);
}
public boolean isVersionAtLeast(PsiElement psiElement, String version, boolean unknownResult)
{
Module module = ModuleUtilCore.findModuleForPsiElement(psiElement);
if(module == null)
{
return unknownResult;
}
final String sdkVersion = getSDKVersion(module);
if(sdkVersion == null)
{
return unknownResult;
}
return sdkVersion.compareTo(version) >= 0;
}
@Nonnull
public String getSDKVersion(PsiElement psiElement)
{
final Module module = ModuleUtilCore.findModuleForPsiElement(psiElement);
if(module == null)
{
return NO_VERSION;
}
final String s = getSDKVersion(module);
return s != null ? s : NO_VERSION;
}
@Override
public boolean isSDKHome(VirtualFile file)
{
if(file != null && file.isDirectory())
{
final String path = file.getPath();
if(GroovyUtils.getFilesInDirectoryByPattern(path + "/lib", GROOVY_JAR_PATTERN).length > 0 ||
GroovyUtils.getFilesInDirectoryByPattern(path + "/lib", GROOVY_JAR_PATTERN_NOVERSION).length > 0 ||
GroovyUtils.getFilesInDirectoryByPattern(path + "/embeddable", GROOVY_ALL_JAR_PATTERN).length >
0 ||
GroovyUtils.getFilesInDirectoryByPattern(path, GROOVY_JAR_PATTERN).length > 0)
{
return true;
}
}
return false;
}
public boolean tryToSetUpGroovyFacetOnTheFly(final Module module)
{
final Project project = module.getProject();
final Library[] libraries = getAllSDKLibraries(project);
if(libraries.length > 0)
{
final Library library = libraries[0];
int result = Messages.showOkCancelDialog(GroovyBundle.message("groovy.like.library.found.text",
module.getName(), library.getName(), getSDKLibVersion(library)), GroovyBundle.message("groovy.like" +
".library.found"), Messages.getQuestionIcon());
if(result == 0)
{
WriteAction.run(() ->
{
ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
LibraryOrderEntry entry = model.addLibraryEntry(libraries[0]);
LibrariesUtil.placeEntryToCorrectPlace(model, entry);
model.commit();
});
return true;
}
}
return false;
}
@Nonnull
public String getSDKLibVersion(Library library)
{
return getSDKVersion(LibrariesUtil.getGroovyLibraryHome(library));
}
public Collection<String> getSDKVersions(Library[] libraries)
{
return ContainerUtil.map2List(libraries, new Function<Library, String>()
{
public String fun(Library library)
{
return getSDKLibVersion(library);
}
});
}
}
| apache-2.0 |
lynnfield/Points | app/src/main/java/com/lynnfield/points/db/models/Points.java | 4067 | package com.lynnfield.points.db.models;
import android.content.ContentValues;
import android.database.Cursor;
import com.lynnfield.points.db.migrations.PointsMigration;
import java.util.Date;
/**
* Created by Genovich V.V. on 06.03.2015.
*/
public final class Points
extends IRecordImpl<Points>
implements IPoints
{
IEvent mEvent;
Float mPoints;
Date mDate;
@Override
public IEvent getEvent()
{
return mEvent;
}
@Override
public void setEvent(IEvent event)
{
mEvent = event;
}
@Override
public Float getAmount()
{
return mPoints;
}
@Override
public void setAmount(Float points)
{
mPoints = points;
}
@Override
public Date getDate()
{
return mDate;
}
@Override
public void setDate(Date date)
{
mDate = date;
}
@Override
public void fillFromCursor(Cursor cursor)
{
super.fillFromCursor(cursor);
mEvent = new Event();
mEvent.setId(
cursor.getLong(
cursor.getColumnIndexOrThrow(
PointsMigration.EVENT_ID)));
mPoints =
cursor.getFloat(
cursor.getColumnIndexOrThrow(
PointsMigration.POINTS_AMOUNT));
mDate =
new Date(
cursor.getInt(
cursor.getColumnIndexOrThrow(
PointsMigration.CHANGE_DATE)));
}
@Override
public ContentValues toContentValues()
{
ContentValues values =
super.toContentValues();
values.put(
PointsMigration.EVENT_ID,
mEvent.getId());
values.put(
PointsMigration.POINTS_AMOUNT,
mPoints);
values.put(
PointsMigration.CHANGE_DATE,
mDate.getTime());
return values;
}
@Override
public String[] getProjection() {
return new String[]
{
super.getProjection()[0],
PointsMigration.EVENT_ID,
PointsMigration.POINTS_AMOUNT,
PointsMigration.CHANGE_DATE
};
}
@Override
public String getTableName() {
return PointsMigration.TABLE_NAME;
}
@Override
public String getWhere() {
StringBuilder where =
new StringBuilder(
super.getWhere());
boolean mEventExists =
mEvent != null;
boolean mPointsExists =
mPoints != null;
boolean mDateExists =
mDate != null;
if (isIdExists() && mEventExists)
where.append(',');
if (mEventExists)
{
where
.append(PointsMigration.EVENT_ID)
.append('=')
.append(mEvent.getId());
}
if ((isIdExists() || mEventExists) && mPointsExists)
where.append(',');
if (mPointsExists)
{
where
.append(PointsMigration.POINTS_AMOUNT)
.append('=')
.append(mPoints);
}
if ((isIdExists() || mEventExists || mPointsExists) && mDateExists)
where.append(',');
if (mDateExists)
{
where
.append(PointsMigration.CHANGE_DATE)
.append('=')
.append(mDate.getTime());
}
return where.toString();
}
@Override
protected Points fromCursor(Cursor cursor) {
Points ret = new Points();
ret.fillFromCursor(cursor);
return ret;
}
@Override
public String toString() {
return "Points{" +
"id=" + (id == null ? "null" : id) +
", mEvent=" + (mEvent == null ? "null" : (mEvent.getId() == null ? "null" : mEvent.getId())) +
", mPoints=" + (mPoints == null ? "null" : mPoints) +
", mDate=" + (mDate == null ? "null" : mDate) +
'}';
}
}
| apache-2.0 |
wmixlabs/correios | src/main/java/com/github/wmixvideo/correios/WSCorreiosRastreador.java | 2016 | package com.github.wmixvideo.correios;
import br.com.correios.webservice.calculador.CalcPrecoPrazoWS;
import br.com.correios.webservice.calculador.CalcPrecoPrazoWSSoap;
import br.com.correios.webservice.rastro.Rastro;
import br.com.correios.webservice.rastro.Service;
import br.com.correios.webservice.rastro.Sroxml;
import javax.xml.ws.BindingProvider;
import java.util.Collection;
import java.util.Map;
public class WSCorreiosRastreador {
private static final String TIPO = "L";//todos
private static final String RESULTADO = "T";//todos
private static final String LINGUA = "101";//portugues
private Service service;
private final String usuario;
private final String senha;
private int timeoutMilliseconds = 15000;
public WSCorreiosRastreador(final String usuario, final String senha) {
this.service = null;
this.usuario = usuario;
this.senha = senha;
}
public WSCorreiosRastreador setTimeout(final int milliseconds) {
this.timeoutMilliseconds = milliseconds;
return this;
}
private Service getService() {
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(this.timeoutMilliseconds));
if (this.service == null) {
this.service = new Rastro().getServicePort();
}
final Map<String, Object> requestContext = ((BindingProvider) this.service).getRequestContext();
requestContext.put("com.sun.xml.internal.ws.connect.timeout", timeoutMilliseconds);
requestContext.put("com.sun.xml.internal.ws.request.timeout", timeoutMilliseconds);
return this.service;
}
public Sroxml consultaObjeto(final String objeto) {
return this.getService().buscaEventos(this.usuario, this.senha, TIPO, RESULTADO, LINGUA, objeto);
}
public Sroxml consultaObjetos(final Collection<String> objetos) {
return this.getService().buscaEventos(this.usuario, this.senha, TIPO, RESULTADO, LINGUA, String.join("", objetos));
}
}
| apache-2.0 |
apache/incubator-shardingsphere | shardingsphere-test/shardingsphere-integration-test/shardingsphere-integration-test-suite/src/test/java/org/apache/shardingsphere/test/integration/engine/dql/BaseDQLIT.java | 6671 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.test.integration.engine.dql;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.shardingsphere.test.integration.engine.SingleITCase;
import org.apache.shardingsphere.test.integration.env.scenario.ScenarioPath;
import org.apache.shardingsphere.test.integration.env.scenario.dataset.DataSetEnvironmentManager;
import org.apache.shardingsphere.test.integration.framework.param.model.AssertionParameterizedArray;
import org.junit.Before;
import javax.sql.DataSource;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Collection;
import java.util.HashSet;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@Getter(AccessLevel.PROTECTED)
public abstract class BaseDQLIT extends SingleITCase {
private static final Collection<String> FILLED_SUITES = new HashSet<>();
private DataSource verificationDataSource;
public BaseDQLIT(final AssertionParameterizedArray parameterizedArray) {
super(parameterizedArray);
}
@Before
public final void init() throws Exception {
fillDataOnlyOnce();
verificationDataSource = null == getAssertion().getExpectedDataSourceName() || 1 == getVerificationDataSourceMap().size()
? getVerificationDataSourceMap().values().iterator().next() : getVerificationDataSourceMap().get(getAssertion().getExpectedDataSourceName());
}
private void fillDataOnlyOnce() throws SQLException, ParseException, IOException, JAXBException {
if (!FILLED_SUITES.contains(getItKey())) {
synchronized (FILLED_SUITES) {
if (!FILLED_SUITES.contains(getScenario())) {
new DataSetEnvironmentManager(new ScenarioPath(getScenario()).getDataSetFile(), getActualDataSourceMap()).fillData();
new DataSetEnvironmentManager(new ScenarioPath(getScenario()).getVerificationDataSetFile(), getVerificationDataSourceMap()).fillData();
FILLED_SUITES.add(getItKey());
}
}
}
}
protected final void assertResultSet(final ResultSet actualResultSet, final ResultSet verificationResultSet) throws SQLException {
assertMetaData(actualResultSet.getMetaData(), verificationResultSet.getMetaData());
assertRows(actualResultSet, verificationResultSet);
}
private void assertMetaData(final ResultSetMetaData actualResultSetMetaData, final ResultSetMetaData verificationResultSetMetaData) throws SQLException {
assertThat(actualResultSetMetaData.getColumnCount(), is(verificationResultSetMetaData.getColumnCount()));
for (int i = 0; i < actualResultSetMetaData.getColumnCount(); i++) {
try {
assertThat(actualResultSetMetaData.getColumnLabel(i + 1).toLowerCase(), is(verificationResultSetMetaData.getColumnLabel(i + 1).toLowerCase()));
} catch (final AssertionError ex) {
// FIXME #15594 Expected: is "order_id", but: was "order_id0"
try {
assertThat(actualResultSetMetaData.getColumnLabel(i + 1).toLowerCase(), is(verificationResultSetMetaData.getColumnLabel(i + 1).toLowerCase() + "0"));
} catch (final AssertionError otherEx) {
// FIXME #15594 Expected: is "sum(order_id_sharding)0", but: was "expr$1"
assertThat(actualResultSetMetaData.getColumnLabel(i + 1).toLowerCase(), startsWith("expr$"));
}
}
}
}
private void assertRows(final ResultSet actualResultSet, final ResultSet verificationResultSet) throws SQLException {
ResultSetMetaData actualMetaData = actualResultSet.getMetaData();
ResultSetMetaData verificationMetaData = verificationResultSet.getMetaData();
while (actualResultSet.next()) {
assertTrue("Size of actual result set is different with size of expected result set.", verificationResultSet.next());
assertRow(actualResultSet, actualMetaData, verificationResultSet, verificationMetaData);
}
assertFalse("Size of actual result set is different with size of expected result set.", verificationResultSet.next());
}
private void assertRow(final ResultSet actualResultSet, final ResultSetMetaData actualMetaData,
final ResultSet verificationResultSet, final ResultSetMetaData verificationMetaData) throws SQLException {
for (int i = 0; i < actualMetaData.getColumnCount(); i++) {
try {
assertThat(actualResultSet.getObject(i + 1), is(verificationResultSet.getObject(i + 1)));
assertThat(actualResultSet.getObject(actualMetaData.getColumnLabel(i + 1)), is(verificationResultSet.getObject(verificationMetaData.getColumnLabel(i + 1))));
} catch (AssertionError ex) {
// FIXME #15593 verify accurate data types
Object actualValue = actualResultSet.getObject(i + 1);
Object verificationValue = verificationResultSet.getObject(i + 1);
if (actualValue instanceof Double || actualValue instanceof Float || actualValue instanceof BigDecimal) {
assertThat(Math.floor(Double.parseDouble(actualValue.toString())), is(Math.floor(Double.parseDouble(verificationValue.toString()))));
} else {
assertThat(actualValue.toString(), is(verificationValue.toString()));
}
}
}
}
}
| apache-2.0 |
stori-es/stori_es | dashboard/src/main/java/org/consumersunion/stories/common/client/ui/form/InputFormControl.java | 1545 | package org.consumersunion.stories.common.client.ui.form;
import java.util.List;
import org.consumersunion.stories.common.client.i18n.FormI18nMessages;
import com.google.gwt.core.client.GWT;
public abstract class InputFormControl extends UiFormControl {
private final FormI18nMessages messages = GWT.create(FormI18nMessages.class);
public InputFormControl(final String label, final String key, final boolean required, final String rowClass) {
super(label, key, required, rowClass);
}
@Override
public void validate() {
final List<String> values = getValues();
int validValues = 0;
final Validator validator = getValidator();
for (final String val : values) {
if (isValue(val)) {
checkLength(val);
if (validator != null) {
validator.validate(val);
}
validValues++;
}
}
if (isRequired() && validValues == 0) {
throw new InputValidationException(messages.requiredField());
}
}
private void checkLength(final String value) {
if (value.length() < getMinLength()) {
throw new InputValidationException(messages.valueAtLeast(getMinLength()));
}
if (value.length() > getMaxLength()) {
throw new InputValidationException(messages.valueMoreThan(getMaxLength()));
}
}
public abstract List<String> getValues();
public abstract void setValues(List<String> values);
}
| apache-2.0 |
cloudiator/colosseum | app/models/service/OperatingSystemService.java | 904 | /*
* Copyright (c) 2014-2015 University of Ulm
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 models.service;
import models.OperatingSystem;
/**
* Created by daniel on 23.07.15.
*/
public interface OperatingSystemService extends ModelService<OperatingSystem> {
}
| apache-2.0 |
cursem/ScriptCompressor | ScriptCompressor1.0/src/dk/brics/tajs/analysis/State.java | 1579 | /*
* Copyright 2009-2013 Aarhus University
*
* 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 dk.brics.tajs.analysis;
import dk.brics.tajs.flowgraph.BasicBlock;
import dk.brics.tajs.lattice.BlockState;
import dk.brics.tajs.lattice.CallEdge;
import dk.brics.tajs.solver.GenericSolver;
/**
* Abstract state.
*/
public final class State extends BlockState<State,Context,CallEdge<State>> {
/**
* Constructs a new abstract state.
*/
public State(GenericSolver<State,Context,CallEdge<State>,?,?>.SolverInterface c, BasicBlock block) {
super(c, block);
}
private State(State x) {
super(x);
}
@Override
public State clone() {
return new State(this);
}
@Override
public String diff(State old) {
return super.diff((BlockState<State,Context,CallEdge<State>>)old);
}
@Override
public void remove(State other) {
super.remove((BlockState<State,Context,CallEdge<State>>)other);
}
@Override
public boolean propagate(State s, boolean funentry) {
return super.propagate((BlockState<State,Context,CallEdge<State>>)s, funentry);
}
}
| apache-2.0 |
ruediste/i18n | i18n/src/main/java/com/github/ruediste1/i18n/messageFormat/formatTypeParsers/TimeParser.java | 1234 | package com.github.ruediste1.i18n.messageFormat.formatTypeParsers;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.HashMap;
import java.util.Map;
import com.github.ruediste.lambdaPegParser.DefaultParsingContext;
public class TimeParser extends DateTimeParserBase {
public TimeParser(DefaultParsingContext ctx) {
super(ctx);
}
private static Map<String, DateTimeFormatter> formatters = new HashMap<>();
static {
formatters.put("short",
DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
formatters.put("medium",
DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
formatters.put("long",
DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG));
formatters.put("full",
DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL));
formatters.put("iso", DateTimeFormatter.ISO_TIME);
formatters.put("isoLocal", DateTimeFormatter.ISO_LOCAL_TIME);
formatters.put("isoOffset", DateTimeFormatter.ISO_OFFSET_TIME);
}
@Override
protected Map<java.lang.String, DateTimeFormatter> getFormatters() {
return formatters;
}
@Override
protected DateTimeFormatter getDefaultFormatter() {
return DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
}
} | apache-2.0 |
signed/intellij-community | java/java-impl/src/com/intellij/codeInsight/intention/impl/DeannotateIntentionAction.java | 7783 | /*
* Copyright 2000-2016 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.
*/
/*
* User: anna
* Date: 08-Jul-2007
*/
package com.intellij.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.ExternalAnnotationsManager;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class DeannotateIntentionAction implements IntentionAction, LowPriorityAction {
private static final Logger LOG = Logger.getInstance(DeannotateIntentionAction.class);
private String myAnnotationName;
@Override
@NotNull
public String getText() {
return CodeInsightBundle.message("deannotate.intention.action.text") + (myAnnotationName != null ? " " + myAnnotationName : "...");
}
@Override
@NotNull
public String getFamilyName() {
return CodeInsightBundle.message("deannotate.intention.action.text");
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
myAnnotationName = null;
PsiModifierListOwner listOwner = getContainer(editor, file);
if (listOwner != null) {
final ExternalAnnotationsManager externalAnnotationsManager = ExternalAnnotationsManager.getInstance(project);
final PsiAnnotation[] annotations = externalAnnotationsManager.findExternalAnnotations(listOwner);
if (annotations != null && annotations.length > 0) {
if (annotations.length == 1) {
myAnnotationName = annotations[0].getQualifiedName();
}
final List<PsiFile> files = externalAnnotationsManager.findExternalAnnotationsFiles(listOwner);
if (files == null || files.isEmpty()) return false;
final VirtualFile virtualFile = files.get(0).getVirtualFile();
return virtualFile != null && (virtualFile.isWritable() || virtualFile.isInLocalFileSystem());
}
}
return false;
}
@Nullable
public static PsiModifierListOwner getContainer(final Editor editor, final PsiFile file) {
final PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false);
if (listOwner == null) {
final PsiIdentifier psiIdentifier = PsiTreeUtil.getParentOfType(element, PsiIdentifier.class, false);
if (psiIdentifier != null && psiIdentifier.getParent() instanceof PsiModifierListOwner) {
listOwner = (PsiModifierListOwner)psiIdentifier.getParent();
} else {
PsiExpression expression = PsiTreeUtil.getParentOfType(element, PsiExpression.class);
if (expression != null) {
while (expression.getParent() instanceof PsiExpression) { //get top level expression
expression = (PsiExpression)expression.getParent();
if (expression instanceof PsiAssignmentExpression) break;
}
if (expression instanceof PsiMethodCallExpression) {
final PsiMethod psiMethod = ((PsiMethodCallExpression)expression).resolveMethod();
if (psiMethod != null) {
return psiMethod;
}
}
final PsiElement parent = expression.getParent();
if (parent instanceof PsiExpressionList) { //try to find corresponding formal parameter
int idx = -1;
final PsiExpression[] args = ((PsiExpressionList)parent).getExpressions();
for (int i = 0; i < args.length; i++) {
PsiExpression arg = args[i];
if (PsiTreeUtil.isAncestor(arg, expression, false)) {
idx = i;
break;
}
}
if (idx > -1) {
PsiElement grParent = parent.getParent();
if (grParent instanceof PsiCall) {
PsiMethod method = ((PsiCall)grParent).resolveMethod();
if (method != null) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length > idx) {
return parameters[idx];
}
}
}
}
}
}
}
}
return listOwner;
}
@Override
public void invoke(@NotNull final Project project, Editor editor, final PsiFile file) throws IncorrectOperationException {
final PsiModifierListOwner listOwner = getContainer(editor, file);
LOG.assertTrue(listOwner != null);
final ExternalAnnotationsManager annotationsManager = ExternalAnnotationsManager.getInstance(project);
final PsiAnnotation[] externalAnnotations = annotationsManager.findExternalAnnotations(listOwner);
LOG.assertTrue(externalAnnotations != null && externalAnnotations.length > 0);
if (externalAnnotations.length == 1) {
deannotate(externalAnnotations[0], project, file, annotationsManager, listOwner);
return;
}
JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<PsiAnnotation>(CodeInsightBundle.message("deannotate.intention.chooser.title"), externalAnnotations) {
@Override
public PopupStep onChosen(final PsiAnnotation selectedValue, final boolean finalChoice) {
deannotate(selectedValue, project, file, annotationsManager, listOwner);
return PopupStep.FINAL_CHOICE;
}
@Override
@NotNull
public String getTextFor(final PsiAnnotation value) {
final String qualifiedName = value.getQualifiedName();
LOG.assertTrue(qualifiedName != null);
return qualifiedName;
}
}).showInBestPositionFor(editor);
}
private void deannotate(final PsiAnnotation annotation,
final Project project,
final PsiFile file,
final ExternalAnnotationsManager annotationsManager,
final PsiModifierListOwner listOwner) {
new WriteCommandAction(project, getText()) {
@Override
protected void run(@NotNull final Result result) throws Throwable {
final VirtualFile virtualFile = file.getVirtualFile();
String qualifiedName = annotation.getQualifiedName();
LOG.assertTrue(qualifiedName != null);
if (annotationsManager.deannotate(listOwner, qualifiedName) && virtualFile != null && virtualFile.isInLocalFileSystem()) {
UndoUtil.markPsiFileForUndo(file);
}
}
}.execute();
}
@Override
public boolean startInWriteAction() {
return false;
}
} | apache-2.0 |
testory/testory | main/java/org/testory/common/DelegatingMatcher.java | 404 | package org.testory.common;
import static java.util.Objects.requireNonNull;
public class DelegatingMatcher implements Matcher {
private final Matcher matcher;
public DelegatingMatcher(Matcher matcher) {
this.matcher = requireNonNull(matcher);
}
public boolean matches(Object item) {
return matcher.matches(item);
}
public String toString() {
return matcher.toString();
}
}
| apache-2.0 |
mhusar/lemming | src/main/java/lemming/character/CharacterDao.java | 10873 | package lemming.character;
import lemming.data.EntityManagerListener;
import lemming.data.GenericDao;
import org.hibernate.StaleObjectStateException;
import org.hibernate.UnresolvableObjectException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.UUID;
/**
* Represents a Data Access Object providing data operations for special
* characters.
*/
public class CharacterDao extends GenericDao<Character> implements ICharacterDao {
/**
* Creates an instance of a CharacterDao.
*/
public CharacterDao() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public Boolean isTransient(Character character) {
return character.getId() == null;
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public void persist(Character character) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
if (character.getUuid() == null) {
character.setUuid(UUID.randomUUID().toString());
}
try {
transaction = entityManager.getTransaction();
transaction.begin();
insertCharacter(entityManager, character);
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(character, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(character, e);
} else {
throw e;
}
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public Character merge(Character character) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<Character> query = entityManager
.createQuery("FROM Character WHERE id = :id", Character.class);
query.setParameter("id", character.getId());
Character persistentCharacter = query.getSingleResult();
Character mergedCharacter = moveCharacter(entityManager, character, persistentCharacter);
transaction.commit();
return mergedCharacter;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(character, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(character, e);
} else {
throw e;
}
return null;
} finally {
entityManager.close();
}
}
/**
* Inserts a character at the specified position. Shifts subsequent elements
* to the right.
*
* @param entityManager entity manager interacting with the persistence context
* @param character a character object
* @throws RuntimeException
*/
private void insertCharacter(EntityManager entityManager, Character character) throws RuntimeException {
TypedQuery<Character> query = entityManager
.createQuery("FROM Character WHERE position >= :position ORDER BY position DESC", Character.class);
query.setParameter("position", character.getPosition());
List<Character> elements = query.getResultList();
for (Character element : elements) {
element.setPosition(element.getPosition() + 1);
entityManager.merge(element);
entityManager.flush();
entityManager.clear();
}
entityManager.persist(character);
}
/**
* Moves a persistent character to a new position.
*
* @param entityManager entity manager interacting with the persistence context
* @param character the new character
* @param persistentCharacter the persistent character
* @throws RuntimeException
*/
private Character moveCharacter(EntityManager entityManager, Character character, Character persistentCharacter)
throws RuntimeException {
Integer position = character.getPosition();
Integer persistentPosition = persistentCharacter.getPosition();
Integer minPosition = Math.min(position, persistentPosition);
Integer maxPosition = Math.max(position, persistentPosition);
if (minPosition.equals(maxPosition)) {
return entityManager.merge(character);
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Character> criteriaQuery = builder.createQuery(Character.class);
Root<Character> root = criteriaQuery.from(Character.class);
criteriaQuery.select(root);
Order elementOrder;
if (position.equals(minPosition)) {
elementOrder = builder.desc(root.<Integer>get("position"));
} else {
elementOrder = builder.asc(root.<Integer>get("position"));
}
criteriaQuery.where(builder.and(builder.ge(root.<Integer>get("position"), minPosition)),
builder.le(root.<Integer>get("position"), maxPosition)).orderBy(elementOrder);
List<Character> elements = entityManager.createQuery(criteriaQuery).getResultList();
elements.remove(persistentCharacter);
character.setPosition(0);
character = entityManager.merge(character);
entityManager.flush();
entityManager.clear();
for (Character element : elements) {
if (position.equals(minPosition)) {
element.setPosition(maxPosition--);
} else {
element.setPosition(minPosition++);
}
entityManager.merge(element);
entityManager.flush();
entityManager.clear();
}
character.setPosition(position);
return entityManager.merge(character);
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public void remove(Character character) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<Character> query = entityManager
.createQuery("FROM Character WHERE id = :id", Character.class);
query.setParameter("id", character.getId());
Character persistentCharacter = query.getSingleResult();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Character> criteriaQuery = builder.createQuery(Character.class);
Root<Character> root = criteriaQuery.from(Character.class);
criteriaQuery.select(root);
criteriaQuery.where(builder.gt(root.<Integer>get("position"), persistentCharacter.getPosition()))
.orderBy(builder.asc(root.<Integer>get("position")));
List<Character> elements = entityManager.createQuery(criteriaQuery).getResultList();
entityManager.remove(persistentCharacter);
entityManager.flush();
entityManager.clear();
for (Character element : elements) {
element.setPosition(element.getPosition() - 1);
entityManager.merge(element);
entityManager.flush();
entityManager.clear();
}
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public Character findByCharacter(String characterString) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<Character> query = entityManager
.createQuery("FROM Character WHERE character = :character", Character.class);
List<Character> characterList = query.setParameter("character", characterString).getResultList();
transaction.commit();
if (characterList.isEmpty()) {
return null;
} else {
return characterList.get(0);
}
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public List<Character> getAll() throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<Character> query = entityManager
.createQuery("FROM Character ORDER BY position ASC", Character.class);
List<Character> characterList = query.getResultList();
transaction.commit();
return characterList;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
}
| apache-2.0 |
troter/s2mai-oreo | s2mai-oreo/src/test/java/jp/troter/seasar/mai/SendMailTest.java | 2158 | /*
* Copyright 2011 Takumi IINO
*
* 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 jp.troter.seasar.mai;
import jp.troter.seasar.mai.MailSend.Mail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seasar.framework.unit.Seasar2;
import org.seasar.framework.util.TextUtil;
import org.seasar.mai.mail.MailAddress;
@RunWith(Seasar2.class)
public class SendMailTest {
private String mailAddress;
@Test
public void smoke() {
send(new MailSendFactory(), MailCharset.UTF_8);
send(new MailSendFactory(), MailCharset.ISO_2022_JP);
}
public void send(MailSendFactory factory, MailCharset charset) {
MailSend sender = factory.getMailSender(charset);
sender.sendMail(createMailText(mailAddress, mailAddress, "テキストメールサンプル(" + charset.getCharset() + ")", TextUtil.readUTF8("sample.txt")));
sender.sendMail(createMailHtml(mailAddress, mailAddress, "HTMLメールサンプル(" + charset.getCharset() + ")", TextUtil.readUTF8("sample.html")));
}
public Mail createMailText(String from, String to, String subject, String text) {
return createMail(from, to, subject, text, false);
}
public Mail createMailHtml(String from, String to, String subject, String text) {
return createMail(from, to, subject, text, true);
}
public Mail createMail(String from, String to, String subject, String text, boolean html) {
Mail m = new Mail();
m.setFrom(new MailAddress(from));
m.setTo(to);
m.setSubject(subject);
m.setText(text);
m.setHtml(html);
return m;
}
}
| apache-2.0 |
hawkular/hawkular-agent | hawkular-javaagent/src/test/java/org/hawkular/agent/javaagent/config/ConfigCopyTest.java | 7366 | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.agent.javaagent.config;
import java.io.File;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
/**
* This tests the copy constructors in all the YAML POJOs.
*/
public class ConfigCopyTest {
@Test
public void testEmpty() throws Exception {
Configuration config = loadTestConfigFile("/empty.yaml");
Configuration clone = new Configuration(config);
Assert.assertEquals(clone.getSubsystem().getEnabled(), config.getSubsystem().getEnabled());
}
@Test
public void testRealConfig() throws Exception {
Configuration config = loadTestConfigFile("/wildfly10/hawkular-javaagent-config.yaml");
Configuration clone = new Configuration(config);
Assert.assertEquals(clone.getSubsystem().getEnabled(), config.getSubsystem().getEnabled());
Assert.assertEquals(clone.getStorageAdapter().getUrl(), config.getStorageAdapter().getUrl());
Assert.assertEquals(clone.getDiagnostics().getEnabled(), config.getDiagnostics().getEnabled());
Assert.assertEquals(clone.getDmrMetricSets().length, config.getDmrMetricSets().length);
Assert.assertEquals(clone.getDmrResourceTypeSets().length, config.getDmrResourceTypeSets().length);
Assert.assertEquals(clone.getJmxMetricSets().length, config.getJmxMetricSets().length);
Assert.assertEquals(clone.getJmxResourceTypeSets().length, config.getJmxResourceTypeSets().length);
Assert.assertEquals(clone.getManagedServers().getLocalDmr().getName(),
config.getManagedServers().getLocalDmr().getName());
Assert.assertEquals(clone.getManagedServers().getLocalJmx().getName(),
config.getManagedServers().getLocalJmx().getName());
Assert.assertEquals(clone.getManagedServers().getRemoteDmrs()[0].getName(),
config.getManagedServers().getRemoteDmrs()[0].getName());
Assert.assertNull(clone.getManagedServers().getRemoteJmxs());
Assert.assertEquals(clone.getPlatform().getEnabled(), config.getPlatform().getEnabled());
Assert.assertEquals(clone.getPlatform().getFileStores().getEnabled(),
config.getPlatform().getFileStores().getEnabled());
Assert.assertEquals(clone.getPlatform().getMemory().getEnabled(),
config.getPlatform().getMemory().getEnabled());
Assert.assertEquals(clone.getPlatform().getProcessors().getEnabled(),
config.getPlatform().getProcessors().getEnabled());
Assert.assertEquals(clone.getPlatform().getPowerSources().getEnabled(),
config.getPlatform().getPowerSources().getEnabled());
Assert.assertEquals(clone.getPlatform().getMachineId(), config.getPlatform().getMachineId());
Assert.assertEquals(clone.getPlatform().getContainerId(), config.getPlatform().getContainerId());
}
@Test
public void testConvertConfig() throws Exception {
Configuration config = loadTestConfigFile("/test-convert.yaml");
Configuration clone = new Configuration(config);
Assert.assertEquals(clone.getSubsystem().getEnabled(), config.getSubsystem().getEnabled());
Assert.assertEquals(clone.getMetricsExporter().getEnabled(), config.getMetricsExporter().getEnabled());
Assert.assertEquals(clone.getMetricsExporter().getHost(), config.getMetricsExporter().getHost());
Assert.assertEquals(clone.getMetricsExporter().getPort(), config.getMetricsExporter().getPort());
Assert.assertEquals(clone.getMetricsExporter().getConfigDir(), config.getMetricsExporter().getConfigDir());
Assert.assertEquals(clone.getMetricsExporter().getConfigFile(), config.getMetricsExporter().getConfigFile());
Assert.assertEquals(clone.getMetricsExporter().getProxy().getMode(),
config.getMetricsExporter().getProxy().getMode());
Assert.assertEquals(clone.getMetricsExporter().getProxy().getDataDir(),
config.getMetricsExporter().getProxy().getDataDir());
Assert.assertEquals(clone.getMetricsExporter().getProxy().getMetricLabelsExpression(),
config.getMetricsExporter().getProxy().getMetricLabelsExpression());
Assert.assertEquals(clone.getStorageAdapter().getUrl(), config.getStorageAdapter().getUrl());
Assert.assertEquals(clone.getDiagnostics().getEnabled(), config.getDiagnostics().getEnabled());
Assert.assertEquals(clone.getDmrMetricSets().length, config.getDmrMetricSets().length);
Assert.assertEquals(clone.getDmrResourceTypeSets().length, config.getDmrResourceTypeSets().length);
Assert.assertEquals(clone.getJmxMetricSets().length, config.getJmxMetricSets().length);
Assert.assertEquals(clone.getJmxResourceTypeSets().length, config.getJmxResourceTypeSets().length);
Assert.assertEquals(clone.getManagedServers().getLocalDmr().getName(),
config.getManagedServers().getLocalDmr().getName());
Assert.assertEquals(clone.getManagedServers().getLocalJmx().getName(),
config.getManagedServers().getLocalJmx().getName());
Assert.assertEquals(clone.getManagedServers().getRemoteDmrs()[0].getName(),
config.getManagedServers().getRemoteDmrs()[0].getName());
Assert.assertEquals(clone.getManagedServers().getRemoteJmxs()[0].getName(),
config.getManagedServers().getRemoteJmxs()[0].getName());
Assert.assertEquals(clone.getPlatform().getEnabled(), config.getPlatform().getEnabled());
Assert.assertEquals(clone.getPlatform().getFileStores().getEnabled(),
config.getPlatform().getFileStores().getEnabled());
Assert.assertEquals(clone.getPlatform().getMemory().getEnabled(),
config.getPlatform().getMemory().getEnabled());
Assert.assertEquals(clone.getPlatform().getProcessors().getEnabled(),
config.getPlatform().getProcessors().getEnabled());
Assert.assertEquals(clone.getPlatform().getPowerSources().getEnabled(),
config.getPlatform().getPowerSources().getEnabled());
Assert.assertEquals(clone.getPlatform().getMachineId(), config.getPlatform().getMachineId());
Assert.assertEquals(clone.getPlatform().getContainerId(), config.getPlatform().getContainerId());
}
private Configuration loadTestConfigFile(String path) throws Exception {
URL url = ConfigCopyTest.class.getResource(path);
Assert.assertNotNull("yaml config file not found", url);
File file = new File(url.toURI());
ConfigManager configManager = new ConfigManager(file);
return configManager.getConfiguration(false);
}
}
| apache-2.0 |
djsilenceboy/LearnTest | Java_Learn/LearnDesignPattern/src/com/djs/learn/behavioral/mediator/Mediator.java | 998 |
package com.djs.learn.behavioral.mediator;
import java.util.Map;
import java.util.TreeMap;
public class Mediator implements MediatorInterface
{
int idCount = 0;
Map<Integer, ColleagueInterface> colleagues = new TreeMap<Integer, ColleagueInterface>();
public Mediator(){
System.out.println("Create mediator.");
}
@Override
public void registerColleague(ColleagueInterface colleague){
colleague.setId(idCount);
colleague.setMediator(this);
colleagues.put(idCount, colleague);
System.out.println("Register colleague <" + idCount + ">.");
idCount++;
}
@Override
public void sendMessage(int fromId, int toId, String message){
ColleagueInterface colleague = colleagues.get(new Integer(toId));
if (colleague == null) {
System.out.println("Send message from colleague <" + fromId + "> to <Unknown>");
} else {
System.out.println("Send message from colleague <" + fromId + "> to <" + toId + ">: " + message);
colleague.receiveMessage(fromId, message);
}
}
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/corefoundation/enums/CFDateFormatterStyle.java | 1894 | /*
Copyright 2014-2016 Intel Corporation
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 apple.corefoundation.enums;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;
/**
* The exact formatted result for these date and time styles depends on the
* locale, but generally:
* Short is completely numeric, such as "12/13/52" or "3:30pm"
* Medium is longer, such as "Jan 12, 1952"
* Long is longer, such as "January 12, 1952" or "3:30:32pm"
* Full is pretty complete; e.g. "Tuesday, April 12, 1952 AD" or "3:30:42pm PST"
* The specifications though are left fuzzy, in part simply because a user's
* preference choices may affect the output, and also the results may change
* from one OS release to another. To produce an exactly formatted date you
* should not rely on styles and localization, but set the format string and
* use nothing but numbers.
*/
@Generated
public final class CFDateFormatterStyle {
@Generated @NInt public static final long NoStyle = 0x0000000000000000L;
@Generated @NInt public static final long ShortStyle = 0x0000000000000001L;
@Generated @NInt public static final long MediumStyle = 0x0000000000000002L;
@Generated @NInt public static final long LongStyle = 0x0000000000000003L;
@Generated @NInt public static final long FullStyle = 0x0000000000000004L;
@Generated
private CFDateFormatterStyle() {
}
}
| apache-2.0 |
java-prolog-connectivity/jpc | src/main/java/org/jpc/util/termprocessor/PrologAbstractWriter.java | 2773 | package org.jpc.util.termprocessor;
import org.jpc.JpcException;
import org.jpc.engine.dialect.Dialect;
import org.jpc.term.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class PrologAbstractWriter implements TermProcessor {
private static final Logger logger = LoggerFactory.getLogger(PrologAbstractWriter.class);
private final Dialect dialect;
private boolean writeDirective;
private boolean writeClause;
private boolean readingLogtalkObjectTerm;
private Term currentLogtalkObjectTerm;
public PrologAbstractWriter() {
this(Dialect.JPC);
}
public PrologAbstractWriter(Dialect dialect) {
this.dialect = dialect;
}
public Dialect getDialect() {
return dialect;
}
private void resetLogtalkOjectTerm() {
currentLogtalkObjectTerm = null;
}
private void setCurrentLogtalkObjectTerm(Term logtalkObjectTerm) {
this.currentLogtalkObjectTerm = logtalkObjectTerm;
}
public Term getCurrentLogtalkObjectTerm() {
return currentLogtalkObjectTerm;
}
@Override
public void accept(Term term) {
if(readingLogtalkObjectTerm) {
setCurrentLogtalkObjectTerm(term); //the read term is the logtalk object context for the instructions that come next
readingLogtalkObjectTerm = false;
} else if(writeDirective) {
writeDirective(term); //the directive should be executed
} else if(writeClause) {
writeClause(term); //the clause should be asserted
} else
throw new JpcException("A writing mode has not been set");
}
private void resetWritingMode() {
writeDirective = false;
writeClause = false;
readingLogtalkObjectTerm = false;
}
//next read terms will be interpreted as goals to be executed
public void followingDirectives() {
resetWritingMode();
writeDirective = true;
}
//next read terms will be considered as clauses to be asserted
public void followingClauses() {
resetWritingMode();
writeClause = true;
}
public void startLogtalkObjectContext() {
readingLogtalkObjectTerm = true; //the next term to come will be considered the logtalk object context
}
public void endLogtalkObjectContext() {
readingLogtalkObjectTerm = false;
resetLogtalkOjectTerm();
}
public void writeDirective(Term directive) {
if(getCurrentLogtalkObjectTerm() == null)
writePrologDirective(directive);
else
writeLogtalkObjectDirective(directive);
}
public abstract void writePrologDirective(Term directive);
public abstract void writeLogtalkObjectDirective(Term directive);
public void writeClause(Term clause) {
if(getCurrentLogtalkObjectTerm() == null)
writePrologClause(clause);
else
writeLogtalkObjectClause(clause);
}
public abstract void writePrologClause(Term clause);
public abstract void writeLogtalkObjectClause(Term clause);
}
| apache-2.0 |
konduruvijaykumar/springboot-examples | springboot-data-jpa/src/main/java/org/pjay/ServletInitializer.java | 430 | package org.pjay;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
* @author vijayk
*
*/
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootDataJpaApplication.class);
}
}
| apache-2.0 |
lynchlee/play-jmx | src/main/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java | 13122 | /*
* 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.thrift;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions;
import org.apache.cassandra.utils.JVMStabilityInspector;
import org.apache.cassandra.security.SSLFactory;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TSSLTransportFactory.TSSLTransportParameters;
import com.google.common.util.concurrent.Uninterruptibles;
/**
* Slightly modified version of the Apache Thrift TThreadPoolServer.
* <p>
* This allows passing an executor so you have more control over the actual
* behaviour of the tasks being run.
* <p/>
* Newer version of Thrift should make this obsolete.
*/
public class CustomTThreadPoolServer extends TServer
{
private static final Logger logger = LoggerFactory.getLogger(CustomTThreadPoolServer.class.getName());
// Executor service for handling client connections
private final ExecutorService executorService;
// Flag for stopping the server
private volatile boolean stopped;
// Server options
private final TThreadPoolServer.Args args;
//Track and Limit the number of connected clients
private final AtomicInteger activeClients = new AtomicInteger(0);
public CustomTThreadPoolServer(TThreadPoolServer.Args args, ExecutorService executorService) {
super(args);
this.executorService = executorService;
this.args = args;
}
@SuppressWarnings("resource")
public void serve()
{
try
{
serverTransport_.listen();
}
catch (TTransportException ttx)
{
logger.error("Error occurred during listening.", ttx);
return;
}
stopped = false;
while (!stopped)
{
// block until we are under max clients
while (activeClients.get() >= args.maxWorkerThreads)
{
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
}
try
{
TTransport client = serverTransport_.accept();
activeClients.incrementAndGet();
WorkerProcess wp = new WorkerProcess(client);
executorService.execute(wp);
}
catch (TTransportException ttx)
{
if (ttx.getCause() instanceof SocketTimeoutException) // org.apache.cassandra.thrift.thrift sucks
continue;
if (!stopped)
{
logger.warn("Transport error occurred during acceptance of message.", ttx);
}
}
catch (RejectedExecutionException e)
{
// worker thread decremented activeClients but hadn't finished exiting
logger.trace("Dropping client connection because our limit of {} has been reached", args.maxWorkerThreads);
continue;
}
if (activeClients.get() >= args.maxWorkerThreads)
logger.warn("Maximum number of clients {} reached", args.maxWorkerThreads);
}
executorService.shutdown();
// Thrift's default shutdown waits for the WorkerProcess threads to complete. We do not,
// because doing that allows a client to hold our shutdown "hostage" by simply not sending
// another message after stop is called (since process will block indefinitely trying to read
// the next meessage header).
//
// The "right" fix would be to update org.apache.cassandra.thrift.thrift to set a socket timeout on client connections
// (and tolerate unintentional timeouts until stopped is set). But this requires deep
// changes to the code generator, so simply setting these threads to daemon (in our custom
// CleaningThreadPool) and ignoring them after shutdown is good enough.
//
// Remember, our goal on shutdown is not necessarily that each client request we receive
// gets answered first [to do that, you should redirect clients to a different coordinator
// first], but rather (1) to make sure that for each update we ack as successful, we generate
// hints for any non-responsive replicas, and (2) to make sure that we quickly stop
// accepting client connections so shutdown can continue. Not waiting for the WorkerProcess
// threads here accomplishes (2); MessagingService's shutdown method takes care of (1).
//
// See CASSANDRA-3335 and CASSANDRA-3727.
}
public void stop()
{
stopped = true;
serverTransport_.interrupt();
}
private class WorkerProcess implements Runnable
{
/**
* Client that this services.
*/
private TTransport client_;
/**
* Default constructor.
*
* @param client Transport to process
*/
private WorkerProcess(TTransport client)
{
client_ = client;
}
/**
* Loops on processing a client forever
*/
public void run()
{
TProcessor processor = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
SocketAddress socket = null;
try (TTransport inputTransport = inputTransportFactory_.getTransport(client_);
TTransport outputTransport = outputTransportFactory_.getTransport(client_))
{
socket = ((TCustomSocket) client_).getSocket().getRemoteSocketAddress();
ThriftSessionManager.instance.setCurrentSocket(socket);
processor = processorFactory_.getProcessor(client_);
inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
// we check stopped first to make sure we're not supposed to be shutting
// down. this is necessary for graceful shutdown. (but not sufficient,
// since process() can take arbitrarily long waiting for client input.
// See comments at the end of serve().)
while (!stopped && processor.process(inputProtocol, outputProtocol))
{
inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
}
}
catch (TTransportException ttx)
{
// Assume the client died and continue silently
// Log at debug to allow debugging of "frame too large" errors (see CASSANDRA-3142).
logger.trace("Thrift transport error occurred during processing of message.", ttx);
}
catch (TException tx)
{
logger.error("Thrift error occurred during processing of message.", tx);
}
catch (Exception e)
{
JVMStabilityInspector.inspectThrowable(e);
logger.error("Error occurred during processing of message.", e);
}
finally
{
if (socket != null)
ThriftSessionManager.instance.connectionComplete(socket);
activeClients.decrementAndGet();
}
}
}
public static class Factory implements TServerFactory
{
@SuppressWarnings("resource")
public TServer buildTServer(Args args)
{
final InetSocketAddress addr = args.addr;
TServerTransport serverTransport;
try
{
final ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
if (clientEnc.enabled)
{
logger.info("enabling encrypted org.apache.cassandra.thrift.thrift connections between client and server");
TSSLTransportParameters params = new TSSLTransportParameters(clientEnc.protocol, new String[0]);
params.setKeyStore(clientEnc.keystore, clientEnc.keystore_password);
if (clientEnc.require_client_auth)
{
params.setTrustStore(clientEnc.truststore, clientEnc.truststore_password);
params.requireClientAuth(true);
}
TServerSocket sslServer = TSSLTransportFactory.getServerSocket(addr.getPort(), 0, addr.getAddress(), params);
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServer.getServerSocket();
String[] suites = SSLFactory.filterCipherSuites(sslServerSocket.getSupportedCipherSuites(), clientEnc.cipher_suites);
sslServerSocket.setEnabledCipherSuites(suites);
sslServerSocket.setEnabledProtocols(SSLFactory.ACCEPTED_PROTOCOLS);
serverTransport = new TCustomServerSocket(sslServer.getServerSocket(), args.keepAlive, args.sendBufferSize, args.recvBufferSize);
}
else
{
serverTransport = new TCustomServerSocket(addr, args.keepAlive, args.sendBufferSize, args.recvBufferSize, args.listenBacklog);
}
}
catch (TTransportException e)
{
throw new RuntimeException(String.format("Unable to create org.apache.cassandra.thrift.thrift socket to %s:%s", addr.getAddress(), addr.getPort()), e);
}
// ThreadPool Server and will be invocation per connection basis...
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport)
.minWorkerThreads(DatabaseDescriptor.getRpcMinThreads())
.maxWorkerThreads(DatabaseDescriptor.getRpcMaxThreads())
.inputTransportFactory(args.inTransportFactory)
.outputTransportFactory(args.outTransportFactory)
.inputProtocolFactory(args.tProtocolFactory)
.outputProtocolFactory(args.tProtocolFactory)
.processor(args.processor);
ExecutorService executorService = new ThreadPoolExecutor(serverArgs.minWorkerThreads,
serverArgs.maxWorkerThreads,
60,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("Thrift"));
return new CustomTThreadPoolServer(serverArgs, executorService);
}
}
}
| apache-2.0 |
dsukhoroslov/bagri | bagri-samples/bagri-samples-client/src/main/java/com/bagri/samples/client/xqj/XQJClientSpringApp.java | 829 | package com.bagri.samples.client.xqj;
import java.util.Properties;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XQJClientSpringApp extends XQJClientApp {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/xqj-client-context.xml");
XQConnection xqc = context.getBean("xqConnection", XQConnection.class);
XQJClientSpringApp client = new XQJClientSpringApp(xqc);
tester.testClient(client);
}
public XQJClientSpringApp(Properties props) throws XQException {
super(props);
}
public XQJClientSpringApp(XQConnection xqConn) {
super(xqConn);
}
}
| apache-2.0 |
atcult/mod-cataloging | src/main/java/org/folio/marccat/business/common/group/GroupManager.java | 356 | package org.folio.marccat.business.common.group;
import org.folio.marccat.business.cataloguing.common.Tag;
import org.folio.marccat.exception.DataAccessException;
public interface GroupManager {
TagGroup getGroup(Tag tag) throws DataAccessException;
boolean isSameGroup(Tag tag1, Tag tag2) throws DataAccessException;
void add(TagGroup group);
}
| apache-2.0 |
smanvi-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/cache/DiskRegionChangingRegionAttributesJUnitTest.java | 3454 | /*
* 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.cache;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Scope;
import org.apache.geode.test.junit.categories.IntegrationTest;
/**
* This test will test that there are no unexpected behaviours if the the region attributes are
* changed after starting it again.
*
* The behaviour should be predictable
*/
@Category(IntegrationTest.class)
public class DiskRegionChangingRegionAttributesJUnitTest extends DiskRegionTestingBase {
private DiskRegionProperties props;
@Override
protected final void postSetUp() throws Exception {
props = new DiskRegionProperties();
props.setDiskDirs(dirs);
}
private void createOverflowOnly() {
props.setOverFlowCapacity(1);
region = DiskRegionHelperFactory.getSyncOverFlowOnlyRegion(cache, props);
}
private void createPersistOnly() {
region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, props, Scope.LOCAL);
}
private void createPersistAndOverflow() {
region = DiskRegionHelperFactory.getSyncOverFlowAndPersistRegion(cache, props);
}
@Test
public void testOverflowOnlyAndThenPersistOnly() {
createOverflowOnly();
put100Int();
region.close();
createPersistOnly();
assertTrue(region.size() == 0);
}
@Test
public void testPersistOnlyAndThenOverflowOnly() {
createPersistOnly();
put100Int();
region.close();
try {
createOverflowOnly();
fail("expected IllegalStateException");
} catch (IllegalStateException expected) {
}
// Asif Recreate the region so that it gets destroyed in teardown
// clearing up the old Oplogs
createPersistOnly();
}
@Test
public void testOverflowOnlyAndThenPeristAndOverflow() {
createOverflowOnly();
put100Int();
region.close();
createPersistAndOverflow();
assertTrue(region.size() == 0);
}
@Test
public void testPersistAndOverflowAndThenOverflowOnly() {
createPersistAndOverflow();
put100Int();
region.close();
try {
createOverflowOnly();
fail("expected IllegalStateException");
} catch (IllegalStateException expected) {
}
createPersistAndOverflow();
}
@Test
public void testPersistOnlyAndThenPeristAndOverflow() {
createPersistOnly();
put100Int();
region.close();
createPersistAndOverflow();
assertTrue(region.size() == 100);
}
@Test
public void testPersistAndOverflowAndThenPersistOnly() {
createPersistAndOverflow();
put100Int();
region.close();
createPersistOnly();
assertTrue(region.size() == 100);
}
}
| apache-2.0 |
EvilMcJerkface/crate | server/src/test/java/io/crate/expression/scalar/SubscriptFunctionTest.java | 2863 | /*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.expression.scalar;
import io.crate.exceptions.ConversionException;
import io.crate.expression.symbol.Literal;
import io.crate.expression.symbol.SelectSymbol;
import org.hamcrest.Matchers;
import org.junit.Test;
import java.util.List;
import static io.crate.testing.SymbolMatchers.isFunction;
import static io.crate.testing.SymbolMatchers.isLiteral;
public class SubscriptFunctionTest extends AbstractScalarFunctionsTest {
@Test
public void test_long_can_be_used_as_array_index() {
assertEvaluate("['Youri', 'Ruben'][x]", "Youri", Literal.of(1L));
}
@Test
public void test_subscript_can_retrieve_items_of_objects_within_array() {
assertEvaluate("[{x=10}, {x=2}]['x']", List.of(10, 2));
}
@Test
public void test_subscript_can_be_used_on_subqueries_returning_objects() {
assertNormalize(
"(select {x=10})['x']",
isFunction("subscript", Matchers.instanceOf(SelectSymbol.class), isLiteral("x"))
);
}
@Test
public void testEvaluate() throws Exception {
assertNormalize("subscript(['Youri', 'Ruben'], cast(1 as integer))", isLiteral("Youri"));
}
@Test
public void testNormalizeSymbol() throws Exception {
assertNormalize("subscript(tags, cast(1 as integer))", isFunction("subscript"));
}
@Test
public void testIndexOutOfRange() throws Exception {
assertNormalize("subscript(['Youri', 'Ruben'], cast(3 as integer))", isLiteral(null));
}
@Test
public void testIndexExpressionIsNotInteger() throws Exception {
expectedException.expect(ConversionException.class);
expectedException.expectMessage("Cannot cast `'foo'` of type `text` to type `integer`");
assertNormalize("subscript(['Youri', 'Ruben'], 'foo')", isLiteral("Ruben"));
}
}
| apache-2.0 |
lfkdsk/Just-Evaluator | src/test/java/com/lfkdsk/justel/utils/GeneratedIdTest.java | 1625 | /*
* Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.lfkdsk.justel.utils;
import com.lfkdsk.justel.utils.logger.Logger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Hashtable;
/**
* Created by liufengkai on 2017/8/4.
*/
class GeneratedIdTest {
@Test
void testGenerateId() throws InterruptedException {
Logger.init("gen-code");
// need curr - table
for (int j = 0; j < 20; j++) {
// hash-table current-control is needed
Hashtable<Integer, Integer> set = new Hashtable<>();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
Integer integer = GeneratedId.generateAtomId();
if (set.contains(integer)) {
Logger.e(set.put(integer, set.get(integer) + 1).toString());
throw new RuntimeException("fuck");
} else {
set.put(integer, 1);
}
Logger.v(String.valueOf(integer));
}).start();
}
// just wait thread completed
Thread.sleep(1000);
Assertions.assertEquals(set.size(), 100);
}
}
} | apache-2.0 |
torrances/swtk-commons | commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p1/p3/WordnetNounIndexIdInstance1390.java | 13624 | package org.swtk.commons.dict.wordnet.indexbyid.instance.p1.p3; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance1390 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("13900047", "{\"term\":\"element\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"13900047\", \"13957498\", \"14864925\", \"08586108\", \"14647071\", \"03085025\", \"05877576\"]}");
add("13900186", "{\"term\":\"element of a cone\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900186\"]}");
add("13900306", "{\"term\":\"element of a cylinder\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900306\"]}");
add("13900424", "{\"term\":\"helix angle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900424\"]}");
add("13900557", "{\"term\":\"kink\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"05696575\", \"05934782\", \"10256539\", \"13900557\", \"14384587\"]}");
add("13900557", "{\"term\":\"twirl\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00344075\", \"13900557\"]}");
add("13900557", "{\"term\":\"twist\", \"synsetCount\":13, \"upperType\":\"NOUN\", \"ids\":[\"00346280\", \"00346467\", \"00535668\", \"05266995\", \"07366509\", \"07447573\", \"13891966\", \"13900557\", \"14322572\", \"00344075\", \"00172070\", \"07188610\", \"07437965\"]}");
add("13900751", "{\"term\":\"convolution\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"00405780\", \"05500078\", \"13900751\"]}");
add("13900751", "{\"term\":\"swirl\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900751\"]}");
add("13900751", "{\"term\":\"vortex\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"07447745\", \"13900751\"]}");
add("13900751", "{\"term\":\"whirl\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"00344075\", \"00788715\", \"13900751\", \"07456668\"]}");
add("13900945", "{\"term\":\"ellipse\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900945\"]}");
add("13900945", "{\"term\":\"oval\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13900945\"]}");
add("13901273", "{\"term\":\"foursquare\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13901273\"]}");
add("13901273", "{\"term\":\"square\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"04298380\", \"04298649\", \"10662243\", \"10662386\", \"13901590\", \"08637195\", \"13753131\", \"13901273\"]}");
add("13901590", "{\"term\":\"square\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"04298380\", \"04298649\", \"10662243\", \"10662386\", \"13901590\", \"08637195\", \"13753131\", \"13901273\"]}");
add("13901688", "{\"term\":\"quadrate\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13901688\", \"13940055\"]}");
add("13901783", "{\"term\":\"quadrangle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04036994\", \"13901783\"]}");
add("13901783", "{\"term\":\"quadrilateral\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13901783\"]}");
add("13901783", "{\"term\":\"tetragon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13901783\"]}");
add("13901977", "{\"term\":\"triangle\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04488109\", \"04488251\", \"09484854\", \"13902291\", \"13901977\"]}");
add("13901977", "{\"term\":\"trigon\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04490466\", \"08003213\", \"13901977\"]}");
add("13901977", "{\"term\":\"trilateral\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13901977\"]}");
add("13902291", "{\"term\":\"triangle\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04488109\", \"04488251\", \"09484854\", \"13902291\", \"13901977\"]}");
add("13902473", "{\"term\":\"acute-angled triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902473\"]}");
add("13902473", "{\"term\":\"acute triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902473\"]}");
add("13902604", "{\"term\":\"equiangular triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902604\"]}");
add("13902604", "{\"term\":\"equilateral triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902604\"]}");
add("13902759", "{\"term\":\"delta\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06847508\", \"13902759\", \"09287709\"]}");
add("13902856", "{\"term\":\"isosceles triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902856\"]}");
add("13902952", "{\"term\":\"oblique triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13902952\"]}");
add("13903072", "{\"term\":\"obtuse-angled triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903072\"]}");
add("13903072", "{\"term\":\"obtuse triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903072\"]}");
add("13903208", "{\"term\":\"right-angled triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903208\"]}");
add("13903208", "{\"term\":\"right triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903208\"]}");
add("13903361", "{\"term\":\"scalene triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903361\"]}");
add("13903468", "{\"term\":\"hexagram\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903468\"]}");
add("13903651", "{\"term\":\"parallel\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"13903651\", \"08613276\", \"04753670\"]}");
add("13903832", "{\"term\":\"parallelogram\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13903832\"]}");
add("13904038", "{\"term\":\"trapezium\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05280390\", \"09484199\", \"13904038\"]}");
add("13904169", "{\"term\":\"trapezoid\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05280572\", \"13904169\"]}");
add("13904301", "{\"term\":\"star\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"05738875\", \"06841439\", \"10183316\", \"13904301\", \"10668135\", \"09467687\", \"09781932\", \"09467004\"]}");
add("13904467", "{\"term\":\"asterism\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09231384\", \"13904467\"]}");
add("13904665", "{\"term\":\"pentacle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13904665\"]}");
add("13904665", "{\"term\":\"pentagram\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13904665\"]}");
add("13904665", "{\"term\":\"pentangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13904665\"]}");
add("13904858", "{\"term\":\"pentagon\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"13904858\", \"08224016\", \"03918615\"]}");
add("13904933", "{\"term\":\"hexagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13904933\"]}");
add("13905042", "{\"term\":\"regular hexagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905042\"]}");
add("13905144", "{\"term\":\"heptagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905144\"]}");
add("13905220", "{\"term\":\"octagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905220\"]}");
add("13905296", "{\"term\":\"nonagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905296\"]}");
add("13905370", "{\"term\":\"decagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905370\"]}");
add("13905461", "{\"term\":\"undecagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905461\"]}");
add("13905540", "{\"term\":\"dodecagon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905540\"]}");
add("13905618", "{\"term\":\"diamond\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"02783939\", \"02802752\", \"03192656\", \"13905618\", \"14858733\", \"13393131\"]}");
add("13905618", "{\"term\":\"rhomb\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905618\"]}");
add("13905618", "{\"term\":\"rhombus\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13905618\"]}");
add("13905790", "{\"term\":\"rhomboid\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05582633\", \"13905790\"]}");
add("13906003", "{\"term\":\"rectangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13906003\"]}");
add("13906151", "{\"term\":\"box\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"00135968\", \"02887252\", \"02887691\", \"02887848\", \"12766866\", \"13906151\", \"14432355\", \"13787764\", \"02887466\", \"02886585\"]}");
add("13906260", "{\"term\":\"spherical polygon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13906260\"]}");
add("13906420", "{\"term\":\"spherical triangle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13906420\"]}");
add("13906542", "{\"term\":\"polyhedron\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13906542\"]}");
add("13906918", "{\"term\":\"convex polyhedron\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13906918\"]}");
add("13907041", "{\"term\":\"concave polyhedron\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907041\"]}");
add("13907168", "{\"term\":\"prism\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04011716\", \"13907168\"]}");
add("13907397", "{\"term\":\"parallelepiped\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907397\"]}");
add("13907397", "{\"term\":\"parallelepipedon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907397\"]}");
add("13907397", "{\"term\":\"parallelopiped\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907397\"]}");
add("13907397", "{\"term\":\"parallelopipedon\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907397\"]}");
add("13907587", "{\"term\":\"cuboid\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907587\"]}");
add("13907668", "{\"term\":\"quadrangular prism\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907668\"]}");
add("13907768", "{\"term\":\"triangular prism\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907768\"]}");
add("13907864", "{\"term\":\"sinuosity\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907864\"]}");
add("13907864", "{\"term\":\"sinuousness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13907864\"]}");
add("13908063", "{\"term\":\"contortion\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13908063\", \"00405547\"]}");
add("13908063", "{\"term\":\"crookedness\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04882751\", \"05081387\", \"13908063\"]}");
add("13908063", "{\"term\":\"torsion\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11540135\", \"13908063\"]}");
add("13908063", "{\"term\":\"tortuosity\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13908063\"]}");
add("13908063", "{\"term\":\"tortuousness\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04773875\", \"13908063\"]}");
add("13908393", "{\"term\":\"buckle\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13908393\", \"02913678\"]}");
add("13908393", "{\"term\":\"warp\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"04559236\", \"07448702\", \"13908393\", \"14528328\"]}");
add("13908529", "{\"term\":\"gnarl\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13908529\"]}");
add("13908529", "{\"term\":\"knot\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"02031554\", \"04956082\", \"13908529\", \"15304617\", \"15127279\", \"03632523\", \"07976998\"]}");
add("13908826", "{\"term\":\"arch\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"02736529\", \"02737222\", \"05584204\", \"13908826\"]}");
add("13908953", "{\"term\":\"bell\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"02828000\", \"03020822\", \"10861809\", \"10861972\", \"10862171\", \"13908953\", \"15252389\", \"07391844\", \"03227219\", \"02827590\"]}");
add("13908953", "{\"term\":\"bell shape\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13908953\"]}");
add("13908953", "{\"term\":\"campana\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13908953\"]}");
add("13909064", "{\"term\":\"parabola\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13909064\"]}");
add("13909268", "{\"term\":\"hyperbola\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13909268\"]}");
add("13909417", "{\"term\":\"forking\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"00389200\", \"13909417\"]}");
add("13909417", "{\"term\":\"furcation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13909417\"]}");
add("13909603", "{\"term\":\"bifurcation\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"00389518\", \"13909603\", \"13909749\"]}");
add("13909749", "{\"term\":\"bifurcation\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"00389518\", \"13909603\", \"13909749\"]}");
add("13909904", "{\"term\":\"jog\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"00113817\", \"00295034\", \"13909904\"]}");
} private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } } | apache-2.0 |
InstaList/instalist-android-backend | src/androidTest/java/org/noorganization/instalist/presenter/IRecipeControllerTest.java | 8823 | /*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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.noorganization.instalist.presenter;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.Ingredient;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.Recipe;
import org.noorganization.instalist.provider.ProviderTestUtils;
import org.noorganization.instalist.provider.internal.IngredientProvider;
import org.noorganization.instalist.provider.internal.ProductProvider;
import org.noorganization.instalist.provider.internal.RecipeProvider;
public class IRecipeControllerTest extends AndroidTestCase {
Recipe mCheeseCake;
Recipe mPuffPastries;
Product mFlour;
Product mEgg;
Product mCurd;
Ingredient mIngredientFlourInCake;
Ingredient mIngredientCurdInCake;
IRecipeController mRecipeController;
IProductController mProductController;
ContentResolver mResolver;
public void setUp() throws Exception {
super.setUp();
mRecipeController = ControllerFactory.getRecipeController(mContext);
mProductController = ControllerFactory.getProductController(mContext);
mResolver = mContext.getContentResolver();
tearDown();
Uri cheeseCakeUri = ProviderTestUtils.insertRecipe(mResolver, "_TEST_cheesecake");
assertNotNull(cheeseCakeUri);
mCheeseCake = new Recipe(cheeseCakeUri.getLastPathSegment(), "_TEST_cheesecake");
Uri puffPastriesUri = ProviderTestUtils.insertRecipe(mResolver, "_TEST_puffpastries");
assertNotNull(puffPastriesUri);
mPuffPastries = new Recipe(puffPastriesUri.getLastPathSegment(), "_TEST_puffpastries");
Uri curdUri = ProviderTestUtils.insertProduct(mResolver, "_TEST_curd", 1.0f, 1.0f, null);
assertNotNull(curdUri);
mCurd = new Product(curdUri.getLastPathSegment(), "_TEST_curd", null, 1.0f, 1.0f);
Uri flourUri = ProviderTestUtils.insertProduct(mResolver, "_TEST_flour", 1.0f, 1.0f, null);
assertNotNull(flourUri);
mFlour = new Product(flourUri.getLastPathSegment(), "_TEST_flour", null, 1.0f, 1.0f);
Uri eggUri = ProviderTestUtils.insertProduct(mResolver, "_TEST_egg", 1.0f, 1.0f, null);
assertNotNull(eggUri);
mEgg = new Product(eggUri.getLastPathSegment(), "_TEST_egg", null, 1.0f, 1.0f);
Uri cheeseCakeFlourUri = ProviderTestUtils.insertIngredient(mResolver, mCheeseCake.mUUID, mFlour.mUUID, 0.3f);
assertNotNull(cheeseCakeFlourUri);
Uri cheeseCakeCurdUri = ProviderTestUtils.insertIngredient(mResolver, mCheeseCake.mUUID, mCurd.mUUID, 0.5f);
assertNotNull(cheeseCakeCurdUri);
mIngredientFlourInCake = new Ingredient(cheeseCakeFlourUri.getLastPathSegment(), mFlour,mCheeseCake, 0.3f);
mIngredientCurdInCake = new Ingredient(cheeseCakeCurdUri.getLastPathSegment(), mCurd,mCheeseCake, 0.5f);
}
public void tearDown() throws Exception {
mResolver.delete(Uri.parse(IngredientProvider.MULTIPLE_INGREDIENT_CONTENT_URI), null, null);
mResolver.delete(Uri.parse(ProductProvider.MULTIPLE_PRODUCT_CONTENT_URI), null, null);
mResolver.delete(Uri.parse(RecipeProvider.MULTIPLE_RECIPE_CONTENT_URI), null, null);
}
public void testCreateRecipe() throws Exception {
assertNull(mRecipeController.createRecipe(null));
assertNull(mRecipeController.createRecipe("_TEST_cheesecake"));
Recipe returnedRecipe = mRecipeController.createRecipe("_TEST_pancakes");
assertNotNull(returnedRecipe);
assertEquals("_TEST_pancakes", returnedRecipe.mName);
Recipe savedRecipe = mRecipeController.findById(returnedRecipe.mUUID);
assertNotNull(savedRecipe);
assertEquals(returnedRecipe, savedRecipe);
}
public void testRemoveRecipe() throws Exception {
// nothing should happen.
mRecipeController.removeRecipe(null);
Recipe invalidRecipe = new Recipe("_TEST_pancakes");
// also this should have no consequences.
mRecipeController.removeRecipe(invalidRecipe);
assertNotNull(mCheeseCake.mUUID);
mRecipeController.removeRecipe(mCheeseCake);
assertNull(mRecipeController.findById(mCheeseCake.mUUID));
assertNotNull(mCheeseCake.mUUID);
Cursor ingredientCursor = mResolver.query(Uri.parse(IngredientProvider.MULTIPLE_INGREDIENT_CONTENT_URI),
Ingredient.COLUMN.ALL_COLUMNS,
Ingredient.COLUMN.RECIPE_ID + "=?",
new String[]{mCheeseCake.mUUID},
null);
assertNotNull(ingredientCursor);
assertEquals(0, ingredientCursor.getCount());
ingredientCursor.close();
}
public void testAddOrChangeIngredient() throws Exception {
assertNull(mRecipeController.addOrChangeIngredient(mCheeseCake, null, 1.0f));
assertNull(mRecipeController.addOrChangeIngredient(null, mEgg, 2.0f));
assertNull(mRecipeController.addOrChangeIngredient(mCheeseCake, mEgg, -2.0f));
Ingredient returnedCreatedIngredient = mRecipeController.addOrChangeIngredient(mCheeseCake,
mEgg, 2.0f);
assertNotNull(returnedCreatedIngredient);
assertEquals(mCheeseCake, returnedCreatedIngredient.mRecipe);
assertEquals(mEgg, returnedCreatedIngredient.mProduct);
assertEquals(2.0f, returnedCreatedIngredient.mAmount, 0.001f);
Ingredient savedCreatedIngredient = mRecipeController.findIngredientById(returnedCreatedIngredient.mUUID);
assertNotNull(savedCreatedIngredient);
assertEquals(returnedCreatedIngredient, savedCreatedIngredient);
Ingredient returnedUnchangedIngredient = mRecipeController.addOrChangeIngredient(mCheeseCake,
mFlour, -0.5f);
assertNotNull(returnedUnchangedIngredient);
assertEquals(mIngredientFlourInCake, returnedUnchangedIngredient);
Ingredient returnedChangedIngredient = mRecipeController.addOrChangeIngredient(mCheeseCake,
mFlour, 0.5f);
assertNotNull(returnedChangedIngredient);
assertEquals(0.5f, returnedChangedIngredient.mAmount);
}
public void testRemoveIngredient() throws Exception {
// nothing should happen.
mRecipeController.removeIngredient(null);
assertNotNull(mRecipeController.findIngredientById(mIngredientFlourInCake.mUUID));
mRecipeController.removeIngredient(mIngredientFlourInCake);
// TODO why should that be notnull?
//assertNotNull(mRecipeController.findIngredientById(mIngredientFlourInCake.mUUID));
assertNull(mRecipeController.findIngredientById(mIngredientFlourInCake.mUUID));
assertNotNull(mRecipeController.findIngredientById(mIngredientCurdInCake.mUUID));
mRecipeController.removeIngredient(mCheeseCake, mCurd);
// TODO why should that be notnull?
//assertNotNull(mRecipeController.findIngredientById(mIngredientCurdInCake.mUUID));
assertNull(mRecipeController.findIngredientById(mIngredientCurdInCake.mUUID));
}
public void testRenameRecipe() throws Exception {
assertNull(mRecipeController.renameRecipe(null, "_TEST_pancakes"));
Recipe returnedUnchangedRecipe = mRecipeController.renameRecipe(mCheeseCake, "_TEST_puffpastries");
assertNotNull(returnedUnchangedRecipe);
assertEquals(mCheeseCake, returnedUnchangedRecipe);
Recipe returnedChangedRecipe = mRecipeController.renameRecipe(mCheeseCake, "_TEST_filledbread");
assertNotNull(returnedChangedRecipe);
assertEquals("_TEST_filledbread", returnedChangedRecipe.mName);
}
public void testFindByName() throws Exception {
// negative tests
assertNull(mRecipeController.findByName(null));
assertNull(mRecipeController.findByName("_TEST_not existent list"));
// positive test: get cheese cake!
Recipe cheeseCake = mRecipeController.findByName("_TEST_cheesecake");
assertNotNull(cheeseCake);
assertEquals(mCheeseCake, cheeseCake);
}
} | apache-2.0 |
RunzeCao/ContactsDemo | app/src/main/java/com/metagem/contactsdemo/MGemContactAdapter.java | 5253 | package com.metagem.contactsdemo;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
class MGemContactAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<MGemContact> mGemContacts;
MGemContactAdapter(Context context, List<MGemContact> mGemContacts) {
this.context = context;
this.mGemContacts = mGemContacts;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new NormalViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false));
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
NormalViewHolder viewHolder = (NormalViewHolder) holder;
viewHolder.textView.setText(mGemContacts.get(position).getName());
Bitmap bitmap = loadContactPhoto(context, Uri.parse(mGemContacts.get(position).getPhotoUrl()), 0);
viewHolder.circleImageView.setImageBitmap(bitmap);
if (onDeleteClickListener != null) {
viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onDeleteClickListener.onDeleteClick(v, holder.getAdapterPosition());
}
});
}
}
@Override
public int getItemCount() {
return mGemContacts.size();
}
private class NormalViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CircleImageView circleImageView;
ImageView imageView;
NormalViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.recycle_tv);
circleImageView = (CircleImageView) itemView.findViewById(R.id.recycle_iv);
imageView = (ImageView) itemView.findViewById(R.id.item_delete);
}
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
private OnDeleteClickListener onDeleteClickListener;
void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) {
this.onDeleteClickListener = onDeleteClickListener;
}
interface OnDeleteClickListener {
void onDeleteClick(View view, int position);
}
void removeData(int position) {
mGemContacts.remove(position);
PrefUtils.saveItemBean(context, PrefUtils.obj2String(mGemContacts));
notifyItemRemoved(position);
}
void addItem(MGemContact mGemContact) {
mGemContacts.add(mGemContact);
PrefUtils.saveItemBean(context, PrefUtils.obj2String(mGemContacts));
notifyItemInserted(0);
}
private Bitmap loadContactPhoto(Context context, Uri imageUri, int imageSize) {
AssetFileDescriptor afd = null;
try {
afd = context.getContentResolver().openAssetFileDescriptor(imageUri, "r");
if (afd != null) {
return decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize, imageSize);
}
} catch (FileNotFoundException e) {
return BitmapFactory.decodeResource(context.getResources(), R.mipmap.no_photo);
}
return null;
}
private static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
| apache-2.0 |
cauchyah/zhihudailytest | app/src/main/java/com/zhihudailytest/Utils/DataBaseDao.java | 2306 | package com.zhihudailytest.Utils;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.SparseArray;
import com.zhihudailytest.Bean.Theme;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
/**
* Created by Administrator on 2016/7/19.
*/
public class DataBaseDao {
private final SQLiteDatabase db;
private MyDataBaseHelper helper;
public DataBaseDao(){
helper=MyDataBaseHelper.getInstance();
db=helper.getWritableDatabase();
}
/**
* 插入主题列表信息
* @param values
*/
public void insertTheme(ContentValues values){
db.insert("theme",null,values);
}
public SparseArray<Integer> getRead(){
SparseArray<Integer> ids=new SparseArray<Integer>();
Cursor cursor=db.rawQuery("select * from readed",null);
if (cursor.moveToFirst()){
do {
ids.put(cursor.getInt(1),cursor.getInt(1));
}while (cursor.moveToNext());
}
cursor.close();
return ids;
}
/**
*
* @param id
* @return 1:新增加 2:已有
*/
public int markRead(int id){
//db.rawQuery("insert into readed values(\"null\",\""+id+"\")",null);
Cursor cursor=db.rawQuery("select * from readed where story_id="+id,null);
if (cursor.getCount()<1){
ContentValues values=new ContentValues();
values.put("story_id",id);
db.insert("readed",null,values);
cursor.close();
return 1;
}
cursor.close();
return 2;
}
/**
* 获取主题列表信息
* @return
*/
public List<Theme.Others> getThemeList(){
List<Theme.Others> mData=new ArrayList<Theme.Others>();
Cursor cursor=db.rawQuery("select * from theme ",null);
if (cursor.moveToFirst()){
int id;
String name;
Theme.Others one;
do{
id=cursor.getInt(1);
name=cursor.getString(2);
one=new Theme.Others(id,name);
mData.add(one);
}while (cursor.moveToNext());
}
cursor.close();
return mData;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/AWSRoboMakerAsyncClient.java | 50369 | /*
* Copyright 2014-2019 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.robomaker;
import javax.annotation.Generated;
import com.amazonaws.services.robomaker.model.*;
import com.amazonaws.client.AwsAsyncClientParams;
import com.amazonaws.annotation.ThreadSafe;
import java.util.concurrent.ExecutorService;
/**
* Client for accessing RoboMaker asynchronously. Each asynchronous method will return a Java Future object representing
* the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive notification when
* an asynchronous operation completes.
* <p>
* <p>
* This section provides documentation for the AWS RoboMaker API operations.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSRoboMakerAsyncClient extends AWSRoboMakerClient implements AWSRoboMakerAsync {
private static final int DEFAULT_THREAD_POOL_SIZE = 50;
private final java.util.concurrent.ExecutorService executorService;
public static AWSRoboMakerAsyncClientBuilder asyncBuilder() {
return AWSRoboMakerAsyncClientBuilder.standard();
}
/**
* Constructs a new asynchronous client to invoke service methods on RoboMaker using the specified parameters.
*
* @param asyncClientParams
* Object providing client parameters.
*/
AWSRoboMakerAsyncClient(AwsAsyncClientParams asyncClientParams) {
super(asyncClientParams);
this.executorService = asyncClientParams.getExecutor();
}
/**
* Returns the executor service used by this client to execute async requests.
*
* @return The executor service used by this client to execute async requests.
*/
public ExecutorService getExecutorService() {
return executorService;
}
@Override
public java.util.concurrent.Future<BatchDescribeSimulationJobResult> batchDescribeSimulationJobAsync(BatchDescribeSimulationJobRequest request) {
return batchDescribeSimulationJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<BatchDescribeSimulationJobResult> batchDescribeSimulationJobAsync(final BatchDescribeSimulationJobRequest request,
final com.amazonaws.handlers.AsyncHandler<BatchDescribeSimulationJobRequest, BatchDescribeSimulationJobResult> asyncHandler) {
final BatchDescribeSimulationJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<BatchDescribeSimulationJobResult>() {
@Override
public BatchDescribeSimulationJobResult call() throws Exception {
BatchDescribeSimulationJobResult result = null;
try {
result = executeBatchDescribeSimulationJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CancelDeploymentJobResult> cancelDeploymentJobAsync(CancelDeploymentJobRequest request) {
return cancelDeploymentJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<CancelDeploymentJobResult> cancelDeploymentJobAsync(final CancelDeploymentJobRequest request,
final com.amazonaws.handlers.AsyncHandler<CancelDeploymentJobRequest, CancelDeploymentJobResult> asyncHandler) {
final CancelDeploymentJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CancelDeploymentJobResult>() {
@Override
public CancelDeploymentJobResult call() throws Exception {
CancelDeploymentJobResult result = null;
try {
result = executeCancelDeploymentJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CancelSimulationJobResult> cancelSimulationJobAsync(CancelSimulationJobRequest request) {
return cancelSimulationJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<CancelSimulationJobResult> cancelSimulationJobAsync(final CancelSimulationJobRequest request,
final com.amazonaws.handlers.AsyncHandler<CancelSimulationJobRequest, CancelSimulationJobResult> asyncHandler) {
final CancelSimulationJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CancelSimulationJobResult>() {
@Override
public CancelSimulationJobResult call() throws Exception {
CancelSimulationJobResult result = null;
try {
result = executeCancelSimulationJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateDeploymentJobResult> createDeploymentJobAsync(CreateDeploymentJobRequest request) {
return createDeploymentJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateDeploymentJobResult> createDeploymentJobAsync(final CreateDeploymentJobRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateDeploymentJobRequest, CreateDeploymentJobResult> asyncHandler) {
final CreateDeploymentJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateDeploymentJobResult>() {
@Override
public CreateDeploymentJobResult call() throws Exception {
CreateDeploymentJobResult result = null;
try {
result = executeCreateDeploymentJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateFleetResult> createFleetAsync(CreateFleetRequest request) {
return createFleetAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateFleetResult> createFleetAsync(final CreateFleetRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateFleetRequest, CreateFleetResult> asyncHandler) {
final CreateFleetRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateFleetResult>() {
@Override
public CreateFleetResult call() throws Exception {
CreateFleetResult result = null;
try {
result = executeCreateFleet(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateRobotResult> createRobotAsync(CreateRobotRequest request) {
return createRobotAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateRobotResult> createRobotAsync(final CreateRobotRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateRobotRequest, CreateRobotResult> asyncHandler) {
final CreateRobotRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateRobotResult>() {
@Override
public CreateRobotResult call() throws Exception {
CreateRobotResult result = null;
try {
result = executeCreateRobot(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateRobotApplicationResult> createRobotApplicationAsync(CreateRobotApplicationRequest request) {
return createRobotApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateRobotApplicationResult> createRobotApplicationAsync(final CreateRobotApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateRobotApplicationRequest, CreateRobotApplicationResult> asyncHandler) {
final CreateRobotApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateRobotApplicationResult>() {
@Override
public CreateRobotApplicationResult call() throws Exception {
CreateRobotApplicationResult result = null;
try {
result = executeCreateRobotApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateRobotApplicationVersionResult> createRobotApplicationVersionAsync(CreateRobotApplicationVersionRequest request) {
return createRobotApplicationVersionAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateRobotApplicationVersionResult> createRobotApplicationVersionAsync(
final CreateRobotApplicationVersionRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateRobotApplicationVersionRequest, CreateRobotApplicationVersionResult> asyncHandler) {
final CreateRobotApplicationVersionRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateRobotApplicationVersionResult>() {
@Override
public CreateRobotApplicationVersionResult call() throws Exception {
CreateRobotApplicationVersionResult result = null;
try {
result = executeCreateRobotApplicationVersion(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateSimulationApplicationResult> createSimulationApplicationAsync(CreateSimulationApplicationRequest request) {
return createSimulationApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateSimulationApplicationResult> createSimulationApplicationAsync(final CreateSimulationApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateSimulationApplicationRequest, CreateSimulationApplicationResult> asyncHandler) {
final CreateSimulationApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateSimulationApplicationResult>() {
@Override
public CreateSimulationApplicationResult call() throws Exception {
CreateSimulationApplicationResult result = null;
try {
result = executeCreateSimulationApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateSimulationApplicationVersionResult> createSimulationApplicationVersionAsync(
CreateSimulationApplicationVersionRequest request) {
return createSimulationApplicationVersionAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateSimulationApplicationVersionResult> createSimulationApplicationVersionAsync(
final CreateSimulationApplicationVersionRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateSimulationApplicationVersionRequest, CreateSimulationApplicationVersionResult> asyncHandler) {
final CreateSimulationApplicationVersionRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateSimulationApplicationVersionResult>() {
@Override
public CreateSimulationApplicationVersionResult call() throws Exception {
CreateSimulationApplicationVersionResult result = null;
try {
result = executeCreateSimulationApplicationVersion(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<CreateSimulationJobResult> createSimulationJobAsync(CreateSimulationJobRequest request) {
return createSimulationJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<CreateSimulationJobResult> createSimulationJobAsync(final CreateSimulationJobRequest request,
final com.amazonaws.handlers.AsyncHandler<CreateSimulationJobRequest, CreateSimulationJobResult> asyncHandler) {
final CreateSimulationJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<CreateSimulationJobResult>() {
@Override
public CreateSimulationJobResult call() throws Exception {
CreateSimulationJobResult result = null;
try {
result = executeCreateSimulationJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteFleetResult> deleteFleetAsync(DeleteFleetRequest request) {
return deleteFleetAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteFleetResult> deleteFleetAsync(final DeleteFleetRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteFleetRequest, DeleteFleetResult> asyncHandler) {
final DeleteFleetRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteFleetResult>() {
@Override
public DeleteFleetResult call() throws Exception {
DeleteFleetResult result = null;
try {
result = executeDeleteFleet(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteRobotResult> deleteRobotAsync(DeleteRobotRequest request) {
return deleteRobotAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteRobotResult> deleteRobotAsync(final DeleteRobotRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteRobotRequest, DeleteRobotResult> asyncHandler) {
final DeleteRobotRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteRobotResult>() {
@Override
public DeleteRobotResult call() throws Exception {
DeleteRobotResult result = null;
try {
result = executeDeleteRobot(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteRobotApplicationResult> deleteRobotApplicationAsync(DeleteRobotApplicationRequest request) {
return deleteRobotApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteRobotApplicationResult> deleteRobotApplicationAsync(final DeleteRobotApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteRobotApplicationRequest, DeleteRobotApplicationResult> asyncHandler) {
final DeleteRobotApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteRobotApplicationResult>() {
@Override
public DeleteRobotApplicationResult call() throws Exception {
DeleteRobotApplicationResult result = null;
try {
result = executeDeleteRobotApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeleteSimulationApplicationResult> deleteSimulationApplicationAsync(DeleteSimulationApplicationRequest request) {
return deleteSimulationApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeleteSimulationApplicationResult> deleteSimulationApplicationAsync(final DeleteSimulationApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<DeleteSimulationApplicationRequest, DeleteSimulationApplicationResult> asyncHandler) {
final DeleteSimulationApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeleteSimulationApplicationResult>() {
@Override
public DeleteSimulationApplicationResult call() throws Exception {
DeleteSimulationApplicationResult result = null;
try {
result = executeDeleteSimulationApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DeregisterRobotResult> deregisterRobotAsync(DeregisterRobotRequest request) {
return deregisterRobotAsync(request, null);
}
@Override
public java.util.concurrent.Future<DeregisterRobotResult> deregisterRobotAsync(final DeregisterRobotRequest request,
final com.amazonaws.handlers.AsyncHandler<DeregisterRobotRequest, DeregisterRobotResult> asyncHandler) {
final DeregisterRobotRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DeregisterRobotResult>() {
@Override
public DeregisterRobotResult call() throws Exception {
DeregisterRobotResult result = null;
try {
result = executeDeregisterRobot(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeDeploymentJobResult> describeDeploymentJobAsync(DescribeDeploymentJobRequest request) {
return describeDeploymentJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeDeploymentJobResult> describeDeploymentJobAsync(final DescribeDeploymentJobRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeDeploymentJobRequest, DescribeDeploymentJobResult> asyncHandler) {
final DescribeDeploymentJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeDeploymentJobResult>() {
@Override
public DescribeDeploymentJobResult call() throws Exception {
DescribeDeploymentJobResult result = null;
try {
result = executeDescribeDeploymentJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeFleetResult> describeFleetAsync(DescribeFleetRequest request) {
return describeFleetAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeFleetResult> describeFleetAsync(final DescribeFleetRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeFleetRequest, DescribeFleetResult> asyncHandler) {
final DescribeFleetRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeFleetResult>() {
@Override
public DescribeFleetResult call() throws Exception {
DescribeFleetResult result = null;
try {
result = executeDescribeFleet(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeRobotResult> describeRobotAsync(DescribeRobotRequest request) {
return describeRobotAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeRobotResult> describeRobotAsync(final DescribeRobotRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeRobotRequest, DescribeRobotResult> asyncHandler) {
final DescribeRobotRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeRobotResult>() {
@Override
public DescribeRobotResult call() throws Exception {
DescribeRobotResult result = null;
try {
result = executeDescribeRobot(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeRobotApplicationResult> describeRobotApplicationAsync(DescribeRobotApplicationRequest request) {
return describeRobotApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeRobotApplicationResult> describeRobotApplicationAsync(final DescribeRobotApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeRobotApplicationRequest, DescribeRobotApplicationResult> asyncHandler) {
final DescribeRobotApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeRobotApplicationResult>() {
@Override
public DescribeRobotApplicationResult call() throws Exception {
DescribeRobotApplicationResult result = null;
try {
result = executeDescribeRobotApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeSimulationApplicationResult> describeSimulationApplicationAsync(DescribeSimulationApplicationRequest request) {
return describeSimulationApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeSimulationApplicationResult> describeSimulationApplicationAsync(
final DescribeSimulationApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeSimulationApplicationRequest, DescribeSimulationApplicationResult> asyncHandler) {
final DescribeSimulationApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeSimulationApplicationResult>() {
@Override
public DescribeSimulationApplicationResult call() throws Exception {
DescribeSimulationApplicationResult result = null;
try {
result = executeDescribeSimulationApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<DescribeSimulationJobResult> describeSimulationJobAsync(DescribeSimulationJobRequest request) {
return describeSimulationJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeSimulationJobResult> describeSimulationJobAsync(final DescribeSimulationJobRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeSimulationJobRequest, DescribeSimulationJobResult> asyncHandler) {
final DescribeSimulationJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeSimulationJobResult>() {
@Override
public DescribeSimulationJobResult call() throws Exception {
DescribeSimulationJobResult result = null;
try {
result = executeDescribeSimulationJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListDeploymentJobsResult> listDeploymentJobsAsync(ListDeploymentJobsRequest request) {
return listDeploymentJobsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListDeploymentJobsResult> listDeploymentJobsAsync(final ListDeploymentJobsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListDeploymentJobsRequest, ListDeploymentJobsResult> asyncHandler) {
final ListDeploymentJobsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListDeploymentJobsResult>() {
@Override
public ListDeploymentJobsResult call() throws Exception {
ListDeploymentJobsResult result = null;
try {
result = executeListDeploymentJobs(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListFleetsResult> listFleetsAsync(ListFleetsRequest request) {
return listFleetsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListFleetsResult> listFleetsAsync(final ListFleetsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListFleetsRequest, ListFleetsResult> asyncHandler) {
final ListFleetsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListFleetsResult>() {
@Override
public ListFleetsResult call() throws Exception {
ListFleetsResult result = null;
try {
result = executeListFleets(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListRobotApplicationsResult> listRobotApplicationsAsync(ListRobotApplicationsRequest request) {
return listRobotApplicationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListRobotApplicationsResult> listRobotApplicationsAsync(final ListRobotApplicationsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListRobotApplicationsRequest, ListRobotApplicationsResult> asyncHandler) {
final ListRobotApplicationsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListRobotApplicationsResult>() {
@Override
public ListRobotApplicationsResult call() throws Exception {
ListRobotApplicationsResult result = null;
try {
result = executeListRobotApplications(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListRobotsResult> listRobotsAsync(ListRobotsRequest request) {
return listRobotsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListRobotsResult> listRobotsAsync(final ListRobotsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListRobotsRequest, ListRobotsResult> asyncHandler) {
final ListRobotsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListRobotsResult>() {
@Override
public ListRobotsResult call() throws Exception {
ListRobotsResult result = null;
try {
result = executeListRobots(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListSimulationApplicationsResult> listSimulationApplicationsAsync(ListSimulationApplicationsRequest request) {
return listSimulationApplicationsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListSimulationApplicationsResult> listSimulationApplicationsAsync(final ListSimulationApplicationsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListSimulationApplicationsRequest, ListSimulationApplicationsResult> asyncHandler) {
final ListSimulationApplicationsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListSimulationApplicationsResult>() {
@Override
public ListSimulationApplicationsResult call() throws Exception {
ListSimulationApplicationsResult result = null;
try {
result = executeListSimulationApplications(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListSimulationJobsResult> listSimulationJobsAsync(ListSimulationJobsRequest request) {
return listSimulationJobsAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListSimulationJobsResult> listSimulationJobsAsync(final ListSimulationJobsRequest request,
final com.amazonaws.handlers.AsyncHandler<ListSimulationJobsRequest, ListSimulationJobsResult> asyncHandler) {
final ListSimulationJobsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListSimulationJobsResult>() {
@Override
public ListSimulationJobsResult call() throws Exception {
ListSimulationJobsResult result = null;
try {
result = executeListSimulationJobs(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest request) {
return listTagsForResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(final ListTagsForResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler) {
final ListTagsForResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<ListTagsForResourceResult>() {
@Override
public ListTagsForResourceResult call() throws Exception {
ListTagsForResourceResult result = null;
try {
result = executeListTagsForResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<RegisterRobotResult> registerRobotAsync(RegisterRobotRequest request) {
return registerRobotAsync(request, null);
}
@Override
public java.util.concurrent.Future<RegisterRobotResult> registerRobotAsync(final RegisterRobotRequest request,
final com.amazonaws.handlers.AsyncHandler<RegisterRobotRequest, RegisterRobotResult> asyncHandler) {
final RegisterRobotRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<RegisterRobotResult>() {
@Override
public RegisterRobotResult call() throws Exception {
RegisterRobotResult result = null;
try {
result = executeRegisterRobot(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<RestartSimulationJobResult> restartSimulationJobAsync(RestartSimulationJobRequest request) {
return restartSimulationJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<RestartSimulationJobResult> restartSimulationJobAsync(final RestartSimulationJobRequest request,
final com.amazonaws.handlers.AsyncHandler<RestartSimulationJobRequest, RestartSimulationJobResult> asyncHandler) {
final RestartSimulationJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<RestartSimulationJobResult>() {
@Override
public RestartSimulationJobResult call() throws Exception {
RestartSimulationJobResult result = null;
try {
result = executeRestartSimulationJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<SyncDeploymentJobResult> syncDeploymentJobAsync(SyncDeploymentJobRequest request) {
return syncDeploymentJobAsync(request, null);
}
@Override
public java.util.concurrent.Future<SyncDeploymentJobResult> syncDeploymentJobAsync(final SyncDeploymentJobRequest request,
final com.amazonaws.handlers.AsyncHandler<SyncDeploymentJobRequest, SyncDeploymentJobResult> asyncHandler) {
final SyncDeploymentJobRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<SyncDeploymentJobResult>() {
@Override
public SyncDeploymentJobResult call() throws Exception {
SyncDeploymentJobResult result = null;
try {
result = executeSyncDeploymentJob(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest request) {
return tagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<TagResourceResult> tagResourceAsync(final TagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler) {
final TagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<TagResourceResult>() {
@Override
public TagResourceResult call() throws Exception {
TagResourceResult result = null;
try {
result = executeTagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest request) {
return untagResourceAsync(request, null);
}
@Override
public java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(final UntagResourceRequest request,
final com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler) {
final UntagResourceRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UntagResourceResult>() {
@Override
public UntagResourceResult call() throws Exception {
UntagResourceResult result = null;
try {
result = executeUntagResource(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateRobotApplicationResult> updateRobotApplicationAsync(UpdateRobotApplicationRequest request) {
return updateRobotApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateRobotApplicationResult> updateRobotApplicationAsync(final UpdateRobotApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateRobotApplicationRequest, UpdateRobotApplicationResult> asyncHandler) {
final UpdateRobotApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateRobotApplicationResult>() {
@Override
public UpdateRobotApplicationResult call() throws Exception {
UpdateRobotApplicationResult result = null;
try {
result = executeUpdateRobotApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<UpdateSimulationApplicationResult> updateSimulationApplicationAsync(UpdateSimulationApplicationRequest request) {
return updateSimulationApplicationAsync(request, null);
}
@Override
public java.util.concurrent.Future<UpdateSimulationApplicationResult> updateSimulationApplicationAsync(final UpdateSimulationApplicationRequest request,
final com.amazonaws.handlers.AsyncHandler<UpdateSimulationApplicationRequest, UpdateSimulationApplicationResult> asyncHandler) {
final UpdateSimulationApplicationRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<UpdateSimulationApplicationResult>() {
@Override
public UpdateSimulationApplicationResult call() throws Exception {
UpdateSimulationApplicationResult result = null;
try {
result = executeUpdateSimulationApplication(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
/**
* Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
* asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
* call {@code getExecutorService().shutdown()} followed by {@code getExecutorService().awaitTermination()} prior to
* calling this method.
*/
@Override
public void shutdown() {
super.shutdown();
executorService.shutdownNow();
}
}
| apache-2.0 |
inbloom/secure-data-service | sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/util/MongoIndex.java | 3537 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.ingestion.util;
import java.util.Map;
import com.mongodb.DBObject;
/**
* Structure for Mongo indexes
*
* @author tke
*
*/
public class MongoIndex {
private String collection;
private boolean unique;
private IndexObject keys;
private boolean sparse;
public MongoIndex(String collection, boolean unique, DBObject keys) {
this.collection = collection;
this.unique = unique;
this.keys = new IndexObject(keys);
}
public MongoIndex(String collection, boolean unique, DBObject keys, boolean sparse) {
this.collection = collection;
this.unique = unique;
this.keys = new IndexObject(keys);
this.sparse = sparse;
}
/**
* constructor has been provided
*/
public MongoIndex() {
keys = new IndexObject();
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public boolean isUnique() {
return unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
public Map<String, Integer> getKeys() {
return keys.getKeys();
}
public void setKeys(IndexObject keys) {
this.keys = keys;
}
public boolean isSparse() {
return sparse;
}
public void setSparse(boolean sparse) {
this.sparse = sparse;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((collection == null) ? 0 : collection.hashCode());
result = prime * result + ((keys == null) ? 0 : keys.hashCode());
result = prime * result + (unique ? 1231 : 1237);
result = prime * result + (sparse ? 1231 : 1237);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MongoIndex other = (MongoIndex) obj;
if (collection == null) {
if (other.collection != null) {
return false;
}
} else if (!collection.equals(other.collection)) {
return false;
}
if (keys == null) {
if (other.keys != null) {
return false;
}
} else if (!keys.equals(other.keys)) {
return false;
}
if (unique != other.unique) {
return false;
}
if (sparse != other.sparse) {
return false;
}
return true;
}
}
| apache-2.0 |
RobAltena/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/scatter/ScatterAdd.java | 3820 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.api.ops.impl.scatter;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.base.Preconditions;
import org.nd4j.imports.NoOpNameFoundException;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by farizrahman4u on 3/23/18.
*/
public class ScatterAdd extends DynamicCustomOp {
public ScatterAdd(SameDiff sameDiff, SDVariable ref, SDVariable indices, SDVariable updates) {
super(null, sameDiff, new SDVariable[]{ref, indices, updates}, false);
}
public ScatterAdd(){}
@Override
public String opName() {
return "scatter_add";
}
@Override
public String onnxName() {
throw new NoOpNameFoundException("No onnx op opName found for " + opName());
}
@Override
public String tensorflowName() {
return "ScatterAdd";
}
@Override
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
TFGraphMapper.initFunctionFromProperties(nodeDef.getOp(), this, attributesForNode, nodeDef, graph);
if (nodeDef.containsAttr("use_locking")) {
if (nodeDef.getAttrOrThrow("use_locking").getB() == true) {
bArguments.add(true);
} else {
bArguments.add(false);
}
} else
bArguments.add(false);
}
@Override
public List<SDVariable> doDiff(List<SDVariable> gradOut){
//3 args: ref, indices, updates
//For non-modified indices, input gradient (referenc) is same as output gradient
//For modified indices, dL/dref = dL/dOut * dOut/dRef = dL/dOut * d(ref + update)/dRef = dL/dOut
//And for updates, dL/du = dL/dOut * dOut/du = dL/dOut * d(ref + update)/du = dL/dOut -> gather op
List<SDVariable> ret = new ArrayList<>(3);
ret.add(gradOut.get(0)); //Reference array
ret.add(f().zerosLike(arg(1))); //Indices
SDVariable gather = f().gather(gradOut.get(0), arg(1), 0); //Updates
ret.add(gather);
return ret;
}
@Override
public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){
Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == 3, "Expected exactly 3 input datatypes for %s, got %s", getClass(), inputDataTypes);
Preconditions.checkState(inputDataTypes.get(0) == inputDataTypes.get(2), "Reference (input 0) and updates (input 2) must have exactly same data types, got %s and %s",
inputDataTypes.get(0), inputDataTypes.get(2));
return Collections.singletonList(inputDataTypes.get(0));
}
}
| apache-2.0 |
epam/DLab | services/self-service/src/main/java/com/epam/dlab/backendapi/schedulers/exploratory/TerminateExploratoryJob.java | 1350 | /*
* Copyright (c) 2018, EPAM SYSTEMS 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.epam.dlab.backendapi.schedulers.exploratory;
import com.epam.dlab.backendapi.service.SchedulerJobService;
import com.fiestacabin.dropwizard.quartz.Scheduled;
import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
/**
* There realized integration with Quartz scheduler framework and defined terminate exploratory scheduler job which
* executes every time specified.
*/
@Slf4j
@Scheduled(interval = 10)
public class TerminateExploratoryJob implements Job {
@Inject
private SchedulerJobService schedulerJobService;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
schedulerJobService.executeTerminateResourceJob(false);
}
}
| apache-2.0 |
siemens/ASLanPPConnector | src/aslanpp-translator/src/main/java/org/avantssar/aslanpp/flow/AbstractEdge.java | 13084 | // Copyright 2010-2013 (c) IeAT, Siemens AG, AVANTSSAR and SPaCIoS consortia.
// 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.avantssar.aslanpp.flow;
import java.io.PrintStream;
import java.util.List;
import java.util.Set;
import org.avantssar.aslan.IASLanSpec;
import org.avantssar.aslan.RewriteRule;
import org.avantssar.aslanpp.Debug;
import org.avantssar.aslanpp.IReduceable;
import org.avantssar.aslanpp.model.ExpressionContext;
import org.avantssar.aslanpp.model.FunctionTerm;
import org.avantssar.aslanpp.model.IExpression;
import org.avantssar.aslanpp.model.ITerm;
import org.avantssar.aslanpp.model.NegationExpression;
import org.avantssar.aslanpp.model.Prelude;
import org.avantssar.aslanpp.model.SymbolsState;
public abstract class AbstractEdge implements IEdge {
private static final String STEP_PREFIX = "step";
private static int GRAPHVIZ_LABEL_LENGTH = 15;
private final INode sourceNode;
private INode targetNode;
private int index;
protected final ASLanBuilder builder;
protected AbstractEdge(INode sourceNode, INode targetNode, ASLanBuilder builder) {
this.sourceNode = sourceNode;
sourceNode.addOutgoingEdge(this);
this.targetNode = targetNode;
this.builder = builder;
}
protected AbstractEdge(INode sourceNode, ASLanBuilder builder) {
this.sourceNode = sourceNode;
sourceNode.addOutgoingEdge(this);
targetNode = new Node(this);
this.builder = builder;
}
protected AbstractEdge(AbstractEdge old, INode sourceNode) {
this(sourceNode, null, old.builder);
}
public INode getSourceNode() {
return sourceNode;
}
public INode getTargetNode() {
return targetNode;
}
public int getIndex() {
return index;
}
public IEdge optimize(INode sourceNode) {
INode farthestNode = getFarthestNode();
IEdge newEdge = recreate(sourceNode);
((AbstractEdge) newEdge).targetNode = farthestNode.optimize(newEdge);
return newEdge;
}
protected abstract IEdge recreate(INode sourceNode);
private INode getFarthestNode() {
INode finalNode = getTargetNode();
boolean over = false;
while (!over) {
if (finalNode.wasOptimized()) {
// it's a loop, we need to stop
over = true;
}
else {
if (finalNode.getOutgoingEdges().size() != 1) {
// A branch comes down the line, or the chain ends. either
// way we stop.
over = true;
}
else {
GenericEdge edge = (GenericEdge) finalNode.getOutgoingEdges().get(0);
if (edge.canBeDropped()) {
// Move on to the next (single) edge.
finalNode = edge.getTargetNode();
}
else {
// The edge cannot be dropped. We stop.
over = true;
}
}
}
}
return finalNode;
}
public boolean canBeDropped() {
return false;
}
public boolean canNeverBeTaken() {
return false;
}
public Counters assignIndexes(Counters counters) {
index = counters.edges;
int nextNodeIndex = targetNode.wasVisited() ? targetNode.getNodeIndex() : counters.nodes + 1;
if (!targetNode.wasVisited()) {
return targetNode.assignIndexes(new Counters(nextNodeIndex, counters.edges + 1));
}
else {
return new Counters(counters.nodes, counters.edges + 1);
}
}
public void renderGraphviz(PrintStream out) {
toGraphviz(out);
if (!targetNode.wasVisited()) {
targetNode.renderGraphviz(out);
}
}
public int gatherTransitions(IASLanSpec spec, int nextTransitionIndex) {
int idx = nextTransitionIndex;
getTransition(spec, idx++, new SymbolsState());
if (!targetNode.wasVisited()) {
idx = targetNode.gatherTransitions(spec, idx);
}
return idx;
}
public int gatherTransitionsLumped(IASLanSpec spec, RewriteRule soFar, SymbolsState symState, Set<Integer> visitedStates, int nextTransitionIndex, int sourceNodeIndex, TransitionsRecorder rec) {
Debug.logger.debug("Starting getTransitionLumped");
Debug.logger.debug("\tedge=" + this.describeForGraphviz());
Debug.logger.debug("\tnext idx=" + nextTransitionIndex);
Debug.logger.debug("\tvisited states=" + visitedStates.size() + " " + visitedStates);
Debug.logger.debug("\tso far=" + (soFar != null ? soFar.getRepresentation() : "N/A"));
int idx = nextTransitionIndex;
if (soFar == null) {
Debug.logger.debug("\tnothing so far");
soFar = getTransition(spec, idx++, symState);
}
else {
Debug.logger.debug("\tsomething so far");
boolean couldContribute = contributeToTransition(soFar, symState);
if (!couldContribute) {
Debug.logger.debug("\tcould not contribute further, restarting");
symState.clear();
soFar = getTransition(spec, idx++, symState);
}
else {
Debug.logger.debug("\tcontributed further\n");
}
}
boolean continued = false;
int origIdx = idx;
if (targetNode.isBigState() || targetNode.mustStartNewTransitionOnLumping()) {
symState.clear();
if (!targetNode.wasVisited()) {
idx = targetNode.gatherTransitionsLumped(spec, null, symState, visitedStates, idx, targetNode.getNodeIndex(), rec);
}
}
else {
if (!visitedStates.contains(new Integer(targetNode.getNodeIndex()))) {
if (!canBeContributedAfter()) {
symState.clear();
idx = targetNode.gatherTransitionsLumped(spec, null, symState, visitedStates, idx, targetNode.getNodeIndex(), rec);
}
else {
continued = true;
idx = targetNode.gatherTransitionsLumped(spec, soFar, symState, visitedStates, idx, sourceNodeIndex, rec);
}
}
else {
symState.clear();
}
}
if (!continued) {
rec.record(sourceNodeIndex, targetNode.getNodeIndex(), origIdx - 1);
}
return idx;
}
public boolean mustStartNewTransitionOnLumping() {
return false;
}
protected abstract RewriteRule getTransition(IASLanSpec spec, int index, SymbolsState symState);
protected abstract boolean contributeToTransition(RewriteRule soFar, SymbolsState symState);
protected abstract boolean canBeContributedAfter();
public void clearVisited() {
if (targetNode.wasVisited()) {
targetNode.clearVisited();
}
}
protected void toGraphviz(PrintStream out) {
StringBuffer sb = new StringBuffer();
sb.append(sourceNode.getNodeIndex());
sb.append(" -> ");
sb.append(targetNode.getNodeIndex());
sb.append(" [");
sb.append("label=\"");
sb.append("step_");
sb.append(index);
sb.append("\\n");
sb.append(getGraphvizPrefix());
// sb.append(", line ");
// sb.append(lineNumber);
String desc = describeForGraphviz();
if (desc.length() > 0) {
sb.append("\\n");
if (desc.length() > GRAPHVIZ_LABEL_LENGTH) {
desc = desc.substring(0, GRAPHVIZ_LABEL_LENGTH) + "...";
}
sb.append(desc);
}
sb.append("\"");
sb.append(", ");
sb.append("color=");
sb.append(getGraphvizColor());
sb.append("] ;");
out.println(sb.toString());
}
protected String getGraphvizColor() {
return "black";
}
protected abstract String getGraphvizPrefix();
protected String describe() {
return getClass().getSimpleName();
}
protected String describeForGraphviz() {
return describe();
}
protected String buildName(String name, int index, int lineNumber) {
StringBuffer sb = new StringBuffer();
sb.append(STEP_PREFIX);
sb.append("_");
sb.append(String.format("%03d", index));
sb.append("_");
sb.append(name);
if (lineNumber > 0/* && TranslatorOptions.rulesNoLineNumber()*/) {
sb.append("__line_");
sb.append(lineNumber);
}
return sb.toString();
}
protected void retract(RewriteRule rule, ITerm term, ExpressionContext ctx, SymbolsState symState) {
addLHS(rule, term, ctx, symState, false, true);
}
protected void introduce(RewriteRule rule, ITerm term, ExpressionContext ctx, SymbolsState symState) {
addRHS(rule, term, ctx, symState, false, true);
}
protected void addLHS(RewriteRule rule, ITerm term, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
addEx(rule, true, term, ctx, symState, avoidDuplicates, checkOtherSide);
}
protected void addLHS(RewriteRule rule, IExpression expr, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
addEx(rule, true, expr, ctx, symState, avoidDuplicates, checkOtherSide);
}
protected void addRHS(RewriteRule rule, ITerm term, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
addEx(rule, false, term, ctx, symState, avoidDuplicates, checkOtherSide);
}
protected void addRHS(RewriteRule rule, IExpression expr, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
addEx(rule, false, expr, ctx, symState, avoidDuplicates, checkOtherSide);
}
private void addEx(RewriteRule rule, boolean toLeft, IExpression expr, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
org.avantssar.aslan.ITerm aslanTerm = null;
if (expr instanceof NegationExpression) {
IExpression baseExpr = ((NegationExpression) expr).getBaseExpression();
aslanTerm = builder.transform(baseExpr).negate();
}
else {
aslanTerm = builder.transform(expr);
}
addInternal(rule, toLeft, aslanTerm, avoidDuplicates, checkOtherSide);
addAdditional(rule, toLeft, ctx, symState);
}
private void addEx(RewriteRule rule, boolean toLeft, ITerm term, ExpressionContext ctx, SymbolsState symState, boolean avoidDuplicates, boolean checkOtherSide) {
addInternal(rule, toLeft, builder.transform(term), avoidDuplicates, checkOtherSide);
addAdditional(rule, toLeft, ctx, symState);
}
// TODO rename Reduce to Substitute
protected <T> T solveReduce(IReduceable<T> aa, SymbolsState symState, boolean forceReplacementOfMatches) {
T result = null;
ExpressionContext ctx;
if (forceReplacementOfMatches) {
ctx = new ExpressionContext(true);
aa.buildContext(ctx, false);
symState.push();
aa.useContext(ctx, symState);
result = aa.reduce(symState);
symState.pop();
}
ctx = new ExpressionContext();
aa.buildContext(ctx, false);
aa.useContext(ctx, symState);
if (!forceReplacementOfMatches) {
result = aa.reduce(symState);
}
return result;
}
private static String[] noAdditional = new String[] { Prelude.CHILD };
protected boolean isSpecialSessionGoalTerm(ITerm term) {
boolean special = false;
if (term instanceof FunctionTerm) {
FunctionTerm fterm = (FunctionTerm) term;
String fname = fterm.getSymbol().getOriginalName();
boolean found = false;
for (String s : noAdditional) {
if (s.equals(fname)) {
found = true;
break;
}
}
if (found) {
special = true;
}
}
return special;
}
protected <T> void addAdditional(RewriteRule rule, boolean toLeft, ExpressionContext ctx, SymbolsState symState) {
List<ITerm> auxiliaryTerms = ctx.getAuxiliaryTerms();
if (auxiliaryTerms != null) {
for (ITerm term : auxiliaryTerms) {
ITerm red = solveReduce(term, symState, false);
addInternal(rule, toLeft, builder.transform(red), true, false);
}
}
List<ITerm> sessionGoalTerms = ctx.getSessionGoalTerms();
if (sessionGoalTerms != null) {
for (ITerm term : sessionGoalTerms) {
// bloody special case: for certain function symbols
// we don't add additional stuff and we avoid duplicates
boolean special = isSpecialSessionGoalTerm(term);
// session goal terms are always rendered on RHS
ITerm red = solveReduce(term, symState, true);
org.avantssar.aslan.ITerm aslanRed = builder.transform(red);
addInternal(rule, false, aslanRed, true, false);
if (special) {
addInternal(rule, true, aslanRed, true, false);
}
// session goal terms may have additional terms (e.g. secrecy terms)
ExpressionContext sgtCtx = new ExpressionContext();
term.buildContext(sgtCtx, false);
if (sgtCtx.getAuxiliaryTerms() != null) {
for (ITerm auxTerm : sgtCtx.getAuxiliaryTerms()) {
ITerm auxRed = solveReduce(auxTerm, symState, false);
addInternal(rule, false, builder.transform(auxRed), true, false);
}
}
}
}
}
protected void addInternal(RewriteRule rule, boolean toLeft, org.avantssar.aslan.ITerm term, boolean avoidDuplicates, boolean checkOtherSide) {
if (checkOtherSide && rule.contains(term, !toLeft)) {
rule.remove(term, !toLeft);
}
else if (!avoidDuplicates || !rule.contains(term, toLeft)) {
rule.add(term, toLeft);
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(sourceNode.getNodeIndex());
sb.append(" -> ");
sb.append(targetNode.getNodeIndex());
sb.append("::");
sb.append(index);
sb.append("::");
sb.append(getGraphvizPrefix());
return sb.toString();
}
}
| apache-2.0 |
jlannoy/ninja | ninja-servlet-archetype-simple/src/main/resources/archetype-resources/src/main/java/conf/Module.java | 966 | /**
* Copyright (C) 2012-2019 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.
*/
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package conf;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
@Singleton
public class Module extends AbstractModule {
protected void configure() {
// bind your injections here!
}
}
| apache-2.0 |
petezybrick/iote2e | iote2e-tests/src/main/java/com/pzybrick/iote2e/tests/pilldisp/DumpPillsDispensedImages.java | 2040 | /**
* Copyright 2016, 2017 Peter Zybrick and others.
*
* 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.
*
* @author Pete Zybrick
* @version 1.0.0, 2017-09
*
*/
package com.pzybrick.iote2e.tests.pilldisp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import com.pzybrick.iote2e.common.config.MasterConfig;
import com.pzybrick.iote2e.common.persist.ConfigDao;
import com.pzybrick.iote2e.stream.persist.PillsDispensedDao;
/**
* The Class DumpPillsDispensedImages.
*/
public class DumpPillsDispensedImages {
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
try {
String masterConfigKey = args[0];
String contactPoint = args[1];
String keyspaceName = args[2];
String tmpDir = "/tmp/iote2e-shared/images/";
MasterConfig masterConfig = MasterConfig.getInstance( masterConfigKey, contactPoint, keyspaceName );
List<String> allUuids = PillsDispensedDao.findAllPillsDispensedUuids( masterConfig );
for( String uuid : allUuids ) {
byte[] bytes = PillsDispensedDao.findImageBytesByPillsDispensedUuid(masterConfig, uuid);
String pathNameExt = tmpDir + uuid + ".png";
System.out.println("Writing: " + pathNameExt );
FileOutputStream fos = new FileOutputStream(new File(pathNameExt));
fos.write(bytes);
fos.close();
}
ConfigDao.connect(contactPoint, keyspaceName);
System.out.println();
} catch(Exception e) {
System.out.println(e);
}
}
}
| apache-2.0 |
openid/AppAuth-Android | library/javatests/net/openid/appauth/browser/BrowserAllowListTest.java | 3627 | /*
* Copyright 2016 The AppAuth for Android 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 net.openid.appauth.browser;
import static org.assertj.core.api.Assertions.assertThat;
import net.openid.appauth.BuildConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 16)
public class BrowserAllowListTest {
@Test
public void testMatches_emptyAllowList() {
BrowserAllowList allowList = new BrowserAllowList();
assertThat(allowList.matches(Browsers.Chrome.customTab("46"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.standaloneBrowser("10"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.customTab("57"))).isFalse();
assertThat(allowList.matches(Browsers.SBrowser.standaloneBrowser("11"))).isFalse();
}
@Test
public void testMatches_chromeBrowserOnly() {
BrowserAllowList allowList = new BrowserAllowList(VersionedBrowserMatcher.CHROME_BROWSER);
assertThat(allowList.matches(Browsers.Chrome.standaloneBrowser("46"))).isTrue();
assertThat(allowList.matches(Browsers.Chrome.customTab("46"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.standaloneBrowser("10"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.customTab("57"))).isFalse();
}
@Test
public void testMatches_chromeCustomTabOrBrowser() {
BrowserAllowList allowList = new BrowserAllowList(
VersionedBrowserMatcher.CHROME_BROWSER,
VersionedBrowserMatcher.CHROME_CUSTOM_TAB);
assertThat(allowList.matches(Browsers.Chrome.standaloneBrowser("46"))).isTrue();
assertThat(allowList.matches(Browsers.Chrome.customTab("46"))).isTrue();
assertThat(allowList.matches(Browsers.Firefox.standaloneBrowser("10"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.customTab("57"))).isFalse();
}
@Test
public void testMatches_firefoxOrSamsung() {
BrowserAllowList allowList = new BrowserAllowList(
VersionedBrowserMatcher.FIREFOX_BROWSER,
VersionedBrowserMatcher.FIREFOX_CUSTOM_TAB,
VersionedBrowserMatcher.SAMSUNG_BROWSER,
VersionedBrowserMatcher.SAMSUNG_CUSTOM_TAB);
assertThat(allowList.matches(Browsers.Chrome.standaloneBrowser("46"))).isFalse();
assertThat(allowList.matches(Browsers.Chrome.customTab("46"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.standaloneBrowser("10"))).isTrue();
assertThat(allowList.matches(Browsers.Firefox.customTab("56"))).isFalse();
assertThat(allowList.matches(Browsers.Firefox.customTab("57"))).isTrue();
assertThat(allowList.matches(Browsers.SBrowser.standaloneBrowser("10"))).isTrue();
assertThat(allowList.matches(Browsers.SBrowser.customTab("4.0"))).isTrue();
assertThat(allowList.matches(Browsers.SBrowser.customTab("3.9"))).isFalse();
}
}
| apache-2.0 |
aehlig/bazel | src/main/java/com/google/devtools/build/lib/query2/engine/QueryEnvironment.java | 25987 | // Copyright 2014 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.query2.engine;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The environment of a Blaze query. Implementations do not need to be thread-safe. The generic type
* T represents a node of the graph on which the query runs; as such, there is no restriction on T.
* However, query assumes a certain graph model, and the {@link TargetAccessor} class is used to
* access properties of these nodes. Also, the query engine doesn't assume T's {@link
* Object#hashCode} and {@link Object#equals} are meaningful and instead uses {@link
* QueryEnvironment#createUniquifier}, {@link QueryEnvironment#createThreadSafeMutableSet()}, and
* {@link QueryEnvironment#createMutableMap()} when appropriate.
*
* @param <T> the node type of the dependency graph
*/
public interface QueryEnvironment<T> {
/** Type of an argument of a user-defined query function. */
enum ArgumentType {
EXPRESSION,
WORD,
INTEGER;
}
/** Value of an argument of a user-defined query function. */
class Argument {
private final ArgumentType type;
private final QueryExpression expression;
private final String word;
private final int integer;
private Argument(ArgumentType type, QueryExpression expression, String word, int integer) {
this.type = type;
this.expression = expression;
this.word = word;
this.integer = integer;
}
public static Argument of(QueryExpression expression) {
return new Argument(ArgumentType.EXPRESSION, expression, null, 0);
}
public static Argument of(String word) {
return new Argument(ArgumentType.WORD, null, word, 0);
}
public static Argument of(int integer) {
return new Argument(ArgumentType.INTEGER, null, null, integer);
}
public ArgumentType getType() {
return type;
}
public QueryExpression getExpression() {
return Preconditions.checkNotNull(expression, "Expected expression argument");
}
public String getWord() {
return word;
}
public int getInteger() {
return integer;
}
@Override
public String toString() {
switch (type) {
case WORD:
return "'" + word + "'";
case EXPRESSION:
return expression.toString();
case INTEGER:
return Integer.toString(integer);
}
throw new IllegalStateException();
}
}
/** A user-defined query function. */
interface QueryFunction {
/** Name of the function as it appears in the query language. */
String getName();
/**
* The number of arguments that are required. The rest is optional.
*
* <p>This should be greater than or equal to zero and at smaller than or equal to the length of
* the list returned by {@link #getArgumentTypes}.
*/
int getMandatoryArguments();
/** The types of the arguments of the function. */
Iterable<ArgumentType> getArgumentTypes();
/**
* Returns a {@link QueryTaskFuture} representing the asynchronous application of this {@link
* QueryFunction} to the given {@code args}, feeding the results to the given {@code callback}.
*
* @param env the query environment this function is evaluated in.
* @param expression the expression being evaluated.
* @param context the context relevant to the expression being evaluated. Contains the variable
* bindings from {@link LetExpression}s.
* @param args the input arguments. These are type-checked against the specification returned by
* {@link #getArgumentTypes} and {@link #getMandatoryArguments}
*/
<T> QueryTaskFuture<Void> eval(
QueryEnvironment<T> env,
QueryExpressionContext<T> context,
QueryExpression expression,
List<Argument> args,
Callback<T> callback);
/**
* A filtering function is one whose outputs are a subset of a single input argument. Returns
* the function as a filtering function if it is one and {@code null} otherwise.
*/
@Nullable
default FilteringQueryFunction asFilteringFunction() {
return null;
}
}
/** A {@link QueryFunction} whose output is a subset of some input argument expression. */
abstract class FilteringQueryFunction implements QueryFunction {
@Override
public final FilteringQueryFunction asFilteringFunction() {
return this;
}
/** Returns a function representing the filter but inverted. */
public abstract FilteringQueryFunction invert();
/** Returns the argument index of the expression that is used as the input to be filtered. */
public abstract int getExpressionToFilterIndex();
}
/**
* Exception type for the case where a target cannot be found. It's basically a wrapper for
* whatever exception is internally thrown.
*/
final class TargetNotFoundException extends Exception {
public TargetNotFoundException(String msg) {
super(msg);
}
public TargetNotFoundException(Throwable cause) {
super(cause.getMessage(), cause);
}
}
/**
* QueryEnvironment implementations can optionally also implement this interface to provide custom
* implementations of various operators.
*/
interface CustomFunctionQueryEnvironment<T> extends QueryEnvironment<T> {
/**
* Computes the transitive closure of dependencies at most maxDepth away from the given targets,
* and calls the given callback with the results.
*/
void deps(Iterable<T> from, int maxDepth, QueryExpression caller, Callback<T> callback)
throws InterruptedException, QueryException;
/** Computes some path from a node in 'from' to a node in 'to'. */
void somePath(Iterable<T> from, Iterable<T> to, QueryExpression caller, Callback<T> callback)
throws InterruptedException, QueryException;
/** Computes all paths from a node in 'from' to a node in 'to'. */
void allPaths(Iterable<T> from, Iterable<T> to, QueryExpression caller, Callback<T> callback)
throws InterruptedException, QueryException;
/**
* Computes all reverse dependencies of a node in 'from' with at most distance maxDepth within
* the transitive closure of 'universe'.
*/
void rdeps(
Iterable<T> from,
Iterable<T> universe,
int maxDepth,
QueryExpression caller,
Callback<T> callback)
throws InterruptedException, QueryException;
/** Computes direct reverse deps of all nodes in 'from' within the same package. */
void samePkgDirectRdeps(Iterable<T> from, QueryExpression caller, Callback<T> callback)
throws InterruptedException, QueryException;
}
/** Returns all of the targets in <code>target</code>'s package, in some stable order. */
Collection<T> getSiblingTargetsInPackage(T target);
/**
* Invokes {@code callback} with the set of target nodes in the graph for the specified target
* pattern, in 'blaze build' syntax.
*/
QueryTaskFuture<Void> getTargetsMatchingPattern(
QueryExpression owner, String pattern, Callback<T> callback);
/** Ensures the specified target exists. */
// NOTE(bazel-team): this method is left here as scaffolding from a previous refactoring. It may
// be possible to remove it.
T getOrCreate(T target);
/** Returns the direct forward dependencies of the specified targets. */
Iterable<T> getFwdDeps(Iterable<T> targets, QueryExpressionContext<T> context)
throws InterruptedException;
/** Returns the direct reverse dependencies of the specified targets. */
Iterable<T> getReverseDeps(Iterable<T> targets, QueryExpressionContext<T> context)
throws InterruptedException;
/**
* Returns the forward transitive closure of all of the targets in "targets". Callers must ensure
* that {@link #buildTransitiveClosure} has been called for the relevant subgraph.
*/
ThreadSafeMutableSet<T> getTransitiveClosure(
ThreadSafeMutableSet<T> targets, QueryExpressionContext<T> context)
throws InterruptedException;
/**
* Construct the dependency graph for a depth-bounded forward transitive closure of all nodes in
* "targetNodes". The identity of the calling expression is required to produce error messages.
*
* <p>If a larger transitive closure was already built, returns it to improve incrementality,
* since all depth-constrained methods filter it after it is built anyway.
*/
void buildTransitiveClosure(
QueryExpression caller, ThreadSafeMutableSet<T> targetNodes, int maxDepth)
throws QueryException, InterruptedException;
/** Returns the ordered sequence of nodes on some path from "from" to "to". */
Iterable<T> getNodesOnPath(T from, T to, QueryExpressionContext<T> context)
throws InterruptedException;
/**
* Returns a {@link QueryTaskFuture} representing the asynchronous evaluation of the given {@code
* expr} and passing of the results to the given {@code callback}.
*
* <p>Note that this method should guarantee that the callback does not see repeated elements.
*
* @param expr The expression to evaluate
* @param callback The caller callback to notify when results are available
*/
QueryTaskFuture<Void> eval(
QueryExpression expr, QueryExpressionContext<T> context, Callback<T> callback);
/**
* An asynchronous computation of part of a query evaluation.
*
* <p>A {@link QueryTaskFuture} can only be produced from scratch via {@link #eval}, {@link
* #execute}, {@link #immediateSuccessfulFuture}, {@link #immediateFailedFuture}, and {@link
* #immediateCancelledFuture}.
*
* <p>Combined with the helper methods like {@link #whenSucceedsCall} below, this is very similar
* to Guava's {@link ListenableFuture}.
*
* <p>This class is deliberately opaque; the only ways to compose/use {@link #QueryTaskFuture}
* instances are the helper methods like {@link #whenSucceedsCall} below. A crucial consequence of
* this is there is no way for a {@link QueryExpression} or {@link QueryFunction} implementation
* to block on the result of a {@link #QueryTaskFuture}. This eliminates a large class of
* deadlocks by design!
*/
@ThreadSafe
public abstract class QueryTaskFuture<T> {
// We use a public abstract class with a private constructor so that this type is visible to all
// the query codebase, but yet the only possible implementation is under our control in this
// file.
private QueryTaskFuture() {}
/**
* If this {@link QueryTasksFuture}'s encapsulated computation is currently complete and
* successful, returns the result. This method is intended to be used in combination with {@link
* #whenSucceedsCall}.
*
* <p>See the javadoc for the various helper methods that produce {@link QueryTasksFuture} for
* the precise definition of "successful".
*/
public abstract T getIfSuccessful();
}
/**
* Returns a {@link QueryTaskFuture} representing the successful computation of {@code value}.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful}.
*/
abstract <R> QueryTaskFuture<R> immediateSuccessfulFuture(R value);
/**
* Returns a {@link QueryTaskFuture} representing a computation that was unsuccessful because of
* {@code e}.
*
* <p>The returned {@link QueryTaskFuture} is considered "unsuccessful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful}.
*/
abstract <R> QueryTaskFuture<R> immediateFailedFuture(QueryException e);
/**
* Returns a {@link QueryTaskFuture} representing a cancelled computation.
*
* <p>The returned {@link QueryTaskFuture} is considered "unsuccessful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful}.
*/
abstract <R> QueryTaskFuture<R> immediateCancelledFuture();
/** A {@link ThreadSafe} {@link Callable} for computations during query evaluation. */
@ThreadSafe
public interface QueryTaskCallable<T> extends Callable<T> {
/**
* Returns the computed value or throws a {@link QueryException} on failure or a {@link
* InterruptedException} on interruption.
*/
@Override
T call() throws QueryException, InterruptedException;
}
/** Like Guava's AsyncCallable, but for {@link QueryTaskFuture}. */
@ThreadSafe
public interface QueryTaskAsyncCallable<T> {
/**
* Returns a {@link QueryTaskFuture} whose completion encapsulates the result of the
* computation.
*/
QueryTaskFuture<T> call();
}
/**
* Returns a {@link QueryTaskFuture} representing the given computation {@code callable} being
* performed asynchronously.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful} iff
* {@code callable#call} does not throw an exception.
*/
<R> QueryTaskFuture<R> execute(QueryTaskCallable<R> callable);
/**
* Returns a {@link QueryTaskFuture} representing both the given {@code callable} being performed
* asynchronously and also the returned {@link QueryTaskFuture} returned therein being completed.
*/
<R> QueryTaskFuture<R> executeAsync(QueryTaskAsyncCallable<R> callable);
/**
* Returns a {@link QueryTaskFuture} representing the given computation {@code callable} being
* performed after the successful completion of the computation encapsulated by the given {@code
* future} has completed successfully.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful} iff
* {@code future} is successful and {@code callable#call} does not throw an exception.
*/
<R> QueryTaskFuture<R> whenSucceedsCall(QueryTaskFuture<?> future, QueryTaskCallable<R> callable);
/**
* Returns a {@link QueryTaskFuture} representing the successful completion of all the
* computations encapsulated by the given {@code futures}.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful} iff
* all of the given computations are "successful".
*/
QueryTaskFuture<Void> whenAllSucceed(Iterable<? extends QueryTaskFuture<?>> futures);
/**
* Returns a {@link QueryTaskFuture} representing the given computation {@code callable} being
* performed after the successful completion of all the computations encapsulated by the given
* {@code futures}.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful} iff
* all of the given computations are "successful" and {@code callable#call} does not throw an
* exception.
*/
<R> QueryTaskFuture<R> whenAllSucceedCall(
Iterable<? extends QueryTaskFuture<?>> futures, QueryTaskCallable<R> callable);
/**
* Returns a {@link QueryTaskFuture} representing the asynchronous application of the given {@code
* function} to the value produced by the computation encapsulated by the given {@code future}.
*
* <p>The returned {@link QueryTaskFuture} is considered "successful" for purposes of {@link
* #whenSucceedsCall}, {@link #whenAllSucceed}, and {@link QueryTaskFuture#getIfSuccessful} iff
* {@code} future is "successful".
*/
<T1, T2> QueryTaskFuture<T2> transformAsync(
QueryTaskFuture<T1> future, Function<T1, QueryTaskFuture<T2>> function);
/**
* The sole package-protected subclass of {@link QueryTaskFuture}.
*
* <p>Do not subclass this class; it's an implementation detail. {@link QueryExpression} and
* {@link QueryFunction} implementations should use {@link #eval} and {@link #execute} to get
* access to {@link QueryTaskFuture} instances and the then use the helper methods like {@link
* #whenSucceedsCall} to transform them.
*/
abstract class QueryTaskFutureImplBase<T> extends QueryTaskFuture<T> {
protected QueryTaskFutureImplBase() {}
}
/**
* A mutable {@link ThreadSafe} {@link Set} that uses proper equality semantics for {@code T}.
* {@link QueryExpression}/{@link QueryFunction} implementations should use {@code
* ThreadSafeMutableSet<T>} they need a set-like data structure for {@code T}.
*/
@ThreadSafe
interface ThreadSafeMutableSet<T> extends Set<T> {}
/** Returns a fresh {@link ThreadSafeMutableSet} instance for the type {@code T}. */
ThreadSafeMutableSet<T> createThreadSafeMutableSet();
/**
* A simple map-like interface that uses proper equality semantics for the key type. {@link
* QueryExpression}/{@link QueryFunction} implementations should use {@code
* ThreadSafeMutableSet<T, V>} they need a map-like data structure for {@code T}.
*/
interface MutableMap<K, V> {
/**
* Returns the value {@code value} associated with the given key by the most recent call to
* {@code put(key, value)}, or {@code null} if there was no such call.
*/
@Nullable
V get(K key);
/**
* Associates the given key with the given value and returns the previous value associated with
* the key, or {@code null} if there wasn't one.
*/
V put(K key, V value);
}
/** Returns a fresh {@link MutableMap} instance with key type {@code T}. */
<V> MutableMap<T, V> createMutableMap();
/**
* Creates a Uniquifier for use in a {@code QueryExpression}. Note that the usage of this
* uniquifier should not be used for returning unique results to the parent callback. It should
* only be used to avoid processing the same elements multiple times within this QueryExpression.
*/
Uniquifier<T> createUniquifier();
/**
* Creates a {@link MinDepthUniquifier} for use in a {@code QueryExpression}. Note that the usage
* of this uniquifier should not be used for returning unique results to the parent callback. It
* should only be used to try to avoid processing the same elements multiple times at the same
* depth bound within this QueryExpression.
*/
MinDepthUniquifier<T> createMinDepthUniquifier();
void reportBuildFileError(QueryExpression expression, String msg) throws QueryException;
/**
* Returns the set of BUILD, and optionally Skylark files that define the given set of targets.
* Each such file is itself represented as a target in the result.
*/
ThreadSafeMutableSet<T> getBuildFiles(
QueryExpression caller,
ThreadSafeMutableSet<T> nodes,
boolean buildFiles,
boolean loads,
QueryExpressionContext<T> context)
throws QueryException, InterruptedException;
/**
* Returns an object that can be used to query information about targets. Implementations should
* create a single instance and return that for all calls. A class can implement both {@code
* QueryEnvironment} and {@code TargetAccessor} at the same time, in which case this method simply
* returns {@code this}.
*/
TargetAccessor<T> getAccessor();
/**
* Whether the given setting is enabled. The code should default to return {@code false} for all
* unknown settings. The enum is used rather than a method for each setting so that adding more
* settings is backwards-compatible.
*
* @throws NullPointerException if setting is null
*/
boolean isSettingEnabled(@Nonnull Setting setting);
/** Returns the set of query functions implemented by this query environment. */
Iterable<QueryFunction> getFunctions();
/** Settings for the query engine. See {@link QueryEnvironment#isSettingEnabled}. */
enum Setting {
/**
* Whether to evaluate tests() expressions in strict mode. If {@link #isSettingEnabled} returns
* true for this setting, then the tests() expression will give an error when expanding tests
* suites, if the test suite contains any non-test targets.
*/
TESTS_EXPRESSION_STRICT,
/**
* Do not consider implicit deps (any label that was not explicitly specified in the BUILD file)
* when traversing dependency edges.
*/
NO_IMPLICIT_DEPS,
/** Do not consider non-target dependencies when traversing dependency edges. */
ONLY_TARGET_DEPS,
/** Do not consider nodep attributes when traversing dependency edges. */
NO_NODEP_DEPS;
}
/**
* An adapter interface giving access to properties of T. There are four types of targets: rules,
* package groups, source files, and generated files. Of these, only rules can have attributes.
*/
interface TargetAccessor<T> {
/**
* Returns the target type represented as a string of the form {@code <type> rule} or
* {@code package group} or {@code source file} or {@code generated file}. This is widely used
* for target filtering, so implementations must use the Blaze rule class naming scheme.
*/
String getTargetKind(T target);
/** Returns the full label of the target as a string, e.g. {@code //some:target}. */
String getLabel(T target);
/** Returns the label of the target's package as a string, e.g. {@code //some/package} */
String getPackage(T target);
/** Returns whether the given target is a rule. */
boolean isRule(T target);
/**
* Returns whether the given target is a test target. If this returns true, then {@link #isRule}
* must also return true for the target.
*/
boolean isTestRule(T target);
/**
* Returns whether the given target is a test suite target. If this returns true, then {@link
* #isRule} must also return true for the target, but {@link #isTestRule} must return false;
* test suites are not test rules, and vice versa.
*/
boolean isTestSuite(T target);
/**
* If the attribute of the given name on the given target is a label or label list, then this
* method returns the list of corresponding target instances. Otherwise returns an empty list.
* If an error occurs during resolution, it throws a {@link QueryException} using the caller and
* error message prefix.
*
* @throws IllegalArgumentException if target is not a rule (according to {@link #isRule})
*/
Iterable<T> getLabelListAttr(
QueryExpression caller, T target, String attrName, String errorMsgPrefix)
throws QueryException, InterruptedException;
/**
* If the attribute of the given name on the given target is a string list, then this method
* returns it.
*
* @throws IllegalArgumentException if target is not a rule (according to {@link #isRule}), or
* if the target does not have an attribute of type string list with the given name
*/
List<String> getStringListAttr(T target, String attrName);
/**
* If the attribute of the given name on the given target is a string, then this method returns
* it.
*
* @throws IllegalArgumentException if target is not a rule (according to {@link #isRule}), or
* if the target does not have an attribute of type string with the given name
*/
String getStringAttr(T target, String attrName);
/**
* Returns the given attribute represented as a list of strings. For "normal" attributes, this
* should just be a list of size one containing the attribute's value. For configurable
* attributes, there should be one entry for each possible value the attribute may take.
*
* <p>Note that for backwards compatibility, tristate and boolean attributes are returned as int
* using the values {@code 0, 1} and {@code -1}. If there is no such attribute, this method
* returns an empty list.
*
* @throws IllegalArgumentException if target is not a rule (according to {@link #isRule})
*/
Iterable<String> getAttrAsString(T target, String attrName);
/**
* Returns the set of package specifications the given target is visible from, represented as
* {@link QueryVisibility}s.
*/
Set<QueryVisibility<T>> getVisibility(T from) throws QueryException, InterruptedException;
}
/** List of the default query functions. */
ImmutableList<QueryFunction> DEFAULT_QUERY_FUNCTIONS =
ImmutableList.of(
new AllPathsFunction(),
new AttrFunction(),
new BuildFilesFunction(),
new DepsFunction(),
new FilterFunction(),
new KindFunction(),
new LabelsFunction(),
new LoadFilesFunction(),
new RdepsFunction(),
new SamePkgDirectRdepsFunction(),
new SiblingsFunction(),
new SomeFunction(),
new SomePathFunction(),
new TestsFunction(),
new VisibleFunction());
}
| apache-2.0 |
XiLingHost/tg-qq-trans | src/config/ConfigData.java | 886 | /**
* 这个类用于存储所有的配置信息
*/
package config;
import java.util.List;
/**
* @author XiLing
*
*/
public class ConfigData
{
public String coolqDir; //酷Q软件的安装目录,结尾不要带有斜杠或反斜杠,相对绝对路径均可
public int qqBotPort; //酷Q Socket API的监听端口,这里必须和酷Q Socket API中的设置一致,除非你设定了端口转发
public String qqBotNumber; //QQ机器人的QQ号
public String telegramBotToken; //Telegram机器人的访问Token,格式是000000000:ABcd1234_AasdfbgqwertyZe5QnyBt6_OlY
public List<GroupsPairs> groupsPairs; //Telegram群组和QQ群的匹配关系
public ProxyConfig proxyConfig; //代理服务器设定,可以使用SOCKS和HTTP代理
public List<String> enabledPlugins; //已启用的插件,用完整路径表示,如plugins.classname
}
| apache-2.0 |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryResultTest.java | 2841 | /*
* Copyright 2021-2021 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.cloud.spanner.r2dbc.v2;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.r2dbc.spi.RowMetadata;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
class SpannerClientLibraryResultTest {
@Test
void nullRowsNotAllowed() {
assertThrows(IllegalArgumentException.class,
() -> new SpannerClientLibraryResult(null, 42));
}
@Test
void getRowsUpdatedReturnsCorrectNumber() {
SpannerClientLibraryResult result = new SpannerClientLibraryResult(Flux.empty(), 42);
StepVerifier.create(result.getRowsUpdated())
.expectNext(42)
.verifyComplete();
}
@Test
void mapGeneratesMetadataOnlyOnFirstCall() {
SpannerClientLibraryRow mockRow1 = mock(SpannerClientLibraryRow.class);
when(mockRow1.get("col")).thenReturn("value1");
RowMetadata mockMetadata = mock(RowMetadata.class);
when(mockRow1.generateMetadata()).thenReturn(mockMetadata);
SpannerClientLibraryRow mockRow2 = mock(SpannerClientLibraryRow.class);
when(mockRow2.get("col")).thenReturn("value2");
SpannerClientLibraryResult result =
new SpannerClientLibraryResult(Flux.just(mockRow1, mockRow2), 0);
StepVerifier.create(
result.map((r, rm) -> r.get("col"))
).expectNext("value1", "value2")
.verifyComplete();
verify(mockRow1).generateMetadata();
verify(mockRow2, times(0)).generateMetadata();
}
@Test
void filterNotSupported() {
SpannerClientLibraryResult result = new SpannerClientLibraryResult(Flux.empty(), 0);
assertThatThrownBy(() -> result.filter(null))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
void flatMapWithSegmentNotSupported() {
SpannerClientLibraryResult result = new SpannerClientLibraryResult(Flux.empty(), 0);
StepVerifier.create(
result.flatMap(segment -> Mono.empty())
).verifyError(UnsupportedOperationException.class);
}
}
| apache-2.0 |
raydac/netbeans-mmd-plugin | mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/plugins/processors/EditTextPlugin.java | 2320 | /*
* Copyright 2015-2018 Igor Maznitsa.
*
* 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.igormaznitsa.mindmap.plugins.processors;
import static com.igormaznitsa.meta.common.utils.Assertions.assertNotNull;
import com.igormaznitsa.mindmap.model.Topic;
import com.igormaznitsa.mindmap.plugins.PopUpSection;
import com.igormaznitsa.mindmap.plugins.api.AbstractFocusedTopicPlugin;
import com.igormaznitsa.mindmap.plugins.api.PluginContext;
import com.igormaznitsa.mindmap.swing.panel.Texts;
import com.igormaznitsa.mindmap.swing.panel.ui.AbstractElement;
import com.igormaznitsa.mindmap.swing.services.IconID;
import com.igormaznitsa.mindmap.swing.services.ImageIconServiceProvider;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.Icon;
public class EditTextPlugin extends AbstractFocusedTopicPlugin {
private static final Icon ICO = ImageIconServiceProvider.findInstance().getIconForId(IconID.POPUP_EDIT_TEXT);
@Override
public int getOrder() {
return 0;
}
@Override
@Nullable
protected Icon getIcon(@Nonnull final PluginContext context, @Nullable final Topic activeTopic) {
return ICO;
}
@Override
@Nonnull
protected String getName(@Nonnull final PluginContext context, @Nullable final Topic activeTopic) {
return Texts.getString("MMDGraphEditor.makePopUp.miEditText");
}
@Override
protected void doActionForTopic(@Nonnull final PluginContext context, @Nullable final Topic activeTopic) {
if (activeTopic != null) {
context.getPanel().startEdit((AbstractElement) assertNotNull(activeTopic.getPayload()));
}
}
@Override
@Nonnull
public PopUpSection getSection() {
return PopUpSection.MAIN;
}
@Override
public boolean isCompatibleWithFullScreenMode() {
return true;
}
}
| apache-2.0 |
piotr-j/VisEditor | runtime/src/main/java/com/kotcrab/vis/runtime/properties/TintOwner.java | 791 | /*
* Copyright 2014-2016 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kotcrab.vis.runtime.properties;
import com.badlogic.gdx.graphics.Color;
/** @author Kotcrab */
public interface TintOwner {
Color getTint ();
void setTint (Color tint);
}
| apache-2.0 |
eemirtekin/Sakai-10.6-TR | syllabus/syllabus-app/src/java/org/sakaiproject/jsf/syllabus/SyllabusTableTag.java | 1355 | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/syllabus/tags/sakai-10.6/syllabus-app/src/java/org/sakaiproject/jsf/syllabus/SyllabusTableTag.java $
* $Id: SyllabusTableTag.java 105080 2012-02-24 23:10:31Z ottenhoff@longsight.com $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.jsf.syllabus;
import com.sun.faces.taglib.html_basic.DataTableTag;
public class SyllabusTableTag extends DataTableTag
{
public String getComponentType()
{
return "SakaiSyllabusTable";
}
}
| apache-2.0 |
nikitamarchenko/open-kilda | services/src/messaging/src/main/java/org/openkilda/messaging/info/switches/SyncRulesResponse.java | 1544 | /* Copyright 2018 Telstra Open Source
*
* 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.openkilda.messaging.info.switches;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Value;
import org.openkilda.messaging.info.InfoData;
import java.util.List;
@Value
@Builder
public class SyncRulesResponse extends InfoData {
@JsonProperty("added_rules")
private List<String> addedRules;
@JsonProperty("proper_rules")
private List<String> properRules;
@JsonProperty("not_deleted")
private List<String> notDeleted;
@JsonCreator
public SyncRulesResponse(
@JsonProperty("added_rules") List<String> addedRules,
@JsonProperty("proper_rules") List<String> properRules,
@JsonProperty("not_deleted") List<String> notDeleted) {
this.addedRules = addedRules;
this.properRules = properRules;
this.notDeleted = notDeleted;
}
}
| apache-2.0 |
patrickfav/tuwien | master/swt workspace/ModelJUnit 2.0 beta1/modeljunit/src/main/java/nz/ac/waikato/jdsl/graph/algo/InvalidQueryException.java | 1854 | /*
Copyright (c) 1999, 2000 Brown University, Providence, RI
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose other than its incorporation into a
commercial product is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of Brown University not be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission.
BROWN UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL BROWN
UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
package nz.ac.waikato.jdsl.graph.algo;
import nz.ac.waikato.jdsl.graph.api.GraphException;
/**
* This exception is currently used only by the two subclasses of
* AbstractTopologicalSort. It is thrown when number(Vertex) or
* sortedVertices() are called and the graph is cyclic.
*
* @author David Ellis
* @author based on a previous version by Lucy Perry
* @version JDSL 2.1.1
*/
public class InvalidQueryException extends GraphException {
public InvalidQueryException (String message) {
super(message);
}
public InvalidQueryException (String message, Throwable cause) {
super(message, cause);
}
public InvalidQueryException (Throwable cause) {
super(cause);
}
}
| apache-2.0 |
bremersee/common | common-base-web/src/main/java/org/bremersee/http/HttpHeadersHelper.java | 1829 | /*
* Copyright 2019 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.bremersee.http;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiConsumer;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
/**
* Helper to create http headers.
*
* @author Christian Bremer
*/
public abstract class HttpHeadersHelper {
private HttpHeadersHelper() {
}
/**
* Build http headers.
*
* @param headers the headers
* @return the http headers
*/
public static HttpHeaders buildHttpHeaders(
final Map<String, ? extends Collection<String>> headers) {
if (headers instanceof HttpHeaders) {
return (HttpHeaders) headers;
}
if (headers instanceof MultiValueMap) {
//noinspection unchecked,rawtypes
return new HttpHeaders((MultiValueMap) headers);
}
final HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach(
(BiConsumer<String, Collection<String>>) (key, values)
-> httpHeaders.addAll(key, values != null
? new ArrayList<>(values)
: Collections.emptyList()));
}
return httpHeaders;
}
}
| apache-2.0 |
AlienYvonne/SSM | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/socket/NotebookServer.java | 87144 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.socket;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.AngularObjectRegistryListener;
import org.apache.zeppelin.helium.ApplicationEventListener;
import org.apache.zeppelin.helium.HeliumPackage;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContextRunner;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.notebook.JobListenerFactory;
import org.apache.zeppelin.notebook.Folder;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.notebook.NotebookEventListener;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.notebook.ParagraphJobListener;
import org.apache.zeppelin.notebook.repo.NotebookRepo.Revision;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.apache.zeppelin.notebook.socket.WatcherMessage;
import org.apache.zeppelin.rest.exception.ForbiddenException;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.server.SmartZeppelinServer;
import org.apache.zeppelin.ticket.TicketContainer;
import org.apache.zeppelin.types.InterpreterSettingsList;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.util.WatcherSecurityKey;
import org.apache.zeppelin.utils.InterpreterBindingUtils;
import org.apache.zeppelin.utils.SecurityUtils;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Queues;
import com.google.gson.reflect.TypeToken;
/**
* Zeppelin websocket service.
*/
public class NotebookServer extends WebSocketServlet
implements NotebookSocketListener, JobListenerFactory, AngularObjectRegistryListener,
RemoteInterpreterProcessListener, ApplicationEventListener {
/**
* Job manager service type
*/
protected enum JOB_MANAGER_SERVICE {
JOB_MANAGER_PAGE("JOB_MANAGER_PAGE");
private String serviceTypeKey;
JOB_MANAGER_SERVICE(String serviceType) {
this.serviceTypeKey = serviceType;
}
String getKey() {
return this.serviceTypeKey;
}
}
private static final Logger LOG = LoggerFactory.getLogger(NotebookServer.class);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
final Map<String, List<NotebookSocket>> noteSocketMap = new HashMap<>();
final Queue<NotebookSocket> connectedSockets = new ConcurrentLinkedQueue<>();
final Map<String, Queue<NotebookSocket>> userConnectedSockets = new ConcurrentHashMap<>();
/**
* This is a special endpoint in the notebook websoket, Every connection in this Queue
* will be able to watch every websocket event, it doesnt need to be listed into the map of
* noteSocketMap. This can be used to get information about websocket traffic and watch what
* is going on.
*/
final Queue<NotebookSocket> watcherSockets = Queues.newConcurrentLinkedQueue();
private Notebook notebook() {
return SmartZeppelinServer.notebook;
}
@Override
public void configure(WebSocketServletFactory factory) {
factory.setCreator(new NotebookWebSocketCreator(this));
}
public boolean checkOrigin(HttpServletRequest request, String origin) {
try {
return SecurityUtils.isValidOrigin(origin, ZeppelinConfiguration.create());
} catch (UnknownHostException e) {
LOG.error(e.toString(), e);
} catch (URISyntaxException e) {
LOG.error(e.toString(), e);
}
return false;
}
public NotebookSocket doWebSocketConnect(HttpServletRequest req, String protocol) {
return new NotebookSocket(req, protocol, this);
}
@Override
public void onOpen(NotebookSocket conn) {
LOG.info("New connection from {} : {}", conn.getRequest().getRemoteAddr(),
conn.getRequest().getRemotePort());
connectedSockets.add(conn);
}
@Override
public void onMessage(NotebookSocket conn, String msg) {
Notebook notebook = notebook();
try {
Message messagereceived = deserializeMessage(msg);
LOG.debug("RECEIVE << " + messagereceived.op);
LOG.debug("RECEIVE PRINCIPAL << " + messagereceived.principal);
LOG.debug("RECEIVE TICKET << " + messagereceived.ticket);
LOG.debug("RECEIVE ROLES << " + messagereceived.roles);
if (LOG.isTraceEnabled()) {
LOG.trace("RECEIVE MSG = " + messagereceived);
}
String ticket = TicketContainer.instance.getTicket(messagereceived.principal);
if (ticket != null &&
(messagereceived.ticket == null || !ticket.equals(messagereceived.ticket))) {
/* not to pollute logs, log instead of exception */
if (StringUtils.isEmpty(messagereceived.ticket)) {
LOG.debug("{} message: invalid ticket {} != {}", messagereceived.op,
messagereceived.ticket, ticket);
} else {
if (!messagereceived.op.equals(OP.PING)) {
conn.send(serializeMessage(new Message(OP.SESSION_LOGOUT).put("info",
"Your ticket is invalid possibly due to server restart. "
+ "Please login again.")));
}
}
return;
}
ZeppelinConfiguration conf = ZeppelinConfiguration.create();
boolean allowAnonymous = conf.isAnonymousAllowed();
if (!allowAnonymous && messagereceived.principal.equals("anonymous")) {
throw new Exception("Anonymous access not allowed ");
}
HashSet<String> userAndRoles = new HashSet<>();
userAndRoles.add(messagereceived.principal);
if (!messagereceived.roles.equals("")) {
HashSet<String> roles =
gson.fromJson(messagereceived.roles, new TypeToken<HashSet<String>>() {
}.getType());
if (roles != null) {
userAndRoles.addAll(roles);
}
}
if (StringUtils.isEmpty(conn.getUser())) {
addUserConnection(messagereceived.principal, conn);
}
AuthenticationInfo subject =
new AuthenticationInfo(messagereceived.principal, messagereceived.ticket);
/** Lets be elegant here */
switch (messagereceived.op) {
case LIST_NOTES:
unicastNoteList(conn, subject, userAndRoles);
break;
case RELOAD_NOTES_FROM_REPO:
broadcastReloadedNoteList(subject, userAndRoles);
break;
case GET_HOME_NOTE:
sendHomeNote(conn, userAndRoles, notebook, messagereceived);
break;
case GET_NOTE:
sendNote(conn, userAndRoles, notebook, messagereceived);
break;
case NEW_NOTE:
createNote(conn, userAndRoles, notebook, messagereceived);
break;
case DEL_NOTE:
removeNote(conn, userAndRoles, notebook, messagereceived);
break;
case REMOVE_FOLDER:
removeFolder(conn, userAndRoles, notebook, messagereceived);
break;
case MOVE_NOTE_TO_TRASH:
moveNoteToTrash(conn, userAndRoles, notebook, messagereceived);
break;
case MOVE_FOLDER_TO_TRASH:
moveFolderToTrash(conn, userAndRoles, notebook, messagereceived);
break;
case EMPTY_TRASH:
emptyTrash(conn, userAndRoles, notebook, messagereceived);
break;
case RESTORE_FOLDER:
restoreFolder(conn, userAndRoles, notebook, messagereceived);
break;
case RESTORE_NOTE:
restoreNote(conn, userAndRoles, notebook, messagereceived);
break;
case RESTORE_ALL:
restoreAll(conn, userAndRoles, notebook, messagereceived);
break;
case CLONE_NOTE:
cloneNote(conn, userAndRoles, notebook, messagereceived);
break;
case IMPORT_NOTE:
importNote(conn, userAndRoles, notebook, messagereceived);
break;
case COMMIT_PARAGRAPH:
updateParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case RUN_PARAGRAPH:
runParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case RUN_ALL_PARAGRAPHS:
runAllParagraphs(conn, userAndRoles, notebook, messagereceived);
break;
case CANCEL_PARAGRAPH:
cancelParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case MOVE_PARAGRAPH:
moveParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case INSERT_PARAGRAPH:
insertParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case COPY_PARAGRAPH:
copyParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case PARAGRAPH_REMOVE:
removeParagraph(conn, userAndRoles, notebook, messagereceived);
break;
case PARAGRAPH_CLEAR_OUTPUT:
clearParagraphOutput(conn, userAndRoles, notebook, messagereceived);
break;
case PARAGRAPH_CLEAR_ALL_OUTPUT:
clearAllParagraphOutput(conn, userAndRoles, notebook, messagereceived);
break;
case NOTE_UPDATE:
updateNote(conn, userAndRoles, notebook, messagereceived);
break;
case NOTE_RENAME:
renameNote(conn, userAndRoles, notebook, messagereceived);
break;
case FOLDER_RENAME:
renameFolder(conn, userAndRoles, notebook, messagereceived);
break;
case UPDATE_PERSONALIZED_MODE:
updatePersonalizedMode(conn, userAndRoles, notebook, messagereceived);
break;
case COMPLETION:
completion(conn, userAndRoles, notebook, messagereceived);
break;
case PING:
break; //do nothing
case ANGULAR_OBJECT_UPDATED:
angularObjectUpdated(conn, userAndRoles, notebook, messagereceived);
break;
case ANGULAR_OBJECT_CLIENT_BIND:
angularObjectClientBind(conn, userAndRoles, notebook, messagereceived);
break;
case ANGULAR_OBJECT_CLIENT_UNBIND:
angularObjectClientUnbind(conn, userAndRoles, notebook, messagereceived);
break;
case LIST_CONFIGURATIONS:
sendAllConfigurations(conn, userAndRoles, notebook);
break;
case CHECKPOINT_NOTE:
checkpointNote(conn, notebook, messagereceived);
break;
case LIST_REVISION_HISTORY:
listRevisionHistory(conn, notebook, messagereceived);
break;
case SET_NOTE_REVISION:
setNoteRevision(conn, userAndRoles, notebook, messagereceived);
break;
case NOTE_REVISION:
getNoteByRevision(conn, notebook, messagereceived);
break;
case LIST_NOTE_JOBS:
unicastNoteJobInfo(conn, messagereceived);
break;
case UNSUBSCRIBE_UPDATE_NOTE_JOBS:
unsubscribeNoteJobInfo(conn);
break;
case GET_INTERPRETER_BINDINGS:
getInterpreterBindings(conn, messagereceived);
break;
case SAVE_INTERPRETER_BINDINGS:
saveInterpreterBindings(conn, messagereceived);
break;
case EDITOR_SETTING:
getEditorSetting(conn, messagereceived);
break;
case GET_INTERPRETER_SETTINGS:
getInterpreterSettings(conn, subject);
break;
case WATCHER:
switchConnectionToWatcher(conn, messagereceived);
break;
default:
break;
}
} catch (Exception e) {
LOG.error("Can't handle message", e);
}
}
@Override
public void onClose(NotebookSocket conn, int code, String reason) {
LOG.info("Closed connection to {} : {}. ({}) {}", conn.getRequest().getRemoteAddr(),
conn.getRequest().getRemotePort(), code, reason);
removeConnectionFromAllNote(conn);
connectedSockets.remove(conn);
removeUserConnection(conn.getUser(), conn);
}
private void removeUserConnection(String user, NotebookSocket conn) {
if (userConnectedSockets.containsKey(user)) {
userConnectedSockets.get(user).remove(conn);
} else {
LOG.warn("Closing connection that is absent in user connections");
}
}
private void addUserConnection(String user, NotebookSocket conn) {
conn.setUser(user);
if (userConnectedSockets.containsKey(user)) {
userConnectedSockets.get(user).add(conn);
} else {
Queue<NotebookSocket> socketQueue = new ConcurrentLinkedQueue<>();
socketQueue.add(conn);
userConnectedSockets.put(user, socketQueue);
}
}
protected Message deserializeMessage(String msg) {
return gson.fromJson(msg, Message.class);
}
protected String serializeMessage(Message m) {
return gson.toJson(m);
}
private void addConnectionToNote(String noteId, NotebookSocket socket) {
synchronized (noteSocketMap) {
removeConnectionFromAllNote(socket); // make sure a socket relates only a
// single note.
List<NotebookSocket> socketList = noteSocketMap.get(noteId);
if (socketList == null) {
socketList = new LinkedList<>();
noteSocketMap.put(noteId, socketList);
}
if (!socketList.contains(socket)) {
socketList.add(socket);
}
}
}
private void removeConnectionFromNote(String noteId, NotebookSocket socket) {
synchronized (noteSocketMap) {
List<NotebookSocket> socketList = noteSocketMap.get(noteId);
if (socketList != null) {
socketList.remove(socket);
}
}
}
private void removeNote(String noteId) {
synchronized (noteSocketMap) {
List<NotebookSocket> socketList = noteSocketMap.remove(noteId);
}
}
private void removeConnectionFromAllNote(NotebookSocket socket) {
synchronized (noteSocketMap) {
Set<String> keys = noteSocketMap.keySet();
for (String noteId : keys) {
removeConnectionFromNote(noteId, socket);
}
}
}
private String getOpenNoteId(NotebookSocket socket) {
String id = null;
synchronized (noteSocketMap) {
Set<String> keys = noteSocketMap.keySet();
for (String noteId : keys) {
List<NotebookSocket> sockets = noteSocketMap.get(noteId);
if (sockets.contains(socket)) {
id = noteId;
}
}
}
return id;
}
private void broadcastToNoteBindedInterpreter(String interpreterGroupId, Message m) {
Notebook notebook = notebook();
List<Note> notes = notebook.getAllNotes();
for (Note note : notes) {
List<String> ids = notebook.getInterpreterSettingManager().getInterpreters(note.getId());
for (String id : ids) {
if (id.equals(interpreterGroupId)) {
broadcast(note.getId(), m);
}
}
}
}
private void broadcast(String noteId, Message m) {
synchronized (noteSocketMap) {
broadcastToWatchers(noteId, StringUtils.EMPTY, m);
List<NotebookSocket> socketLists = noteSocketMap.get(noteId);
if (socketLists == null || socketLists.size() == 0) {
return;
}
LOG.debug("SEND >> " + m.op);
for (NotebookSocket conn : socketLists) {
try {
conn.send(serializeMessage(m));
} catch (IOException e) {
LOG.error("socket error", e);
}
}
}
}
private void broadcastExcept(String noteId, Message m, NotebookSocket exclude) {
synchronized (noteSocketMap) {
broadcastToWatchers(noteId, StringUtils.EMPTY, m);
List<NotebookSocket> socketLists = noteSocketMap.get(noteId);
if (socketLists == null || socketLists.size() == 0) {
return;
}
LOG.debug("SEND >> " + m.op);
for (NotebookSocket conn : socketLists) {
if (exclude.equals(conn)) {
continue;
}
try {
conn.send(serializeMessage(m));
} catch (IOException e) {
LOG.error("socket error", e);
}
}
}
}
private void multicastToUser(String user, Message m) {
if (!userConnectedSockets.containsKey(user)) {
LOG.warn("Multicasting to user {} that is not in connections map", user);
return;
}
for (NotebookSocket conn : userConnectedSockets.get(user)) {
unicast(m, conn);
}
}
private void unicast(Message m, NotebookSocket conn) {
try {
conn.send(serializeMessage(m));
} catch (IOException e) {
LOG.error("socket error", e);
}
broadcastToWatchers(StringUtils.EMPTY, StringUtils.EMPTY, m);
}
public void unicastNoteJobInfo(NotebookSocket conn, Message fromMessage) throws IOException {
addConnectionToNote(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(), conn);
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
List<Map<String, Object>> noteJobs = notebook().getJobListByUnixTime(false, 0, subject);
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", noteJobs);
conn.send(serializeMessage(new Message(OP.LIST_NOTE_JOBS).put("noteJobs", response)));
}
public void broadcastUpdateNoteJobInfo(long lastUpdateUnixTime) throws IOException {
List<Map<String, Object>> noteJobs = new LinkedList<>();
Notebook notebookObject = notebook();
List<Map<String, Object>> jobNotes = null;
if (notebookObject != null) {
jobNotes = notebook().getJobListByUnixTime(false, lastUpdateUnixTime, null);
noteJobs = jobNotes == null ? noteJobs : jobNotes;
}
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", noteJobs != null ? noteJobs : new LinkedList<>());
broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
public void unsubscribeNoteJobInfo(NotebookSocket conn) {
removeConnectionFromNote(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(), conn);
}
public void saveInterpreterBindings(NotebookSocket conn, Message fromMessage) {
String noteId = (String) fromMessage.data.get("noteId");
try {
List<String> settingIdList =
gson.fromJson(String.valueOf(fromMessage.data.get("selectedSettingIds")),
new TypeToken<ArrayList<String>>() {
}.getType());
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
notebook().bindInterpretersToNote(subject.getUser(), noteId, settingIdList);
broadcastInterpreterBindings(noteId,
InterpreterBindingUtils.getInterpreterBindings(notebook(), noteId));
} catch (Exception e) {
LOG.error("Error while saving interpreter bindings", e);
}
}
public void getInterpreterBindings(NotebookSocket conn, Message fromMessage) throws IOException {
String noteId = (String) fromMessage.data.get("noteId");
List<InterpreterSettingsList> settingList =
InterpreterBindingUtils.getInterpreterBindings(notebook(), noteId);
conn.send(serializeMessage(
new Message(OP.INTERPRETER_BINDINGS).put("interpreterBindings", settingList)));
}
public List<Map<String, String>> generateNotesInfo(boolean needsReload,
AuthenticationInfo subject, Set<String> userAndRoles) {
Notebook notebook = notebook();
ZeppelinConfiguration conf = notebook.getConf();
String homescreenNoteId = conf.getString(ConfVars.ZEPPELIN_NOTEBOOK_HOMESCREEN);
boolean hideHomeScreenNotebookFromList =
conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_HOMESCREEN_HIDE);
if (needsReload) {
try {
notebook.reloadAllNotes(subject);
} catch (IOException e) {
LOG.error("Fail to reload notes from repository", e);
}
}
List<Note> notes = notebook.getAllNotes(userAndRoles);
List<Map<String, String>> notesInfo = new LinkedList<>();
for (Note note : notes) {
Map<String, String> info = new HashMap<>();
if (hideHomeScreenNotebookFromList && note.getId().equals(homescreenNoteId)) {
continue;
}
info.put("id", note.getId());
info.put("name", note.getName());
notesInfo.add(info);
}
return notesInfo;
}
public void broadcastNote(Note note) {
broadcast(note.getId(), new Message(OP.NOTE).put("note", note));
}
public void broadcastInterpreterBindings(String noteId, List settingList) {
broadcast(noteId, new Message(OP.INTERPRETER_BINDINGS).put("interpreterBindings", settingList));
}
public void broadcastParagraph(Note note, Paragraph p) {
if (note.isPersonalizedMode()) {
broadcastParagraphs(p.getUserParagraphMap());
} else {
broadcast(note.getId(), new Message(OP.PARAGRAPH).put("paragraph", p));
}
}
public void broadcastParagraphs(Map<String, Paragraph> userParagraphMap) {
if (null != userParagraphMap) {
for (String user : userParagraphMap.keySet()) {
multicastToUser(user,
new Message(OP.PARAGRAPH).put("paragraph", userParagraphMap.get(user)));
}
}
}
private void broadcastNewParagraph(Note note, Paragraph para) {
LOG.info("Broadcasting paragraph on run call instead of note.");
int paraIndex = note.getParagraphs().indexOf(para);
broadcast(note.getId(),
new Message(OP.PARAGRAPH_ADDED).put("paragraph", para).put("index", paraIndex));
}
public void broadcastNoteList(AuthenticationInfo subject, HashSet userAndRoles) {
if (subject == null) {
subject = new AuthenticationInfo(StringUtils.EMPTY);
}
//send first to requesting user
List<Map<String, String>> notesInfo = generateNotesInfo(false, subject, userAndRoles);
multicastToUser(subject.getUser(), new Message(OP.NOTES_INFO).put("notes", notesInfo));
//to others afterwards
broadcastNoteListExcept(notesInfo, subject);
}
public void unicastNoteList(NotebookSocket conn, AuthenticationInfo subject,
HashSet<String> userAndRoles) {
List<Map<String, String>> notesInfo = generateNotesInfo(false, subject, userAndRoles);
unicast(new Message(OP.NOTES_INFO).put("notes", notesInfo), conn);
}
public void broadcastReloadedNoteList(AuthenticationInfo subject, HashSet userAndRoles) {
if (subject == null) {
subject = new AuthenticationInfo(StringUtils.EMPTY);
}
//reload and reply first to requesting user
List<Map<String, String>> notesInfo = generateNotesInfo(true, subject, userAndRoles);
multicastToUser(subject.getUser(), new Message(OP.NOTES_INFO).put("notes", notesInfo));
//to others afterwards
broadcastNoteListExcept(notesInfo, subject);
}
private void broadcastNoteListExcept(List<Map<String, String>> notesInfo,
AuthenticationInfo subject) {
Set<String> userAndRoles;
NotebookAuthorization authInfo = NotebookAuthorization.getInstance();
for (String user : userConnectedSockets.keySet()) {
if (subject.getUser().equals(user)) {
continue;
}
//reloaded already above; parameter - false
userAndRoles = authInfo.getRoles(user);
userAndRoles.add(user);
notesInfo = generateNotesInfo(false, new AuthenticationInfo(user), userAndRoles);
multicastToUser(user, new Message(OP.NOTES_INFO).put("notes", notesInfo));
}
}
void permissionError(NotebookSocket conn, String op, String userName, Set<String> userAndRoles,
Set<String> allowed) throws IOException {
LOG.info("Cannot {}. Connection readers {}. Allowed readers {}", op, userAndRoles, allowed);
conn.send(serializeMessage(new Message(OP.AUTH_INFO).put("info",
"Insufficient privileges to " + op + " note.\n\n" + "Allowed users or roles: " + allowed
.toString() + "\n\n" + "But the user " + userName + " belongs to: " + userAndRoles
.toString())));
}
private void sendNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
LOG.info("New operation from {} : {} : {} : {} : {}", conn.getRequest().getRemoteAddr(),
conn.getRequest().getRemotePort(), fromMessage.principal, fromMessage.op,
fromMessage.get("id"));
String noteId = (String) fromMessage.get("id");
if (noteId == null) {
return;
}
String user = fromMessage.principal;
Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (note != null) {
if (!notebookAuthorization.isReader(noteId, userAndRoles)) {
permissionError(conn, "read", fromMessage.principal, userAndRoles,
notebookAuthorization.getReaders(noteId));
return;
}
addConnectionToNote(note.getId(), conn);
if (note.isPersonalizedMode()) {
note = note.getUserNote(user);
}
conn.send(serializeMessage(new Message(OP.NOTE).put("note", note)));
sendAllAngularObjects(note, user, conn);
} else {
conn.send(serializeMessage(new Message(OP.NOTE).put("note", null)));
}
}
private void sendHomeNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
String noteId = notebook.getConf().getString(ConfVars.ZEPPELIN_NOTEBOOK_HOMESCREEN);
String user = fromMessage.principal;
Note note = null;
if (noteId != null) {
note = notebook.getNote(noteId);
}
if (note != null) {
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isReader(noteId, userAndRoles)) {
permissionError(conn, "read", fromMessage.principal, userAndRoles,
notebookAuthorization.getReaders(noteId));
return;
}
addConnectionToNote(note.getId(), conn);
conn.send(serializeMessage(new Message(OP.NOTE).put("note", note)));
sendAllAngularObjects(note, user, conn);
} else {
removeConnectionFromAllNote(conn);
conn.send(serializeMessage(new Message(OP.NOTE).put("note", null)));
}
}
private void updateNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws SchedulerException, IOException {
String noteId = (String) fromMessage.get("id");
String name = (String) fromMessage.get("name");
Map<String, Object> config = (Map<String, Object>) fromMessage.get("config");
if (noteId == null) {
return;
}
if (config == null) {
return;
}
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "update", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
Note note = notebook.getNote(noteId);
if (note != null) {
boolean cronUpdated = isCronUpdated(config, note.getConfig());
note.setName(name);
note.setConfig(config);
if (cronUpdated) {
notebook.refreshCron(note.getId());
}
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
note.persist(subject);
broadcast(note.getId(), new Message(OP.NOTE_UPDATED).put("name", name).put("config", config)
.put("info", note.getInfo()));
broadcastNoteList(subject, userAndRoles);
}
}
private void updatePersonalizedMode(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws SchedulerException, IOException {
String noteId = (String) fromMessage.get("id");
String personalized = (String) fromMessage.get("personalized");
boolean isPersonalized = personalized.equals("true") ? true : false;
if (noteId == null) {
return;
}
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
permissionError(conn, "persoanlized ", fromMessage.principal, userAndRoles,
notebookAuthorization.getOwners(noteId));
return;
}
Note note = notebook.getNote(noteId);
if (note != null) {
note.setPersonalizedMode(isPersonalized);
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
note.persist(subject);
broadcastNote(note);
}
}
private void renameNote(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
renameNote(conn, userAndRoles, notebook, fromMessage, "rename");
}
private void renameNote(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage, String op)
throws SchedulerException, IOException {
String noteId = (String) fromMessage.get("id");
String name = (String) fromMessage.get("name");
if (noteId == null) {
return;
}
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
permissionError(conn, "rename", fromMessage.principal, userAndRoles,
notebookAuthorization.getOwners(noteId));
return;
}
Note note = notebook.getNote(noteId);
if (note != null) {
note.setName(name);
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
note.persist(subject);
broadcastNote(note);
broadcastNoteList(subject, userAndRoles);
}
}
private void renameFolder(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
renameFolder(conn, userAndRoles, notebook, fromMessage, "rename");
}
private void renameFolder(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage, String op)
throws SchedulerException, IOException {
String oldFolderId = (String) fromMessage.get("id");
String newFolderId = (String) fromMessage.get("name");
if (oldFolderId == null) {
return;
}
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
for (Note note : notebook.getNotesUnderFolder(oldFolderId)) {
String noteId = note.getId();
if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
permissionError(conn, op + " folder of '" + note.getName() + "'", fromMessage.principal,
userAndRoles, notebookAuthorization.getOwners(noteId));
return;
}
}
Folder oldFolder = notebook.renameFolder(oldFolderId, newFolderId);
if (oldFolder != null) {
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
List<Note> renamedNotes = oldFolder.getNotesRecursively();
for (Note note : renamedNotes) {
note.persist(subject);
broadcastNote(note);
}
broadcastNoteList(subject, userAndRoles);
}
}
private boolean isCronUpdated(Map<String, Object> configA, Map<String, Object> configB) {
boolean cronUpdated = false;
if (configA.get("cron") != null && configB.get("cron") != null && configA.get("cron")
.equals(configB.get("cron"))) {
cronUpdated = true;
} else if (configA.get("cron") == null && configB.get("cron") == null) {
cronUpdated = false;
} else if (configA.get("cron") != null || configB.get("cron") != null) {
cronUpdated = true;
}
return cronUpdated;
}
private void createNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message message) throws IOException {
AuthenticationInfo subject = new AuthenticationInfo(message.principal);
try {
Note note = null;
String defaultInterpreterId = (String) message.get("defaultInterpreterId");
if (!StringUtils.isEmpty(defaultInterpreterId)) {
List<String> interpreterSettingIds = new LinkedList<>();
interpreterSettingIds.add(defaultInterpreterId);
for (String interpreterSettingId : notebook.getInterpreterSettingManager().
getDefaultInterpreterSettingList()) {
if (!interpreterSettingId.equals(defaultInterpreterId)) {
interpreterSettingIds.add(interpreterSettingId);
}
}
note = notebook.createNote(interpreterSettingIds, subject);
} else {
note = notebook.createNote(subject);
}
note.addParagraph(subject); // it's an empty note. so add one paragraph
if (message != null) {
String noteName = (String) message.get("name");
if (StringUtils.isEmpty(noteName)) {
noteName = "Note " + note.getId();
}
note.setName(noteName);
}
note.persist(subject);
addConnectionToNote(note.getId(), (NotebookSocket) conn);
conn.send(serializeMessage(new Message(OP.NEW_NOTE).put("note", note)));
} catch (FileSystemException e) {
LOG.error("Exception from createNote", e);
conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info",
"Oops! There is something wrong with the notebook file system. "
+ "Please check the logs for more details.")));
return;
}
broadcastNoteList(subject, userAndRoles);
}
private void removeNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
String noteId = (String) fromMessage.get("id");
if (noteId == null) {
return;
}
Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
permissionError(conn, "remove", fromMessage.principal, userAndRoles,
notebookAuthorization.getOwners(noteId));
return;
}
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
notebook.removeNote(noteId, subject);
removeNote(noteId);
broadcastNoteList(subject, userAndRoles);
}
private void removeFolder(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
String folderId = (String) fromMessage.get("id");
if (folderId == null) {
return;
}
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
List<Note> notes = notebook.getNotesUnderFolder(folderId);
for (Note note : notes) {
String noteId = note.getId();
if (!notebookAuthorization.isOwner(noteId, userAndRoles)) {
permissionError(conn, "remove folder of '" + note.getName() + "'", fromMessage.principal,
userAndRoles, notebookAuthorization.getOwners(noteId));
return;
}
}
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
for (Note note : notes) {
notebook.removeNote(note.getId(), subject);
removeNote(note.getId());
}
broadcastNoteList(subject, userAndRoles);
}
private void moveNoteToTrash(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
String noteId = (String) fromMessage.get("id");
if (noteId == null) {
return;
}
Note note = notebook.getNote(noteId);
if (note != null && !note.isTrash()){
fromMessage.put("name", Folder.TRASH_FOLDER_ID + "/" + note.getName());
renameNote(conn, userAndRoles, notebook, fromMessage, "move");
notebook.moveNoteToTrash(note.getId());
}
}
private void moveFolderToTrash(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
String folderId = (String) fromMessage.get("id");
if (folderId == null) {
return;
}
Folder folder = notebook.getFolder(folderId);
if (folder != null && !folder.isTrash()) {
String trashFolderId = Folder.TRASH_FOLDER_ID + "/" + folderId;
if (notebook.hasFolder(trashFolderId)){
DateTime currentDate = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
trashFolderId += Folder.TRASH_FOLDER_CONFLICT_INFIX + formatter.print(currentDate);
}
fromMessage.put("name", trashFolderId);
renameFolder(conn, userAndRoles, notebook, fromMessage, "move");
}
}
private void restoreNote(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
String noteId = (String) fromMessage.get("id");
if (noteId == null) {
return;
}
Note note = notebook.getNote(noteId);
if (note != null && note.isTrash()) {
fromMessage.put("name", note.getName().replaceFirst(Folder.TRASH_FOLDER_ID + "/", ""));
renameNote(conn, userAndRoles, notebook, fromMessage, "restore");
}
}
private void restoreFolder(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
String folderId = (String) fromMessage.get("id");
if (folderId == null) {
return;
}
Folder folder = notebook.getFolder(folderId);
if (folder != null && folder.isTrash()) {
String restoreName = folder.getId().replaceFirst(Folder.TRASH_FOLDER_ID + "/", "").trim();
// if the folder had conflict when it had moved to trash before
Pattern p = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$");
Matcher m = p.matcher(restoreName);
restoreName = m.replaceAll("").trim();
fromMessage.put("name", restoreName);
renameFolder(conn, userAndRoles, notebook, fromMessage, "restore");
}
}
private void restoreAll(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
Folder trashFolder = notebook.getFolder(Folder.TRASH_FOLDER_ID);
if (trashFolder != null) {
fromMessage.data = new HashMap<>();
fromMessage.put("id", Folder.TRASH_FOLDER_ID);
fromMessage.put("name", Folder.ROOT_FOLDER_ID);
renameFolder(conn, userAndRoles, notebook, fromMessage, "restore trash");
}
}
private void emptyTrash(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage)
throws SchedulerException, IOException {
fromMessage.data = new HashMap<>();
fromMessage.put("id", Folder.TRASH_FOLDER_ID);
removeFolder(conn, userAndRoles, notebook, fromMessage);
}
private void updateParagraph(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws IOException {
String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
Map<String, Object> params = (Map<String, Object>) fromMessage.get("params");
Map<String, Object> config = (Map<String, Object>) fromMessage.get("config");
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
Paragraph p = note.getParagraph(paragraphId);
if (note.isPersonalizedMode()) {
p = p.getUserParagraphMap().get(subject.getUser());
}
p.settings.setParams(params);
p.setConfig(config);
p.setTitle((String) fromMessage.get("title"));
p.setText((String) fromMessage.get("paragraph"));
subject = new AuthenticationInfo(fromMessage.principal);
if (note.isPersonalizedMode()) {
p = p.getUserParagraph(subject.getUser());
p.settings.setParams(params);
p.setConfig(config);
p.setTitle((String) fromMessage.get("title"));
p.setText((String) fromMessage.get("paragraph"));
}
note.persist(subject);
if (note.isPersonalizedMode()) {
Map<String, Paragraph> userParagraphMap =
note.getParagraph(paragraphId).getUserParagraphMap();
broadcastParagraphs(userParagraphMap);
} else {
broadcastParagraph(note, p);
}
}
private void cloneNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException, CloneNotSupportedException {
String noteId = getOpenNoteId(conn);
String name = (String) fromMessage.get("name");
Note newNote = notebook.cloneNote(noteId, name, new AuthenticationInfo(fromMessage.principal));
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
addConnectionToNote(newNote.getId(), (NotebookSocket) conn);
conn.send(serializeMessage(new Message(OP.NEW_NOTE).put("note", newNote)));
broadcastNoteList(subject, userAndRoles);
}
private void clearAllParagraphOutput(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws IOException {
final String noteId = (String) fromMessage.get("id");
if (StringUtils.isBlank(noteId)) {
return;
}
Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "clear output", fromMessage.principal, userAndRoles,
notebookAuthorization.getOwners(noteId));
return;
}
note.clearAllParagraphOutput();
broadcastNote(note);
}
protected Note importNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
Note note = null;
if (fromMessage != null) {
String noteName = (String) ((Map) fromMessage.get("note")).get("name");
String noteJson = gson.toJson(fromMessage.get("note"));
AuthenticationInfo subject = null;
if (fromMessage.principal != null) {
subject = new AuthenticationInfo(fromMessage.principal);
} else {
subject = new AuthenticationInfo("anonymous");
}
note = notebook.importNote(noteJson, noteName, subject);
note.persist(subject);
broadcastNote(note);
broadcastNoteList(subject, userAndRoles);
}
return note;
}
private void removeParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
final String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
/** We dont want to remove the last paragraph */
if (!note.isLastParagraph(paragraphId)) {
Paragraph para = note.removeParagraph(subject.getUser(), paragraphId);
note.persist(subject);
if (para != null) {
broadcast(note.getId(), new Message(OP.PARAGRAPH_REMOVED).
put("id", para.getId()));
}
}
}
private void clearParagraphOutput(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws IOException {
final String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
String user = (note.isPersonalizedMode()) ?
new AuthenticationInfo(fromMessage.principal).getUser() : null;
Paragraph p = note.clearParagraphOutput(paragraphId, user);
broadcastParagraph(note, p);
}
private void completion(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
String paragraphId = (String) fromMessage.get("id");
String buffer = (String) fromMessage.get("buf");
int cursor = (int) Double.parseDouble(fromMessage.get("cursor").toString());
Message resp = new Message(OP.COMPLETION_LIST).put("id", paragraphId);
if (paragraphId == null) {
conn.send(serializeMessage(resp));
return;
}
final Note note = notebook.getNote(getOpenNoteId(conn));
List<InterpreterCompletion> candidates = note.completion(paragraphId, buffer, cursor);
resp.put("completions", candidates);
conn.send(serializeMessage(resp));
}
/**
* When angular object updated from client
*
* @param conn the web socket.
* @param notebook the notebook.
* @param fromMessage the message.
*/
private void angularObjectUpdated(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) {
String noteId = (String) fromMessage.get("noteId");
String paragraphId = (String) fromMessage.get("paragraphId");
String interpreterGroupId = (String) fromMessage.get("interpreterGroupId");
String varName = (String) fromMessage.get("name");
Object varValue = fromMessage.get("value");
String user = fromMessage.principal;
AngularObject ao = null;
boolean global = false;
// propagate change to (Remote) AngularObjectRegistry
Note note = notebook.getNote(noteId);
if (note != null) {
List<InterpreterSetting> settings =
notebook.getInterpreterSettingManager().getInterpreterSettings(note.getId());
for (InterpreterSetting setting : settings) {
if (setting.getInterpreterGroup(user, note.getId()) == null) {
continue;
}
if (interpreterGroupId.equals(setting.getInterpreterGroup(user, note.getId()).getId())) {
AngularObjectRegistry angularObjectRegistry =
setting.getInterpreterGroup(user, note.getId()).getAngularObjectRegistry();
// first trying to get local registry
ao = angularObjectRegistry.get(varName, noteId, paragraphId);
if (ao == null) {
// then try notebook scope registry
ao = angularObjectRegistry.get(varName, noteId, null);
if (ao == null) {
// then try global scope registry
ao = angularObjectRegistry.get(varName, null, null);
if (ao == null) {
LOG.warn("Object {} is not binded", varName);
} else {
// path from client -> server
ao.set(varValue, false);
global = true;
}
} else {
// path from client -> server
ao.set(varValue, false);
global = false;
}
} else {
ao.set(varValue, false);
global = false;
}
break;
}
}
}
if (global) { // broadcast change to all web session that uses related
// interpreter.
for (Note n : notebook.getAllNotes()) {
List<InterpreterSetting> settings =
notebook.getInterpreterSettingManager().getInterpreterSettings(note.getId());
for (InterpreterSetting setting : settings) {
if (setting.getInterpreterGroup(user, n.getId()) == null) {
continue;
}
if (interpreterGroupId.equals(setting.getInterpreterGroup(user, n.getId()).getId())) {
AngularObjectRegistry angularObjectRegistry =
setting.getInterpreterGroup(user, n.getId()).getAngularObjectRegistry();
this.broadcastExcept(n.getId(),
new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", ao)
.put("interpreterGroupId", interpreterGroupId).put("noteId", n.getId())
.put("paragraphId", ao.getParagraphId()), conn);
}
}
}
} else { // broadcast to all web session for the note
this.broadcastExcept(note.getId(),
new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", ao)
.put("interpreterGroupId", interpreterGroupId).put("noteId", note.getId())
.put("paragraphId", ao.getParagraphId()), conn);
}
}
/**
* Push the given Angular variable to the target
* interpreter angular registry given a noteId
* and a paragraph id
*/
protected void angularObjectClientBind(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws Exception {
String noteId = fromMessage.getType("noteId");
String varName = fromMessage.getType("name");
Object varValue = fromMessage.get("value");
String paragraphId = fromMessage.getType("paragraphId");
Note note = notebook.getNote(noteId);
if (paragraphId == null) {
throw new IllegalArgumentException(
"target paragraph not specified for " + "angular value bind");
}
if (note != null) {
final InterpreterGroup interpreterGroup = findInterpreterGroupForParagraph(note, paragraphId);
final AngularObjectRegistry registry = interpreterGroup.getAngularObjectRegistry();
if (registry instanceof RemoteAngularObjectRegistry) {
RemoteAngularObjectRegistry remoteRegistry = (RemoteAngularObjectRegistry) registry;
pushAngularObjectToRemoteRegistry(noteId, paragraphId, varName, varValue, remoteRegistry,
interpreterGroup.getId(), conn);
} else {
pushAngularObjectToLocalRepo(noteId, paragraphId, varName, varValue, registry,
interpreterGroup.getId(), conn);
}
}
}
/**
* Remove the given Angular variable to the target
* interpreter(s) angular registry given a noteId
* and an optional list of paragraph id(s)
*/
protected void angularObjectClientUnbind(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws Exception {
String noteId = fromMessage.getType("noteId");
String varName = fromMessage.getType("name");
String paragraphId = fromMessage.getType("paragraphId");
Note note = notebook.getNote(noteId);
if (paragraphId == null) {
throw new IllegalArgumentException(
"target paragraph not specified for " + "angular value unBind");
}
if (note != null) {
final InterpreterGroup interpreterGroup = findInterpreterGroupForParagraph(note, paragraphId);
final AngularObjectRegistry registry = interpreterGroup.getAngularObjectRegistry();
if (registry instanceof RemoteAngularObjectRegistry) {
RemoteAngularObjectRegistry remoteRegistry = (RemoteAngularObjectRegistry) registry;
removeAngularFromRemoteRegistry(noteId, paragraphId, varName, remoteRegistry,
interpreterGroup.getId(), conn);
} else {
removeAngularObjectFromLocalRepo(noteId, paragraphId, varName, registry,
interpreterGroup.getId(), conn);
}
}
}
private InterpreterGroup findInterpreterGroupForParagraph(Note note, String paragraphId)
throws Exception {
final Paragraph paragraph = note.getParagraph(paragraphId);
if (paragraph == null) {
throw new IllegalArgumentException("Unknown paragraph with id : " + paragraphId);
}
return paragraph.getCurrentRepl().getInterpreterGroup();
}
private void pushAngularObjectToRemoteRegistry(String noteId, String paragraphId, String varName,
Object varValue, RemoteAngularObjectRegistry remoteRegistry, String interpreterGroupId,
NotebookSocket conn) {
final AngularObject ao =
remoteRegistry.addAndNotifyRemoteProcess(varName, varValue, noteId, paragraphId);
this.broadcastExcept(noteId, new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", ao)
.put("interpreterGroupId", interpreterGroupId).put("noteId", noteId)
.put("paragraphId", paragraphId), conn);
}
private void removeAngularFromRemoteRegistry(String noteId, String paragraphId, String varName,
RemoteAngularObjectRegistry remoteRegistry, String interpreterGroupId, NotebookSocket conn) {
final AngularObject ao =
remoteRegistry.removeAndNotifyRemoteProcess(varName, noteId, paragraphId);
this.broadcastExcept(noteId, new Message(OP.ANGULAR_OBJECT_REMOVE).put("angularObject", ao)
.put("interpreterGroupId", interpreterGroupId).put("noteId", noteId)
.put("paragraphId", paragraphId), conn);
}
private void pushAngularObjectToLocalRepo(String noteId, String paragraphId, String varName,
Object varValue, AngularObjectRegistry registry, String interpreterGroupId,
NotebookSocket conn) {
AngularObject angularObject = registry.get(varName, noteId, paragraphId);
if (angularObject == null) {
angularObject = registry.add(varName, varValue, noteId, paragraphId);
} else {
angularObject.set(varValue, true);
}
this.broadcastExcept(noteId,
new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", angularObject)
.put("interpreterGroupId", interpreterGroupId).put("noteId", noteId)
.put("paragraphId", paragraphId), conn);
}
private void removeAngularObjectFromLocalRepo(String noteId, String paragraphId, String varName,
AngularObjectRegistry registry, String interpreterGroupId, NotebookSocket conn) {
final AngularObject removed = registry.remove(varName, noteId, paragraphId);
if (removed != null) {
this.broadcastExcept(noteId,
new Message(OP.ANGULAR_OBJECT_REMOVE).put("angularObject", removed)
.put("interpreterGroupId", interpreterGroupId).put("noteId", noteId)
.put("paragraphId", paragraphId), conn);
}
}
private void moveParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
final String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
final int newIndex = (int) Double.parseDouble(fromMessage.get("index").toString());
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
note.moveParagraph(paragraphId, newIndex);
note.persist(subject);
broadcast(note.getId(),
new Message(OP.PARAGRAPH_MOVED).put("id", paragraphId).put("index", newIndex));
}
private String insertParagraph(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook, Message fromMessage) throws IOException {
final int index = (int) Double.parseDouble(fromMessage.get("index").toString());
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return null;
}
Paragraph newPara = note.insertParagraph(index, subject);
note.persist(subject);
broadcastNewParagraph(note, newPara);
return newPara.getId();
}
private void copyParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
String newParaId = insertParagraph(conn, userAndRoles, notebook, fromMessage);
if (newParaId == null) {
return;
}
fromMessage.put("id", newParaId);
updateParagraph(conn, userAndRoles, notebook, fromMessage);
}
private void cancelParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
final String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
Paragraph p = note.getParagraph(paragraphId);
p.abort();
}
private void runAllParagraphs(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook,
Message fromMessage) throws IOException {
final String noteId = (String) fromMessage.get("noteId");
if (StringUtils.isBlank(noteId)) {
return;
}
Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "run all paragraphs", fromMessage.principal, userAndRoles,
notebookAuthorization.getOwners(noteId));
return;
}
List<Map<String, Object>> paragraphs =
gson.fromJson(String.valueOf(fromMessage.data.get("paragraphs")),
new TypeToken<List<Map<String, Object>>>() {}.getType());
for (Map<String, Object> raw : paragraphs) {
String paragraphId = (String) raw.get("id");
if (paragraphId == null) {
continue;
}
String text = (String) raw.get("paragraph");
String title = (String) raw.get("title");
Map<String, Object> params = (Map<String, Object>) raw.get("params");
Map<String, Object> config = (Map<String, Object>) raw.get("config");
Paragraph p = setParagraphUsingMessage(note, fromMessage,
paragraphId, text, title, params, config);
persistAndExecuteSingleParagraph(conn, note, p);
}
}
private void runParagraph(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
final String paragraphId = (String) fromMessage.get("id");
if (paragraphId == null) {
return;
}
String noteId = getOpenNoteId(conn);
final Note note = notebook.getNote(noteId);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "write", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
String text = (String) fromMessage.get("paragraph");
String title = (String) fromMessage.get("title");
Map<String, Object> params = (Map<String, Object>) fromMessage.get("params");
Map<String, Object> config = (Map<String, Object>) fromMessage.get("config");
Paragraph p = setParagraphUsingMessage(note, fromMessage, paragraphId,
text, title, params, config);
persistAndExecuteSingleParagraph(conn, note, p);
}
private void persistAndExecuteSingleParagraph(NotebookSocket conn,
Note note, Paragraph p) throws IOException {
// if it's the last paragraph and empty, let's add a new one
boolean isTheLastParagraph = note.isLastParagraph(p.getId());
if (!(p.getText().trim().equals(p.getMagic()) ||
Strings.isNullOrEmpty(p.getText())) &&
isTheLastParagraph) {
Paragraph newPara = note.addParagraph(p.getAuthenticationInfo());
broadcastNewParagraph(note, newPara);
}
try {
note.persist(p.getAuthenticationInfo());
} catch (FileSystemException ex) {
LOG.error("Exception from run", ex);
conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info",
"Oops! There is something wrong with the notebook file system. "
+ "Please check the logs for more details.")));
// don't run the paragraph when there is error on persisting the note information
return;
}
try {
note.run(p.getId());
} catch (Exception ex) {
LOG.error("Exception from run", ex);
if (p != null) {
p.setReturn(new InterpreterResult(InterpreterResult.Code.ERROR, ex.getMessage()), ex);
p.setStatus(Status.ERROR);
broadcast(note.getId(), new Message(OP.PARAGRAPH).put("paragraph", p));
}
}
}
private Paragraph setParagraphUsingMessage(Note note, Message fromMessage, String paragraphId,
String text, String title, Map<String, Object> params,
Map<String, Object> config) {
Paragraph p = note.getParagraph(paragraphId);
p.setText(text);
p.setTitle(title);
AuthenticationInfo subject =
new AuthenticationInfo(fromMessage.principal, fromMessage.ticket);
p.setAuthenticationInfo(subject);
p.settings.setParams(params);
p.setConfig(config);
if (note.isPersonalizedMode()) {
p = note.getParagraph(paragraphId);
p.setText(text);
p.setTitle(title);
p.setAuthenticationInfo(subject);
p.settings.setParams(params);
p.setConfig(config);
}
return p;
}
private void sendAllConfigurations(NotebookSocket conn, HashSet<String> userAndRoles,
Notebook notebook) throws IOException {
ZeppelinConfiguration conf = notebook.getConf();
Map<String, String> configurations =
conf.dumpConfigurations(conf, new ZeppelinConfiguration.ConfigurationKeyPredicate() {
@Override
public boolean apply(String key) {
return !key.contains("password") && !key.equals(
ZeppelinConfiguration.ConfVars.ZEPPELIN_NOTEBOOK_AZURE_CONNECTION_STRING
.getVarName());
}
});
conn.send(serializeMessage(
new Message(OP.CONFIGURATIONS_INFO).put("configurations", configurations)));
}
private void checkpointNote(NotebookSocket conn, Notebook notebook, Message fromMessage)
throws IOException {
String noteId = (String) fromMessage.get("noteId");
String commitMessage = (String) fromMessage.get("commitMessage");
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
Revision revision = notebook.checkpointNote(noteId, commitMessage, subject);
if (!Revision.isEmpty(revision)) {
List<Revision> revisions = notebook.listRevisionHistory(noteId, subject);
conn.send(
serializeMessage(new Message(OP.LIST_REVISION_HISTORY).put("revisionList", revisions)));
} else {
conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info",
"Couldn't checkpoint note revision: possibly storage doesn't support versioning. "
+ "Please check the logs for more details.")));
}
}
private void listRevisionHistory(NotebookSocket conn, Notebook notebook, Message fromMessage)
throws IOException {
String noteId = (String) fromMessage.get("noteId");
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
List<Revision> revisions = notebook.listRevisionHistory(noteId, subject);
conn.send(
serializeMessage(new Message(OP.LIST_REVISION_HISTORY).put("revisionList", revisions)));
}
private void setNoteRevision(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook,
Message fromMessage) throws IOException {
String noteId = (String) fromMessage.get("noteId");
String revisionId = (String) fromMessage.get("revisionId");
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
NotebookAuthorization notebookAuthorization = notebook.getNotebookAuthorization();
if (!notebookAuthorization.isWriter(noteId, userAndRoles)) {
permissionError(conn, "update", fromMessage.principal, userAndRoles,
notebookAuthorization.getWriters(noteId));
return;
}
Note headNote = null;
boolean setRevisionStatus;
try {
headNote = notebook.setNoteRevision(noteId, revisionId, subject);
setRevisionStatus = headNote != null;
} catch (Exception e) {
setRevisionStatus = false;
LOG.error("Failed to set given note revision", e);
}
if (setRevisionStatus) {
notebook.loadNoteFromRepo(noteId, subject);
}
conn.send(serializeMessage(new Message(OP.SET_NOTE_REVISION).put("status", setRevisionStatus)));
if (setRevisionStatus) {
Note reloadedNote = notebook.getNote(headNote.getId());
broadcastNote(reloadedNote);
} else {
conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info",
"Couldn't set note to the given revision. "
+ "Please check the logs for more details.")));
}
}
private void getNoteByRevision(NotebookSocket conn, Notebook notebook, Message fromMessage)
throws IOException {
String noteId = (String) fromMessage.get("noteId");
String revisionId = (String) fromMessage.get("revisionId");
AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal);
Note revisionNote = notebook.getNoteByRevision(noteId, revisionId, subject);
conn.send(serializeMessage(
new Message(OP.NOTE_REVISION).put("noteId", noteId).put("revisionId", revisionId)
.put("note", revisionNote)));
}
/**
* This callback is for the paragraph that runs on ZeppelinServer
*
* @param output output to append
*/
@Override
public void onOutputAppend(String noteId, String paragraphId, int index, String output) {
Message msg = new Message(OP.PARAGRAPH_APPEND_OUTPUT).put("noteId", noteId)
.put("paragraphId", paragraphId).put("index", index).put("data", output);
broadcast(noteId, msg);
}
/**
* This callback is for the paragraph that runs on ZeppelinServer
*
* @param output output to update (replace)
*/
@Override
public void onOutputUpdated(String noteId, String paragraphId, int index,
InterpreterResult.Type type, String output) {
Message msg = new Message(OP.PARAGRAPH_UPDATE_OUTPUT).put("noteId", noteId)
.put("paragraphId", paragraphId).put("index", index).put("type", type).put("data", output);
Note note = notebook().getNote(noteId);
if (note.isPersonalizedMode()) {
String user = note.getParagraph(paragraphId).getUser();
if (null != user) {
multicastToUser(user, msg);
}
} else {
broadcast(noteId, msg);
}
}
/**
* This callback is for the paragraph that runs on ZeppelinServer
*/
@Override
public void onOutputClear(String noteId, String paragraphId) {
Notebook notebook = notebook();
final Note note = notebook.getNote(noteId);
note.clearParagraphOutput(paragraphId, null);
Paragraph paragraph = note.getParagraph(paragraphId);
broadcastParagraph(note, paragraph);
}
/**
* When application append output
*/
@Override
public void onOutputAppend(String noteId, String paragraphId, int index, String appId,
String output) {
Message msg =
new Message(OP.APP_APPEND_OUTPUT).put("noteId", noteId).put("paragraphId", paragraphId)
.put("index", index).put("appId", appId).put("data", output);
broadcast(noteId, msg);
}
/**
* When application update output
*/
@Override
public void onOutputUpdated(String noteId, String paragraphId, int index, String appId,
InterpreterResult.Type type, String output) {
Message msg =
new Message(OP.APP_UPDATE_OUTPUT).put("noteId", noteId).put("paragraphId", paragraphId)
.put("index", index).put("type", type).put("appId", appId).put("data", output);
broadcast(noteId, msg);
}
@Override
public void onLoad(String noteId, String paragraphId, String appId, HeliumPackage pkg) {
Message msg = new Message(OP.APP_LOAD).put("noteId", noteId).put("paragraphId", paragraphId)
.put("appId", appId).put("pkg", pkg);
broadcast(noteId, msg);
}
@Override
public void onStatusChange(String noteId, String paragraphId, String appId, String status) {
Message msg =
new Message(OP.APP_STATUS_CHANGE).put("noteId", noteId).put("paragraphId", paragraphId)
.put("appId", appId).put("status", status);
broadcast(noteId, msg);
}
@Override
public void onGetParagraphRunners(String noteId, String paragraphId,
RemoteWorksEventListener callback) {
Notebook notebookIns = notebook();
List<InterpreterContextRunner> runner = new LinkedList<>();
if (notebookIns == null) {
LOG.info("intepreter request notebook instance is null");
callback.onFinished(notebookIns);
}
try {
Note note = notebookIns.getNote(noteId);
if (note != null) {
if (paragraphId != null) {
Paragraph paragraph = note.getParagraph(paragraphId);
if (paragraph != null) {
runner.add(paragraph.getInterpreterContextRunner());
}
} else {
for (Paragraph p : note.getParagraphs()) {
runner.add(p.getInterpreterContextRunner());
}
}
}
callback.onFinished(runner);
} catch (NullPointerException e) {
LOG.warn(e.getMessage());
callback.onError();
}
}
@Override
public void onRemoteRunParagraph(String noteId, String paragraphId) throws Exception {
Notebook notebookIns = notebook();
try {
if (notebookIns == null) {
throw new Exception("onRemoteRunParagraph notebook instance is null");
}
Note noteIns = notebookIns.getNote(noteId);
if (noteIns == null) {
throw new Exception(String.format("Can't found note id %s", noteId));
}
Paragraph paragraph = noteIns.getParagraph(paragraphId);
if (paragraph == null) {
throw new Exception(String.format("Can't found paragraph %s %s", noteId, paragraphId));
}
Set<String> userAndRoles = Sets.newHashSet();
userAndRoles.add(SecurityUtils.getPrincipal());
userAndRoles.addAll(SecurityUtils.getRoles());
if (!notebookIns.getNotebookAuthorization().hasWriteAuthorization(userAndRoles, noteId)) {
throw new ForbiddenException(String.format("can't execute note %s", noteId));
}
AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
paragraph.setAuthenticationInfo(subject);
noteIns.run(paragraphId);
} catch (Exception e) {
throw e;
}
}
/**
* Notebook Information Change event
*/
public static class NotebookInformationListener implements NotebookEventListener {
private NotebookServer notebookServer;
public NotebookInformationListener(NotebookServer notebookServer) {
this.notebookServer = notebookServer;
}
@Override
public void onParagraphRemove(Paragraph p) {
try {
notebookServer.broadcastUpdateNoteJobInfo(System.currentTimeMillis() - 5000);
} catch (IOException ioe) {
LOG.error("can not broadcast for job manager {}", ioe.getMessage());
}
}
@Override
public void onNoteRemove(Note note) {
try {
notebookServer.broadcastUpdateNoteJobInfo(System.currentTimeMillis() - 5000);
} catch (IOException ioe) {
LOG.error("can not broadcast for job manager {}", ioe.getMessage());
}
List<Map<String, Object>> notesInfo = new LinkedList<>();
Map<String, Object> info = new HashMap<>();
info.put("noteId", note.getId());
// set paragraphs
List<Map<String, Object>> paragraphsInfo = new LinkedList<>();
// notebook json object root information.
info.put("isRunningJob", false);
info.put("unixTimeLastRun", 0);
info.put("isRemoved", true);
info.put("paragraphs", paragraphsInfo);
notesInfo.add(info);
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", notesInfo);
notebookServer.broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
@Override
public void onParagraphCreate(Paragraph p) {
Notebook notebook = notebookServer.notebook();
List<Map<String, Object>> notebookJobs = notebook.getJobListByParagraphId(p.getId());
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", notebookJobs);
notebookServer.broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
@Override
public void onNoteCreate(Note note) {
Notebook notebook = notebookServer.notebook();
List<Map<String, Object>> notebookJobs = notebook.getJobListByNoteId(note.getId());
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", notebookJobs);
notebookServer.broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
@Override
public void onParagraphStatusChange(Paragraph p, Status status) {
Notebook notebook = notebookServer.notebook();
List<Map<String, Object>> notebookJobs = notebook.getJobListByParagraphId(p.getId());
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", notebookJobs);
notebookServer.broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
@Override
public void onUnbindInterpreter(Note note, InterpreterSetting setting) {
Notebook notebook = notebookServer.notebook();
List<Map<String, Object>> notebookJobs = notebook.getJobListByNoteId(note.getId());
Map<String, Object> response = new HashMap<>();
response.put("lastResponseUnixTime", System.currentTimeMillis());
response.put("jobs", notebookJobs);
notebookServer.broadcast(JOB_MANAGER_SERVICE.JOB_MANAGER_PAGE.getKey(),
new Message(OP.LIST_UPDATE_NOTE_JOBS).put("noteRunningJobs", response));
}
}
/**
* Need description here.
*/
public static class ParagraphListenerImpl implements ParagraphJobListener {
private NotebookServer notebookServer;
private Note note;
public ParagraphListenerImpl(NotebookServer notebookServer, Note note) {
this.notebookServer = notebookServer;
this.note = note;
}
@Override
public void onProgressUpdate(Job job, int progress) {
notebookServer.broadcast(note.getId(),
new Message(OP.PROGRESS).put("id", job.getId()).put("progress", progress));
}
@Override
public void beforeStatusChange(Job job, Status before, Status after) {
}
@Override
public void afterStatusChange(Job job, Status before, Status after) {
if (after == Status.ERROR) {
if (job.getException() != null) {
LOG.error("Error", job.getException());
}
}
if (job.isTerminated()) {
if (job.getStatus() == Status.FINISHED) {
LOG.info("Job {} is finished successfully, status: {}", job.getId(), job.getStatus());
} else {
LOG.warn("Job {} is finished, status: {}, exception: {}, result: {}" , job.getId(),
job.getStatus(), job.getException(), job.getReturn());
}
try {
//TODO(khalid): may change interface for JobListener and pass subject from interpreter
note.persist(job instanceof Paragraph ? ((Paragraph) job).getAuthenticationInfo() : null);
} catch (IOException e) {
LOG.error(e.toString(), e);
}
}
if (job instanceof Paragraph) {
Paragraph p = (Paragraph) job;
p.setStatusToUserParagraph(job.getStatus());
notebookServer.broadcastParagraph(note, p);
}
try {
notebookServer.broadcastUpdateNoteJobInfo(System.currentTimeMillis() - 5000);
} catch (IOException e) {
LOG.error("can not broadcast for job manager {}", e);
}
}
/**
* This callback is for paragraph that runs on RemoteInterpreterProcess
*/
@Override
public void onOutputAppend(Paragraph paragraph, int idx, String output) {
Message msg =
new Message(OP.PARAGRAPH_APPEND_OUTPUT).put("noteId", paragraph.getNote().getId())
.put("paragraphId", paragraph.getId()).put("data", output);
notebookServer.broadcast(paragraph.getNote().getId(), msg);
}
/**
* This callback is for paragraph that runs on RemoteInterpreterProcess
*/
@Override
public void onOutputUpdate(Paragraph paragraph, int idx, InterpreterResultMessage result) {
String output = result.getData();
Message msg =
new Message(OP.PARAGRAPH_UPDATE_OUTPUT).put("noteId", paragraph.getNote().getId())
.put("paragraphId", paragraph.getId()).put("data", output);
notebookServer.broadcast(paragraph.getNote().getId(), msg);
}
@Override
public void onOutputUpdateAll(Paragraph paragraph, List<InterpreterResultMessage> msgs) {
// TODO
}
}
@Override
public ParagraphJobListener getParagraphJobListener(Note note) {
return new ParagraphListenerImpl(this, note);
}
public NotebookEventListener getNotebookInformationListener() {
return new NotebookInformationListener(this);
}
private void sendAllAngularObjects(Note note, String user, NotebookSocket conn)
throws IOException {
List<InterpreterSetting> settings =
notebook().getInterpreterSettingManager().getInterpreterSettings(note.getId());
if (settings == null || settings.size() == 0) {
return;
}
for (InterpreterSetting intpSetting : settings) {
AngularObjectRegistry registry =
intpSetting.getInterpreterGroup(user, note.getId()).getAngularObjectRegistry();
List<AngularObject> objects = registry.getAllWithGlobal(note.getId());
for (AngularObject object : objects) {
conn.send(serializeMessage(
new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", object)
.put("interpreterGroupId",
intpSetting.getInterpreterGroup(user, note.getId()).getId())
.put("noteId", note.getId()).put("paragraphId", object.getParagraphId())));
}
}
}
@Override
public void onAdd(String interpreterGroupId, AngularObject object) {
onUpdate(interpreterGroupId, object);
}
@Override
public void onUpdate(String interpreterGroupId, AngularObject object) {
Notebook notebook = notebook();
if (notebook == null) {
return;
}
List<Note> notes = notebook.getAllNotes();
for (Note note : notes) {
if (object.getNoteId() != null && !note.getId().equals(object.getNoteId())) {
continue;
}
List<InterpreterSetting> intpSettings =
notebook.getInterpreterSettingManager().getInterpreterSettings(note.getId());
if (intpSettings.isEmpty()) {
continue;
}
broadcast(note.getId(), new Message(OP.ANGULAR_OBJECT_UPDATE).put("angularObject", object)
.put("interpreterGroupId", interpreterGroupId).put("noteId", note.getId())
.put("paragraphId", object.getParagraphId()));
}
}
@Override
public void onRemove(String interpreterGroupId, String name, String noteId, String paragraphId) {
Notebook notebook = notebook();
List<Note> notes = notebook.getAllNotes();
for (Note note : notes) {
if (noteId != null && !note.getId().equals(noteId)) {
continue;
}
List<String> settingIds =
notebook.getInterpreterSettingManager().getInterpreters(note.getId());
for (String id : settingIds) {
if (interpreterGroupId.contains(id)) {
broadcast(note.getId(),
new Message(OP.ANGULAR_OBJECT_REMOVE).put("name", name).put("noteId", noteId)
.put("paragraphId", paragraphId));
break;
}
}
}
}
private void getEditorSetting(NotebookSocket conn, Message fromMessage) throws IOException {
String paragraphId = (String) fromMessage.get("paragraphId");
String replName = (String) fromMessage.get("magic");
String noteId = getOpenNoteId(conn);
String user = fromMessage.principal;
Message resp = new Message(OP.EDITOR_SETTING);
resp.put("paragraphId", paragraphId);
Interpreter interpreter =
notebook().getInterpreterFactory().getInterpreter(user, noteId, replName);
resp.put("editor", notebook().getInterpreterSettingManager().
getEditorSetting(interpreter, user, noteId, replName));
conn.send(serializeMessage(resp));
return;
}
private void getInterpreterSettings(NotebookSocket conn, AuthenticationInfo subject)
throws IOException {
List<InterpreterSetting> availableSettings = notebook().getInterpreterSettingManager().get();
conn.send(serializeMessage(
new Message(OP.INTERPRETER_SETTINGS).put("interpreterSettings", availableSettings)));
}
@Override
public void onMetaInfosReceived(String settingId, Map<String, String> metaInfos) {
InterpreterSetting interpreterSetting =
notebook().getInterpreterSettingManager().get(settingId);
interpreterSetting.setInfos(metaInfos);
}
private void switchConnectionToWatcher(NotebookSocket conn, Message messagereceived)
throws IOException {
if (!isSessionAllowedToSwitchToWatcher(conn)) {
LOG.error("Cannot switch this client to watcher, invalid security key");
return;
}
LOG.info("Going to add {} to watcher socket", conn);
// add the connection to the watcher.
if (watcherSockets.contains(conn)) {
LOG.info("connection alrerady present in the watcher");
return;
}
watcherSockets.add(conn);
// remove this connection from regular zeppelin ws usage.
removeConnectionFromAllNote(conn);
connectedSockets.remove(conn);
removeUserConnection(conn.getUser(), conn);
}
private boolean isSessionAllowedToSwitchToWatcher(NotebookSocket session) {
String watcherSecurityKey = session.getRequest().getHeader(WatcherSecurityKey.HTTP_HEADER);
return !(StringUtils.isBlank(watcherSecurityKey) || !watcherSecurityKey
.equals(WatcherSecurityKey.getKey()));
}
private void broadcastToWatchers(String noteId, String subject, Message message) {
synchronized (watcherSockets) {
if (watcherSockets.isEmpty()) {
return;
}
for (NotebookSocket watcher : watcherSockets) {
try {
watcher.send(
WatcherMessage.builder(noteId).subject(subject).message(serializeMessage(message))
.build().serialize());
} catch (IOException e) {
LOG.error("Cannot broadcast message to watcher", e);
}
}
}
}
}
| apache-2.0 |
TranscendComputing/TopStackCompute | test/java/com/msi/compute/integration/RevokeSecurityGroupIngressTest.java | 4026 | package com.msi.compute.integration;
import java.util.Collection;
import java.util.LinkedList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.RevokeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.UserIdGroupPair;
import com.msi.compute.helper.CreateSecurityGroupLocalHelper;
import com.msi.tough.core.Appctx;
public class RevokeSecurityGroupIngressTest extends AbstractBaseComputeTest {
private static Logger logger = Appctx
.getLogger(RevokeSecurityGroupIngressTest.class.getName());
private CreateSecurityGroupLocalHelper mHelper = null;
private String groupId = null;
@Before
public void setUp() throws Exception {
mHelper = new CreateSecurityGroupLocalHelper();
groupId = mHelper.createSecurityGroup();
logger.debug("Setting up the security group ingresses ");
AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest();
req.setGroupId(groupId);
Collection<IpPermission> ipPermissions = new LinkedList<IpPermission>();
IpPermission ip = new IpPermission();
ip.setFromPort(1010);
ip.setToPort(1010);
ip.setIpProtocol("tcp");
Collection<String> ranges = new LinkedList<String>();
ranges.add("1.2.3.4/16");
ip.setIpRanges(ranges);
ipPermissions.add(ip);
IpPermission ip2 = new IpPermission();
ip2.setFromPort(1012);
ip2.setToPort(1012);
ip2.setIpProtocol("tcp");
Collection<UserIdGroupPair> groups = new LinkedList<UserIdGroupPair>();
UserIdGroupPair group = new UserIdGroupPair();
group.setGroupName("default");
groups.add(group);
ip2.setUserIdGroupPairs(groups);
ipPermissions.add(ip2);
req.setIpPermissions(ipPermissions);
getComputeClientV2().authorizeSecurityGroupIngress(req);
logger.debug("Setting up the test resources completed!");
}
@After
public void cleanupCreated() throws Exception {
mHelper.deleteAllSecurityGroups();
mHelper = null;
}
@Test
public void testRevokeCidrIngress() {
logger.debug("testRevokeCidrIngress is to be tested.");
RevokeSecurityGroupIngressRequest req = new RevokeSecurityGroupIngressRequest();
req.setGroupId(groupId);
Collection<IpPermission> ipPermissions = new LinkedList<IpPermission>();
IpPermission ip = new IpPermission();
ip.setFromPort(1010);
ip.setToPort(1010);
ip.setIpProtocol("tcp");
Collection<String> ranges = new LinkedList<String>();
ranges.add("1.2.3.4/16");
ip.setIpRanges(ranges);
ipPermissions.add(ip);
req.setIpPermissions(ipPermissions);
getComputeClientV2().revokeSecurityGroupIngress(req);
logger.debug("testRevokeCidrIngress test completed!");
}
@Test
public void testRevokeGroupIngress() {
logger.debug("testRevokeGroupIngress is to be tested.");
RevokeSecurityGroupIngressRequest req = new RevokeSecurityGroupIngressRequest();
req.setGroupId(groupId);
Collection<IpPermission> ipPermissions = new LinkedList<IpPermission>();
IpPermission ip = new IpPermission();
ip.setFromPort(1012);
ip.setToPort(1012);
ip.setIpProtocol("tcp");
Collection<UserIdGroupPair> groups = new LinkedList<UserIdGroupPair>();
UserIdGroupPair group = new UserIdGroupPair();
group.setGroupName("default");
groups.add(group);
ip.setUserIdGroupPairs(groups);
ipPermissions.add(ip);
req.setIpPermissions(ipPermissions);
getComputeClientV2().revokeSecurityGroupIngress(req);
logger.debug("testRevokeGroupIngress test completed!");
}
}
| apache-2.0 |
gbehrmann/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/CertificateRevocationLists.java | 8134 | /*
* Copyright 1999-2010 University of Chicago
*
* 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.globus.gsi;
import org.globus.gsi.stores.ResourceCertStoreParameters;
import org.globus.gsi.stores.Stores;
import org.globus.gsi.provider.GlobusProvider;
import javax.security.auth.x500.X500Principal;
import java.security.cert.X509CRLSelector;
import java.security.cert.CertStore;
import java.security.cert.X509CRL;
import java.util.Map;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.io.File;
import org.globus.common.CoGProperties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// COMMENT: what should be used instead? Probably a cert-store. but that doesn't have a refresh or such
// COMMENT: We lost the functionality that stuff is only loaded when it didnt' exist or changed
/**
* @deprecated
*/
public class CertificateRevocationLists {
static {
new ProviderLoader();
}
private static Log logger =
LogFactory.getLog(CertificateRevocationLists.class.getName());
// the list of ca cert locations needed for getDefaultCRL call
private static String prevCaCertLocations = null;
// the default crl locations list derived from prevCaCertLocations
private static String defaultCrlLocations = null;
private static CertificateRevocationLists defaultCrl = null;
private volatile Map<String, X509CRL> crlIssuerDNMap;
private CertificateRevocationLists() {}
public X509CRL[] getCrls() {
if (this.crlIssuerDNMap == null) {
return null;
}
Collection crls = this.crlIssuerDNMap.values();
return (X509CRL[]) crls.toArray(new X509CRL[crls.size()]);
}
public Collection<X509CRL> getCRLs(X509CRLSelector selector) {
Collection<X500Principal> issuers = selector.getIssuers();
int size = issuers.size();
Collection<X509CRL> retval = new ArrayList<X509CRL>(size);
// Yup, this stinks. There's loss when we convert from principal to
// string. Hence, depending on weird encoding effects, we may miss
// some CRLs.
Map<String, X509CRL> crlMap = this.crlIssuerDNMap;
if (crlMap == null) return retval;
for (X500Principal principal : issuers) {
String dn = principal.getName();
X509CRL crl = crlMap.get(dn);
if (crl != null) {
retval.add(crl);
}
}
return retval;
}
public X509CRL getCrl(String issuerName) {
if (this.crlIssuerDNMap == null) {
return null;
}
return (X509CRL)this.crlIssuerDNMap.get(issuerName);
}
public void refresh() {
reload(null);
}
public synchronized void reload(String locations) {
if (locations == null) {
return;
}
StringTokenizer tokens = new StringTokenizer(locations, ",");
Map<String, X509CRL> newCrlIssuerDNMap = new HashMap<String, X509CRL>();
while(tokens.hasMoreTokens()) {
try {
String location = tokens.nextToken().toString().trim();
CertStore tmp = Stores.getCRLStore("file:" + location + "/*.r*");
Collection<X509CRL> coll = (Collection<X509CRL>) tmp.getCRLs(new X509CRLSelector());
for (X509CRL crl : coll) {
newCrlIssuerDNMap.put(crl.getIssuerX500Principal().getName(), crl);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
this.crlIssuerDNMap = newCrlIssuerDNMap;
}
public static CertificateRevocationLists
getCertificateRevocationLists(String locations) {
CertificateRevocationLists crl = new CertificateRevocationLists();
crl.reload(locations);
return crl;
}
public static synchronized
CertificateRevocationLists getDefaultCertificateRevocationLists() {
return getDefault();
}
public static void
setDefaultCertificateRevocationList(CertificateRevocationLists crl) {
defaultCrl = crl;
}
public static synchronized CertificateRevocationLists getDefault() {
if (defaultCrl == null) {
defaultCrl = new DefaultCertificateRevocationLists();
}
defaultCrl.refresh();
return defaultCrl;
}
public String toString() {
if (this.crlIssuerDNMap == null) {
return "crl list is empty";
} else {
return this.crlIssuerDNMap.toString();
}
}
private static class DefaultCertificateRevocationLists
extends CertificateRevocationLists {
private final long lifetime;
private long lastRefresh;
public DefaultCertificateRevocationLists() {
lifetime = CoGProperties.getDefault().getCRLCacheLifetime();
}
public void refresh() {
long now = System.currentTimeMillis();
if (lastRefresh + lifetime <= now) {
reload(getDefaultCRLLocations());
lastRefresh = now;
}
}
private static synchronized String getDefaultCRLLocations() {
String caCertLocations =
CoGProperties.getDefault().getCaCertLocations();
if (prevCaCertLocations == null ||
!prevCaCertLocations.equals(caCertLocations)) {
if (caCertLocations == null) {
logger.debug("No CA cert locations specified");
prevCaCertLocations = null;
defaultCrlLocations = null;
} else {
StringTokenizer tokens = new StringTokenizer(caCertLocations, ",");
File crlFile = null;
LinkedList crlDirs = new LinkedList();
while(tokens.hasMoreTokens()) {
String crlFileName =
tokens.nextToken().toString().trim();
crlFile = new File(crlFileName);
if (crlFile.isDirectory()) {
// all all directories
} else if (crlFile.isFile()) {
// add parent directory
crlFileName = crlFile.getParent();
} else {
// skip other types
continue;
}
// don't add directories twice
if (crlFileName != null &&
!crlDirs.contains(crlFileName)) {
crlDirs.add(crlFileName);
}
}
ListIterator iterator = crlDirs.listIterator(0);
String locations = null;
while (iterator.hasNext()) {
if (locations == null) {
locations = (String)iterator.next();
} else {
locations = locations + ","
+ (String)iterator.next();
}
}
// set defaults
prevCaCertLocations = caCertLocations;
defaultCrlLocations = locations;
}
}
return defaultCrlLocations;
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/ExperimentOperation.java | 50115 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/experiment_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* A single operation on an experiment.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.ExperimentOperation}
*/
public final class ExperimentOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.ExperimentOperation)
ExperimentOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use ExperimentOperation.newBuilder() to construct.
private ExperimentOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ExperimentOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ExperimentOperation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ExperimentOperation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v10.resources.Experiment.Builder subBuilder = null;
if (operationCase_ == 1) {
subBuilder = ((com.google.ads.googleads.v10.resources.Experiment) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.Experiment.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.Experiment) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 1;
break;
}
case 18: {
com.google.ads.googleads.v10.resources.Experiment.Builder subBuilder = null;
if (operationCase_ == 2) {
subBuilder = ((com.google.ads.googleads.v10.resources.Experiment) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.Experiment.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.Experiment) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 2;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
operationCase_ = 3;
operation_ = s;
break;
}
case 34: {
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.ExperimentServiceProto.internal_static_google_ads_googleads_v10_services_ExperimentOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.ExperimentServiceProto.internal_static_google_ads_googleads_v10_services_ExperimentOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.ExperimentOperation.class, com.google.ads.googleads.v10.services.ExperimentOperation.Builder.class);
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
CREATE(1),
UPDATE(2),
REMOVE(3),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 1: return CREATE;
case 2: return UPDATE;
case 3: return REMOVE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
public static final int CREATE_FIELD_NUMBER = 1;
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.Experiment getCreate() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.ExperimentOrBuilder getCreateOrBuilder() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.Experiment getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.ExperimentOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
public static final int REMOVE_FIELD_NUMBER = 3;
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the remove field is set.
*/
public boolean hasRemove() {
return operationCase_ == 3;
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The remove.
*/
public java.lang.String getRemove() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (operationCase_ == 3) {
operation_ = s;
}
return s;
}
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The bytes for remove.
*/
public com.google.protobuf.ByteString
getRemoveBytes() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
if (operationCase_ == 3) {
operation_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (operationCase_ == 1) {
output.writeMessage(1, (com.google.ads.googleads.v10.resources.Experiment) operation_);
}
if (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v10.resources.Experiment) operation_);
}
if (operationCase_ == 3) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, operation_);
}
if (updateMask_ != null) {
output.writeMessage(4, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, (com.google.ads.googleads.v10.resources.Experiment) operation_);
}
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v10.resources.Experiment) operation_);
}
if (operationCase_ == 3) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, operation_);
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.ExperimentOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.ExperimentOperation other = (com.google.ads.googleads.v10.services.ExperimentOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 1:
if (!getCreate()
.equals(other.getCreate())) return false;
break;
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 3:
if (!getRemove()
.equals(other.getRemove())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 1:
hash = (37 * hash) + CREATE_FIELD_NUMBER;
hash = (53 * hash) + getCreate().hashCode();
break;
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 3:
hash = (37 * hash) + REMOVE_FIELD_NUMBER;
hash = (53 * hash) + getRemove().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.ExperimentOperation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.ExperimentOperation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A single operation on an experiment.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.ExperimentOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.ExperimentOperation)
com.google.ads.googleads.v10.services.ExperimentOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.ExperimentServiceProto.internal_static_google_ads_googleads_v10_services_ExperimentOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.ExperimentServiceProto.internal_static_google_ads_googleads_v10_services_ExperimentOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.ExperimentOperation.class, com.google.ads.googleads.v10.services.ExperimentOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.ExperimentOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.ExperimentServiceProto.internal_static_google_ads_googleads_v10_services_ExperimentOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.ExperimentOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.ExperimentOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.ExperimentOperation build() {
com.google.ads.googleads.v10.services.ExperimentOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.ExperimentOperation buildPartial() {
com.google.ads.googleads.v10.services.ExperimentOperation result = new com.google.ads.googleads.v10.services.ExperimentOperation(this);
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
if (operationCase_ == 1) {
if (createBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = createBuilder_.build();
}
}
if (operationCase_ == 2) {
if (updateBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = updateBuilder_.build();
}
}
if (operationCase_ == 3) {
result.operation_ = operation_;
}
result.operationCase_ = operationCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.ExperimentOperation) {
return mergeFrom((com.google.ads.googleads.v10.services.ExperimentOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.ExperimentOperation other) {
if (other == com.google.ads.googleads.v10.services.ExperimentOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case CREATE: {
mergeCreate(other.getCreate());
break;
}
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case REMOVE: {
operationCase_ = 3;
operation_ = other.operation_;
onChanged();
break;
}
case OPERATION_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.ExperimentOperation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.ExperimentOperation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(),
getParentForChildren(),
isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder> createBuilder_;
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.Experiment getCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
} else {
if (operationCase_ == 1) {
return createBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
public Builder setCreate(com.google.ads.googleads.v10.resources.Experiment value) {
if (createBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
public Builder setCreate(
com.google.ads.googleads.v10.resources.Experiment.Builder builderForValue) {
if (createBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
createBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
public Builder mergeCreate(com.google.ads.googleads.v10.resources.Experiment value) {
if (createBuilder_ == null) {
if (operationCase_ == 1 &&
operation_ != com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.Experiment.newBuilder((com.google.ads.googleads.v10.resources.Experiment) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 1) {
createBuilder_.mergeFrom(value);
}
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
public Builder clearCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
}
createBuilder_.clear();
}
return this;
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
public com.google.ads.googleads.v10.resources.Experiment.Builder getCreateBuilder() {
return getCreateFieldBuilder().getBuilder();
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.ExperimentOrBuilder getCreateOrBuilder() {
if ((operationCase_ == 1) && (createBuilder_ != null)) {
return createBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
}
/**
* <pre>
* Create operation
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment create = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder>
getCreateFieldBuilder() {
if (createBuilder_ == null) {
if (!(operationCase_ == 1)) {
operation_ = com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder>(
(com.google.ads.googleads.v10.resources.Experiment) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 1;
onChanged();;
return createBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.Experiment getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v10.resources.Experiment value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v10.resources.Experiment.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v10.resources.Experiment value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.Experiment.newBuilder((com.google.ads.googleads.v10.resources.Experiment) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
}
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
public com.google.ads.googleads.v10.resources.Experiment.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.ExperimentOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.Experiment) operation_;
}
return com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The experiment is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.Experiment update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v10.resources.Experiment.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.Experiment, com.google.ads.googleads.v10.resources.Experiment.Builder, com.google.ads.googleads.v10.resources.ExperimentOrBuilder>(
(com.google.ads.googleads.v10.resources.Experiment) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();;
return updateBuilder_;
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the remove field is set.
*/
@java.lang.Override
public boolean hasRemove() {
return operationCase_ == 3;
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The remove.
*/
@java.lang.Override
public java.lang.String getRemove() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (operationCase_ == 3) {
operation_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return The bytes for remove.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getRemoveBytes() {
java.lang.Object ref = "";
if (operationCase_ == 3) {
ref = operation_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
if (operationCase_ == 3) {
operation_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @param value The remove to set.
* @return This builder for chaining.
*/
public Builder setRemove(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
operationCase_ = 3;
operation_ = value;
onChanged();
return this;
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearRemove() {
if (operationCase_ == 3) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
return this;
}
/**
* <pre>
* Remove operation: The experiment is expected to have a valid
* resource name, in this format:
* `customers/{customer_id}/experiments/{campaign_experiment_id}`
* </pre>
*
* <code>string remove = 3 [(.google.api.resource_reference) = { ... }</code>
* @param value The bytes for remove to set.
* @return This builder for chaining.
*/
public Builder setRemoveBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
operationCase_ = 3;
operation_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.ExperimentOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.ExperimentOperation)
private static final com.google.ads.googleads.v10.services.ExperimentOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.ExperimentOperation();
}
public static com.google.ads.googleads.v10.services.ExperimentOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ExperimentOperation>
PARSER = new com.google.protobuf.AbstractParser<ExperimentOperation>() {
@java.lang.Override
public ExperimentOperation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ExperimentOperation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ExperimentOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ExperimentOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.ExperimentOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
krraghavan/mongodb-aggregate-query-support | mongodb-aggregate-query-support-core/src/main/java/com/github/krr/mongodb/aggregate/support/annotations/Unwind.java | 1205 | /*
* Copyright (c) 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 com.github.krr.mongodb.aggregate.support.annotations;
import java.lang.annotation.*;
/**
* Created by rkolliva on 10/9/2015.
* A pipeline step in an aggregate query. See {@link Aggregate} for further details
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Repeatable(Unwinds.class)
public @interface Unwind {
String query();
int order();
Conditional[] condition() default {};
Conditional.ConditionalMatchType conditionMatchType() default Conditional.ConditionalMatchType.ANY;
}
| apache-2.0 |
evandor/skysail | skysail.server.app.pact/src/io/skysail/server/app/pact/PactApplication.java | 3097 | package io.skysail.server.app.pact;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Reference;
import io.skysail.core.app.ApiVersion;
import io.skysail.core.app.ApplicationConfiguration;
import io.skysail.core.app.ApplicationProvider;
import io.skysail.core.app.SkysailApplication;
import io.skysail.server.app.pact.resources.ConfirmationsResource;
import io.skysail.server.app.pact.resources.PostConfirmationResource;
import io.skysail.server.db.DbService;
import io.skysail.server.menus.MenuItemProvider;
import io.skysail.server.restlet.RouteBuilder;
import io.skysail.server.security.config.SecurityConfigBuilder;
import lombok.Getter;
@Component(immediate = true, configurationPolicy = ConfigurationPolicy.OPTIONAL)
public class PactApplication extends SkysailApplication implements ApplicationProvider, MenuItemProvider {
public static final String LIST_ID = "lid";
public static final String TODO_ID = "id";
public static final String APP_NAME = "pact";
@Reference
private DbService dbService;
@Getter
private PactRepository repo;
@Getter
private ConfirmationRepository confRepo;
public PactApplication() {
super(APP_NAME, new ApiVersion(1));
setDescription("Pact Backend (WYT)");
}
@Activate
@Override
public void activate(ApplicationConfiguration appConfig, ComponentContext componentContext)
throws ConfigurationException {
super.activate(appConfig, componentContext);
this.repo = new PactRepository(dbService);
this.confRepo = new ConfirmationRepository(dbService);
}
@Override
protected void defineSecurityConfig(SecurityConfigBuilder securityConfigBuilder) {
securityConfigBuilder
.authorizeRequests().equalsMatcher("/Bookmarks/").permitAll().and()
.authorizeRequests().startsWithMatcher("/unprotected").permitAll().and()
.authorizeRequests().startsWithMatcher("").permitAll();
// .authorizeRequests().startsWithMatcher("").authenticated();
}
@Override
protected void attach() {
super.attach();
router.attach(new RouteBuilder("", PactResource.class));
router.attach(new RouteBuilder("/pacts", PactsResource.class));
router.attach(new RouteBuilder("/pacts/", PostPactResource.class));
router.attach(new RouteBuilder("/pacts/{id}", PactResource.class));
router.attach(new RouteBuilder("/pact/", PutPactResource.class));
router.attach(new RouteBuilder("/pact", PactResource.class));
router.attach(new RouteBuilder("/turn", NextCandiateResource.class));
router.attach(new RouteBuilder("/confirmations/", PostConfirmationResource.class));
router.attach(new RouteBuilder("/confirmations", ConfirmationsResource.class));
}
} | apache-2.0 |
pedronveloso/AveiroWSProjCompleto | src/com/enei/workshopandroid/network/NetworkCalls.java | 1146 | package com.enei.workshopandroid.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public final class NetworkCalls {
/**
* @return the content of HTTP request if it succeeded, null otherwise
*/
public static String httpGet(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
// fetch result stream
InputStream is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String response = "", data = "";
while ((data = reader.readLine()) != null) {
response += data + "\n";
}
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
jruyi/jruyi | io/src/main/java/org/jruyi/io/channel/IChannelAdmin.java | 710 | /*
* 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.jruyi.io.channel;
public interface IChannelAdmin {
ISelector designateSelector(int id);
ISelector designateSelector(Object id);
}
| apache-2.0 |
grpc/grpc-java | rls/src/test/java/io/grpc/rls/RlsRequestFactoryTest.java | 6449 | /*
* Copyright 2020 The gRPC 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 io.grpc.rls;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.grpc.Metadata;
import io.grpc.rls.RlsProtoData.ExtraKeys;
import io.grpc.rls.RlsProtoData.GrpcKeyBuilder;
import io.grpc.rls.RlsProtoData.GrpcKeyBuilder.Name;
import io.grpc.rls.RlsProtoData.NameMatcher;
import io.grpc.rls.RlsProtoData.RouteLookupConfig;
import io.grpc.rls.RlsProtoData.RouteLookupRequest;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class RlsRequestFactoryTest {
private static final RouteLookupConfig RLS_CONFIG =
RouteLookupConfig.builder()
.grpcKeyBuilders(ImmutableList.of(
GrpcKeyBuilder.create(
ImmutableList.of(Name.create("com.google.service1", "Create")),
ImmutableList.of(
NameMatcher.create("user", ImmutableList.of("User", "Parent")),
NameMatcher.create("id", ImmutableList.of("X-Google-Id"))),
ExtraKeys.create("server-1", null, null),
ImmutableMap.of("const-key-1", "const-value-1")),
GrpcKeyBuilder.create(
ImmutableList.of(Name.create("com.google.service1", "*")),
ImmutableList.of(
NameMatcher.create("user", ImmutableList.of("User", "Parent")),
NameMatcher.create("password", ImmutableList.of("Password"))),
ExtraKeys.create(null, "service-2", null),
ImmutableMap.of("const-key-2", "const-value-2")),
GrpcKeyBuilder.create(
ImmutableList.of(Name.create("com.google.service2", "*")),
ImmutableList.of(
NameMatcher.create("password", ImmutableList.of("Password"))),
ExtraKeys.create(null, "service-3", "method-3"),
ImmutableMap.<String, String>of()),
GrpcKeyBuilder.create(
ImmutableList.of(Name.create("com.google.service3", "*")),
ImmutableList.of(
NameMatcher.create("user", ImmutableList.of("User", "Parent"))),
ExtraKeys.create(null, null, null),
ImmutableMap.of("const-key-4", "const-value-4"))))
.lookupService("bigtable-rls.googleapis.com")
.lookupServiceTimeoutInNanos(TimeUnit.SECONDS.toNanos(2))
.maxAgeInNanos(TimeUnit.SECONDS.toNanos(300))
.staleAgeInNanos(TimeUnit.SECONDS.toNanos(240))
.cacheSizeBytes(1000)
.defaultTarget("us_east_1.cloudbigtable.googleapis.com")
.build();
private final RlsRequestFactory factory = new RlsRequestFactory(
RLS_CONFIG, "bigtable.googleapis.com");
@Test
public void create_pathMatches() {
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("User", Metadata.ASCII_STRING_MARSHALLER), "test");
metadata.put(Metadata.Key.of("X-Google-Id", Metadata.ASCII_STRING_MARSHALLER), "123");
metadata.put(Metadata.Key.of("foo", Metadata.ASCII_STRING_MARSHALLER), "bar");
RouteLookupRequest request = factory.create("com.google.service1", "Create", metadata);
assertThat(request.keyMap()).containsExactly(
"user", "test",
"id", "123",
"server-1", "bigtable.googleapis.com",
"const-key-1", "const-value-1");
}
@Test
public void create_pathFallbackMatches() {
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("Parent", Metadata.ASCII_STRING_MARSHALLER), "test");
metadata.put(Metadata.Key.of("Password", Metadata.ASCII_STRING_MARSHALLER), "hunter2");
metadata.put(Metadata.Key.of("foo", Metadata.ASCII_STRING_MARSHALLER), "bar");
RouteLookupRequest request = factory.create("com.google.service1" , "Update", metadata);
assertThat(request.keyMap()).containsExactly(
"user", "test",
"password", "hunter2",
"service-2", "com.google.service1",
"const-key-2", "const-value-2");
}
@Test
public void create_pathFallbackMatches_optionalHeaderMissing() {
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("User", Metadata.ASCII_STRING_MARSHALLER), "test");
metadata.put(Metadata.Key.of("X-Google-Id", Metadata.ASCII_STRING_MARSHALLER), "123");
metadata.put(Metadata.Key.of("foo", Metadata.ASCII_STRING_MARSHALLER), "bar");
RouteLookupRequest request = factory.create("com.google.service1", "Update", metadata);
assertThat(request.keyMap()).containsExactly(
"user", "test",
"service-2", "com.google.service1",
"const-key-2", "const-value-2");
}
@Test
public void create_unknownPath() {
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("User", Metadata.ASCII_STRING_MARSHALLER), "test");
metadata.put(Metadata.Key.of("X-Google-Id", Metadata.ASCII_STRING_MARSHALLER), "123");
metadata.put(Metadata.Key.of("foo", Metadata.ASCII_STRING_MARSHALLER), "bar");
RouteLookupRequest request = factory.create("abc.def.service999", "Update", metadata);
assertThat(request.keyMap()).isEmpty();
}
@Test
public void create_noMethodInRlsConfig() {
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("User", Metadata.ASCII_STRING_MARSHALLER), "test");
metadata.put(Metadata.Key.of("X-Google-Id", Metadata.ASCII_STRING_MARSHALLER), "123");
metadata.put(Metadata.Key.of("foo", Metadata.ASCII_STRING_MARSHALLER), "bar");
RouteLookupRequest request = factory.create("com.google.service3", "Update", metadata);
assertThat(request.keyMap()).containsExactly(
"user", "test", "const-key-4", "const-value-4");
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-sqlserver | src/main/java/org/docksidestage/sqlserver/dbflute/bsbhv/loader/LoaderOfVendorCheck.java | 2693 | package org.docksidestage.sqlserver.dbflute.bsbhv.loader;
import java.util.List;
import org.dbflute.bhv.*;
import org.docksidestage.sqlserver.dbflute.exbhv.*;
import org.docksidestage.sqlserver.dbflute.exentity.*;
/**
* The referrer loader of VENDOR_CHECK as TABLE. <br>
* <pre>
* [primary key]
* VENDOR_CHECK_ID
*
* [column]
* VENDOR_CHECK_ID, TYPE_OF_VARCHAR, TYPE_OF_NVARCHAR, TYPE_OF_TEXT, TYPE_OF_NUMERIC_DECIMAL, TYPE_OF_NUMERIC_INTEGER, TYPE_OF_NUMERIC_BIGINT, TYPE_OF_SMALLINTEGER, TYPE_OF_INTEGER, TYPE_OF_BIGINT, TYPE_OF_MONEY, TYPE_OF_SMALLMONEY, TYPE_OF_DATETIME, TYPE_OF_SMALLDATETIME, TYPE_OF_BIT, TYPE_OF_BINARY, TYPE_OF_VARBINARY, TYPE_OF_UNIQUEIDENTIFIER, TYPE_OF_XML
*
* [sequence]
*
*
* [identity]
*
*
* [version-no]
*
*
* [foreign table]
*
*
* [referrer table]
*
*
* [foreign property]
*
*
* [referrer property]
*
* </pre>
* @author DBFlute(AutoGenerator)
*/
public class LoaderOfVendorCheck {
// ===================================================================================
// Attribute
// =========
protected List<VendorCheck> _selectedList;
protected BehaviorSelector _selector;
protected VendorCheckBhv _myBhv; // lazy-loaded
// ===================================================================================
// Ready for Loading
// =================
public LoaderOfVendorCheck ready(List<VendorCheck> selectedList, BehaviorSelector selector)
{ _selectedList = selectedList; _selector = selector; return this; }
protected VendorCheckBhv myBhv()
{ if (_myBhv != null) { return _myBhv; } else { _myBhv = _selector.select(VendorCheckBhv.class); return _myBhv; } }
// ===================================================================================
// Pull out Foreign
// ================
// ===================================================================================
// Accessor
// ========
public List<VendorCheck> getSelectedList() { return _selectedList; }
public BehaviorSelector getSelector() { return _selector; }
}
| apache-2.0 |
equella/Equella | autotest/Tests/src/main/java/com/tle/webtests/framework/StandardDriverFactory.java | 7550 | package com.tle.webtests.framework;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.collect.Maps;
import com.tle.common.Check;
import com.tle.webtests.pageobject.AbstractPage;
import com.tle.webtests.pageobject.DownloadFilePage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.codehaus.jackson.map.ObjectMapper;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.*;
public class StandardDriverFactory {
private final String firefoxBinary;
private final String chromeBinary;
private final boolean chrome;
private final String gridUrl;
private final boolean firefoxHeadless;
private final boolean chromeHeadless;
private Proxy proxy;
private static ChromeDriverService _chromeService;
public StandardDriverFactory(TestConfig config) {
this.chrome = config.isChromeDriverSet();
this.chromeBinary = config.getChromeBinary();
this.firefoxBinary = config.getFirefoxBinary();
this.gridUrl = config.getGridUrl();
this.firefoxHeadless = config.getBooleanProperty("webdriver.firefox.headless", false);
this.chromeHeadless = config.getBooleanProperty("webdriver.chrome.headless", false);
String proxyHost = config.getProperty("proxy.host");
if (proxyHost != null) {
int port = Integer.parseInt(config.getProperty("proxy.port"));
proxy = new Proxy();
String proxyHostPort = proxyHost + ":" + port;
proxy.setHttpProxy(proxyHostPort);
proxy.setSslProxy(proxyHostPort);
}
}
private static synchronized ChromeDriverService getChromeService() throws IOException {
if (_chromeService == null) {
_chromeService = ChromeDriverService.createDefaultService();
_chromeService.start();
}
return _chromeService;
}
private void setFirefoxPreferences(FirefoxProfile profile, String downDir) {
profile.setPreference("dom.max_script_run_time", 120);
profile.setPreference("dom.max_chrome_script_run_time", 120);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", downDir);
profile.setPreference("extensions.firebug.currentVersion", "999");
profile.setPreference(
"browser.helperApps.neverAsk.saveToDisk", "application/zip,image/png,text/xml");
profile.setPreference("security.mixed_content.block_active_content", false);
profile.setPreference("security.mixed_content.block_display_content", false);
}
public WebDriver getDriver(Class<?> clazz) throws IOException {
WebDriver driver;
String downDir = DownloadFilePage.getDownDir().getAbsolutePath();
if (!Check.isEmpty(gridUrl) && !clazz.isAnnotationPresent(LocalWebDriver.class)) {
FirefoxProfile profile = new FirefoxProfile();
setFirefoxPreferences(profile, downDir);
profile.addExtension(
new File(
AbstractPage.getPathFromUrl(
StandardDriverPool.class.getResource("firebug-1.10.2-fx.xpi"))));
profile.addExtension(
new File(
AbstractPage.getPathFromUrl(
StandardDriverPool.class.getResource("firepath-0.9.7-fx.xpi"))));
FirefoxOptions options = new FirefoxOptions().setProfile(profile);
if (firefoxHeadless) {
options.addArguments("-headless");
}
driver = new RemoteWebDriver(new URL(gridUrl), options);
RemoteWebDriver rd = (RemoteWebDriver) driver;
rd.setFileDetector(new LocalFileDetector());
driver = new Augmenter().augment(driver);
} else {
if (chrome) {
DesiredCapabilities capabilities = new DesiredCapabilities();
ChromeOptions options = new ChromeOptions();
if (chromeBinary != null) {
options.setBinary(chromeBinary);
}
options.addArguments("test-type");
options.addArguments("disable-gpu");
options.addArguments("no-sandbox");
if (chromeHeadless) {
options.addArguments("headless");
options.addArguments("--lang=en-US");
}
options.addArguments("window-size=1200,800");
Map<String, Object> prefs = Maps.newHashMap();
prefs.put("intl.accept_languages", "en-US");
prefs.put("download.default_directory", downDir);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
if (proxy != null) {
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
RemoteWebDriver rdriver = new RemoteWebDriver(getChromeService().getUrl(), capabilities);
driver = new Augmenter().augment(rdriver);
if (chromeHeadless) {
enableHeadlessDownloads(rdriver, downDir);
}
} else {
FirefoxBinary binary;
if (firefoxBinary != null) {
binary = new FirefoxBinary(new File(firefoxBinary));
} else {
binary = new FirefoxBinary();
}
binary.setTimeout(SECONDS.toMillis(120));
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(getClass(), "firebug-1.10.2-fx.xpi");
profile.addExtension(getClass(), "firepath-0.9.7-fx.xpi");
setFirefoxPreferences(profile, downDir);
FirefoxOptions options = new FirefoxOptions();
if (firefoxHeadless) {
options.addArguments("-headless");
}
options.setCapability("moz:webdriverClick", false);
if (proxy != null) {
options.setCapability(CapabilityType.PROXY, proxy);
}
options.setBinary(binary);
options.setProfile(profile);
driver = new FirefoxDriver(options);
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.MINUTES);
}
}
return driver;
}
private void enableHeadlessDownloads(RemoteWebDriver cdriver, String downDir) throws IOException {
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", downDir);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u =
getChromeService().getUrl().toString()
+ "/session/"
+ cdriver.getSessionId()
+ "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
try {
httpClient.execute(request).getEntity().getContent().close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
| apache-2.0 |
bencaldwell/automatalib | serialization/taf/src/main/java/net/automatalib/serialization/taf/TAFSerialization.java | 3021 | /* Copyright (C) 2015 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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.automatalib.serialization.taf;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import net.automatalib.automata.fsa.DFA;
import net.automatalib.automata.fsa.NFA;
import net.automatalib.automata.fsa.impl.compact.CompactDFA;
import net.automatalib.automata.fsa.impl.compact.CompactNFA;
import net.automatalib.serialization.SerializationProvider;
import net.automatalib.serialization.taf.parser.PrintStreamDiagnosticListener;
import net.automatalib.serialization.taf.parser.TAFParser;
import net.automatalib.serialization.taf.writer.TAFWriter;
import net.automatalib.util.automata.copy.AutomatonCopyMethod;
import net.automatalib.util.automata.copy.AutomatonLowLevelCopy;
import net.automatalib.words.Alphabet;
import net.automatalib.words.impl.Alphabets;
public class TAFSerialization implements SerializationProvider {
private static TAFSerialization INSTANCE = new TAFSerialization();
public static TAFSerialization getInstance() {
return INSTANCE;
}
private TAFSerialization() {
}
@Override
public CompactDFA<Integer> readGenericDFA(InputStream is)
throws IOException {
CompactDFA<String> nativeDfa = readNativeDFA(is);
return normalize(nativeDfa, nativeDfa.getInputAlphabet());
}
@Override
public CompactDFA<String> readNativeDFA(InputStream is) {
return TAFParser.parseDFA(is, PrintStreamDiagnosticListener.getStderrDiagnosticListener());
}
@Override
public <I> void writeDFA(DFA<?, I> dfa, Alphabet<I> alphabet,
OutputStream os) throws IOException {
TAFWriter.writeDFA(dfa, alphabet, new OutputStreamWriter(os));
}
@Override
public CompactNFA<Integer> readGenericNFA(InputStream is)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public <I> void writeNFA(NFA<?, I> nfa, Alphabet<I> alphabet,
OutputStream os) throws IOException {
throw new UnsupportedOperationException();
}
private static <I> CompactDFA<Integer> normalize(DFA<?,I> dfa, Alphabet<I> alphabet) {
Alphabet<Integer> normalizedAlphabet = Alphabets.integers(0, alphabet.size() - 1);
CompactDFA<Integer> result = new CompactDFA<>(normalizedAlphabet, dfa.size());
AutomatonLowLevelCopy.copy(AutomatonCopyMethod.STATE_BY_STATE, dfa, alphabet, result,
i -> alphabet.getSymbolIndex(i));
return result;
}
}
| apache-2.0 |
stain/moxo | dav/src/main/java/com/thinkberg/moxo/dav/MoveHandler.java | 1210 | /*
* Copyright 2007 Matthias L. Jugel.
*
* 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.thinkberg.moxo.dav;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import com.thinkberg.moxo.vfs.extensions.DepthFileSelector;
/**
* @author Matthias L. Jugel
* @version $Id$
*/
public class MoveHandler extends CopyMoveBase {
protected void copyOrMove(FileObject object, FileObject target, int depth)
throws FileSystemException {
try {
object.moveTo(target);
} catch (FileSystemException ex) {
ex.printStackTrace();
target.copyFrom(object, new DepthFileSelector(depth));
object.delete(new DepthFileSelector());
}
}
}
| apache-2.0 |
rbible/one-nio | src/one/nio/http/HttpSession.java | 4828 | /*
* Copyright 2015 Odnoklassniki Ltd, Mail.Ru Group
*
* 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 one.nio.http;
import one.nio.net.Session;
import one.nio.net.Socket;
import one.nio.util.Utf8;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
public class HttpSession extends Session {
private static final Log log = LogFactory.getLog(HttpSession.class);
private static final int MAX_HEADERS = 32;
private static final int MAX_FRAGMENT_LENGTH = 2048;
protected final HttpServer server;
private byte[] fragment;
private int fragmentLength;
private Request request;
public HttpSession(Socket socket, HttpServer server) {
super(socket);
this.server = server;
this.fragment = new byte[MAX_FRAGMENT_LENGTH];
}
@Override
protected void processRead(byte[] buffer) throws IOException {
int length = fragmentLength;
if (length > 0) {
System.arraycopy(fragment, 0, buffer, 0, length);
}
length += super.read(buffer, length, buffer.length - length);
try {
int processed = processHttpBuffer(buffer, length);
length -= processed;
if (length > 0) {
if (length > MAX_FRAGMENT_LENGTH) {
throw new HttpException("Line too long");
}
System.arraycopy(buffer, processed, fragment, 0, length);
}
fragmentLength = length;
} catch (HttpException e) {
if (log.isDebugEnabled()) {
log.debug("Bad request", e);
}
writeError(Response.BAD_REQUEST, e.getMessage());
}
}
private int processHttpBuffer(byte[] buffer, int length) throws IOException, HttpException {
int lineStart = 0;
for (int i = 1; i < length; i++) {
if (buffer[i] == '\n') {
int lineLength = i - lineStart - (buffer[i - 1] == '\r' ? 1 : 0);
if (request == null) {
request = parseRequest(buffer, lineStart, lineLength);
} else if (lineLength > 0) {
request.addHeader(Utf8.read(buffer, lineStart, lineLength));
} else {
server.handleRequest(request, this);
request = null;
}
lineStart = i + 1;
}
}
return lineStart;
}
protected Request parseRequest(byte[] buffer, int start, int length) throws HttpException {
if (length > 13 && Utf8.startsWith(Request.VERB_GET, buffer, start)) {
return new Request(Request.METHOD_GET, Utf8.read(buffer, start + 4, length - 13), MAX_HEADERS);
} else if (length > 14 && Utf8.startsWith(Request.VERB_POST, buffer, start)) {
return new Request(Request.METHOD_POST, Utf8.read(buffer, start + 5, length - 14), MAX_HEADERS);
} else if (length > 14 && Utf8.startsWith(Request.VERB_HEAD, buffer, start)) {
return new Request(Request.METHOD_HEAD, Utf8.read(buffer, start + 5, length - 14), MAX_HEADERS);
} else if (length > 17 && Utf8.startsWith(Request.VERB_OPTIONS, buffer, start)) {
return new Request(Request.METHOD_OPTIONS, Utf8.read(buffer, start + 8, length - 17), MAX_HEADERS);
}
throw new HttpException("Invalid request");
}
public void writeResponse(Request request, Response response) throws IOException {
server.incRequestsProcessed();
boolean close = "close".equalsIgnoreCase(request.getHeader("Connection: "));
response.addHeader(close ? "Connection: close" : "Connection: Keep-Alive");
byte[] bytes = response.toBytes(request.getMethod() != Request.METHOD_HEAD);
super.write(bytes, 0, bytes.length);
if (close) scheduleClose();
}
public void writeError(String code, String message) throws IOException {
server.incRequestsRejected();
Response response = new Response(code, message == null ? Response.EMPTY : Utf8.toBytes(message));
response.addHeader("Connection: close");
byte[] bytes = response.toBytes(true);
super.write(bytes, 0, bytes.length);
scheduleClose();
}
}
| apache-2.0 |
SecureCodingTeam7/Phase3 | java/SmartCardSim/src/scs/Controller.java | 6153 | package scs;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Label statusLabel;
@FXML
private TextField destinationTextField;
@FXML
private TextField pinTextField;
@FXML
private TextField amountTextField;
@FXML
private Label fileLabel;
@FXML
private Button copyTANButton;
@FXML
private TabPane tabPane;
private String tan;
private File file;
@Override
public void initialize(URL location, ResourceBundle resources) {
statusLabel.setVisible(false);
copyTANButton.setVisible(false);
tabPane.getStyleClass().add("floating");
}
@FXML
private void copyTANClicked(ActionEvent event) {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
content.putString(tan);
clipboard.setContent(content);
}
@FXML
private void searchClicked(ActionEvent event) {
FileChooser chooser = new FileChooser();
file = chooser.showOpenDialog(statusLabel.getScene().getWindow());
fileLabel.setText("File: " + file.getName());
}
@FXML
private void generateTANClicked(ActionEvent event) {
statusLabel.setVisible(false);
copyTANButton.setVisible(false);
if(!validateInputs()) {
return;
}
String destination = null;
String amount = null;
if(tabPane.getSelectionModel().getSelectedIndex() == 0) {
destination = destinationTextField.getText();
amount = amountTextField.getText();
} else {
FileParser parser = new FileParser(file);
try {
parser.parse();
destination = parser.getDestination();
amount = parser.getAmount();
if(destination == null || amount == null) {
setNegativeStatus("Destination or amount missing in file!");
return;
}
if(!validateInputs(destination, amount)) {
return;
}
} catch (IOException e) {
e.printStackTrace();
setNegativeStatus("Cannot read from file!");
return;
}
}
generateTAN(destination, amount);
}
private void generateTAN(String destination, String amount) {
String pin = pinTextField.getText();
long time;
try {
time = NetworkTime.getTime();
} catch (IOException ex) {
ex.printStackTrace();
setNegativeStatus("Could not reach time server!");
return;
}
long seed = time - time % (1 * 60);
MessageDigest md5Digest;
try {
md5Digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// this should normally not happen!
e.printStackTrace();
setNegativeStatus("Could not get md5 digest!");
return;
}
byte[] md5 = md5Digest.digest((seed + pin + destination + amount + seed).getBytes());
StringBuffer stringBuffer = new StringBuffer();
for(byte b : md5) {
stringBuffer.append(Math.abs(b));
}
tan = stringBuffer.toString().substring(0, 15);
setPositiveStatus("Your TAN: " + tan);
}
private boolean validateInputs() {
String pin = pinTextField.getText();
String destination = destinationTextField.getText();
String amount = amountTextField.getText();
if(pin.length() != 6) {
setNegativeStatus("PIN must have exactly six digits!");
return false;
}
if(!pin.matches("[0-9]+")) {
setNegativeStatus("PIN must contain only digits!");
return false;
}
// If we are using a batch file just test the file
if(tabPane.getSelectionModel().getSelectedIndex() == 1) {
setNegativeStatus("Please specify a file!");
return file != null;
}
return validateInputs(destination, amount);
}
private boolean validateInputs(String destination, String amount) {
if(destination.isEmpty() || amount.isEmpty()) {
setNegativeStatus("Please fill in all fields!");
return false;
}
if(destination.length() != 10) {
setNegativeStatus("Destination must have exactly ten digits!");
return false;
}
if(!destination.matches("[0-9]+")) {
setNegativeStatus("Destination must contain only digits!");
return false;
}
if(!amount.matches("[0-9]+(\\.\\d{1,2})?")) {
setNegativeStatus("Amount must be a valid amount!");
return false;
}
return true;
}
private void setNegativeStatus(String errorMessage) {
statusLabel.setTextFill(Color.FIREBRICK);
statusLabel.setText(errorMessage);
statusLabel.setVisible(true);
copyTANButton.setVisible(false);
}
private void setPositiveStatus(String message) {
statusLabel.setTextFill(Color.GREEN);
statusLabel.setText(message);
statusLabel.setVisible(true);
copyTANButton.setVisible(true);
}
}
| apache-2.0 |
Activiti/Activiti | activiti-core/activiti-spring-boot-starter/src/test/java/org/activiti/spring/boot/tasks/TaskRuntimeAppVersionIT.java | 2234 | /*
* Copyright 2010-2020 Alfresco Software, 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.activiti.spring.boot.tasks;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.spring.boot.security.util.SecurityUtil;
import org.activiti.spring.boot.test.util.TaskCleanUpUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class TaskRuntimeAppVersionIT {
@Autowired
private TaskRuntime taskRuntime;
@Autowired
private SecurityUtil securityUtil;
@Autowired
private TaskCleanUpUtil taskCleanUpUtil;
@AfterEach
public void taskCleanUp() {
taskCleanUpUtil.cleanUpWithAdmin();
}
@Test
public void should_standaloneTaskAlwaysHaveAppVersion() {
securityUtil.logInAs("user");
taskRuntime.create(TaskPayloadBuilder.create()
.withName("new task")
.build());
Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 50));
assertThat(tasks.getContent()).hasSize(1);
Task result = tasks.getContent().get(0);
assertThat(result.getName()).isEqualTo("new task");
assertThat(result.getAppVersion()).isEqualTo("1");
}
}
| apache-2.0 |
rhencke/buck | src/com/facebook/buck/cli/TestCommand.java | 23321 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.command.Build;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.json.BuildFileParseException;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetException;
import com.facebook.buck.model.Pair;
import com.facebook.buck.parser.BuildFileSpec;
import com.facebook.buck.parser.TargetNodePredicateSpec;
import com.facebook.buck.rules.ActionGraph;
import com.facebook.buck.rules.BuildEngine;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CachingBuildEngine;
import com.facebook.buck.rules.ExternalTestRunnerRule;
import com.facebook.buck.rules.ExternalTestRunnerTestSpec;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetGraphToActionGraph;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.TargetNodes;
import com.facebook.buck.rules.TestRule;
import com.facebook.buck.step.AdbOptions;
import com.facebook.buck.step.DefaultStepRunner;
import com.facebook.buck.step.TargetDevice;
import com.facebook.buck.step.TargetDeviceOptions;
import com.facebook.buck.test.CoverageReportFormat;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.ListeningProcessExecutor;
import com.facebook.buck.util.MoreExceptions;
import com.facebook.buck.util.ProcessExecutorParams;
import com.facebook.buck.util.concurrent.ConcurrencyLimit;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.kohsuke.args4j.Option;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
public class TestCommand extends BuildCommand {
public static final String USE_RESULTS_CACHE = "use_results_cache";
private static final Logger LOG = Logger.get(TestCommand.class);
@Option(name = "--all",
usage =
"Whether all of the tests should be run. " +
"If no targets are given, --all is implied")
private boolean all = false;
@Option(name = "--code-coverage", usage = "Whether code coverage information will be generated.")
private boolean isCodeCoverageEnabled = false;
@Option(name = "--code-coverage-format", usage = "Format to be used for coverage")
private CoverageReportFormat coverageReportFormat = CoverageReportFormat.HTML;
@Option(name = "--code-coverage-title", usage = "Title used for coverage")
private String coverageReportTitle = "Code-Coverage Analysis";
@Option(name = "--debug",
usage = "Whether the test will start suspended with a JDWP debug port of 5005")
private boolean isDebugEnabled = false;
@Option(name = "--xml", usage = "Where to write test output as XML.")
@Nullable
private String pathToXmlTestOutput = null;
@Option(name = "--run-with-java-agent",
usage = "Whether the test will start a java profiling agent")
@Nullable
private String pathToJavaAgent = null;
@Option(name = "--no-results-cache", usage = "Whether to use cached test results.")
@Nullable
private Boolean isResultsCacheDisabled = null;
@Option(name = "--build-filtered", usage = "Whether to build filtered out tests.")
@Nullable
private Boolean isBuildFiltered = null;
// TODO(#9061229): See if we can remove this option entirely. For now, the
// underlying code has been removed, and this option is ignored.
@Option(
name = "--ignore-when-dependencies-fail",
aliases = {"-i"},
usage =
"Deprecated option (ignored).",
hidden = true)
@SuppressWarnings("PMD.UnusedPrivateField")
private boolean isIgnoreFailingDependencies;
@Option(
name = "--dry-run",
usage = "Print tests that match the given command line options, but don't run them.")
private boolean isDryRun;
@Option(
name = "--one-time-output",
usage =
"Put test-results in a unique, one-time output directory. " +
"This allows multiple tests to be run in parallel without interfering with each other, " +
"but at the expense of being unable to use cached results. " +
"WARNING: this is experimental, and only works for Java tests!")
private boolean isUsingOneTimeOutput;
@Option(
name = "--shuffle",
usage =
"Randomize the order in which test classes are executed." +
"WARNING: only works for Java tests!")
private boolean isShufflingTests;
@Option(
name = "--exclude-transitive-tests",
usage =
"Only run the tests targets that were specified on the command line (without adding " +
"more tests by following dependencies).")
private boolean shouldExcludeTransitiveTests;
@AdditionalOptions
@SuppressFieldNotInitialized
private AdbCommandLineOptions adbOptions;
@AdditionalOptions
@SuppressFieldNotInitialized
private TargetDeviceCommandLineOptions targetDeviceOptions;
@AdditionalOptions
@SuppressFieldNotInitialized
private TestSelectorOptions testSelectorOptions;
@AdditionalOptions
@SuppressFieldNotInitialized
private TestLabelOptions testLabelOptions;
@Option(name = "--", handler = ConsumeAllOptionsHandler.class)
private List<String> withDashArguments = Lists.newArrayList();
public boolean isRunAllTests() {
return all || getArguments().isEmpty();
}
@Override
public boolean isCodeCoverageEnabled() {
return isCodeCoverageEnabled;
}
public boolean isResultsCacheEnabled(BuckConfig buckConfig) {
// The option is negative (--no-X) but we prefer to reason about positives, in the code.
if (isResultsCacheDisabled == null) {
boolean isUseResultsCache = buckConfig.getBooleanValue("test", USE_RESULTS_CACHE, true);
isResultsCacheDisabled = !isUseResultsCache;
}
return !isResultsCacheDisabled;
}
@Override
public boolean isDebugEnabled() {
return isDebugEnabled;
}
public Optional<TargetDevice> getTargetDeviceOptional() {
return targetDeviceOptions.getTargetDeviceOptional();
}
public AdbOptions getAdbOptions(BuckConfig buckConfig) {
return adbOptions.getAdbOptions(buckConfig);
}
public TargetDeviceOptions getTargetDeviceOptions() {
return targetDeviceOptions.getTargetDeviceOptions();
}
public boolean isDryRun() {
return isDryRun;
}
public boolean isMatchedByLabelOptions(BuckConfig buckConfig, Set<Label> labels) {
return testLabelOptions.isMatchedByLabelOptions(buckConfig, labels);
}
public boolean shouldExcludeTransitiveTests() {
return shouldExcludeTransitiveTests;
}
public boolean shouldExcludeWin() {
return testLabelOptions.shouldExcludeWin();
}
public boolean isBuildFiltered(BuckConfig buckConfig) {
return isBuildFiltered != null ?
isBuildFiltered :
buckConfig.getBooleanValue("test", "build_filtered_tests", false);
}
public int getNumTestThreads(BuckConfig buckConfig) {
if (isDebugEnabled()) {
return 1;
}
return buckConfig.getNumThreads();
}
private TestRunningOptions getTestRunningOptions(CommandRunnerParams params) {
return TestRunningOptions.builder()
.setUsingOneTimeOutputDirectories(isUsingOneTimeOutput)
.setCodeCoverageEnabled(isCodeCoverageEnabled)
.setRunAllTests(isRunAllTests())
.setTestSelectorList(testSelectorOptions.getTestSelectorList())
.setShouldExplainTestSelectorList(testSelectorOptions.shouldExplain())
.setResultsCacheEnabled(isResultsCacheEnabled(params.getBuckConfig()))
.setDryRun(isDryRun)
.setShufflingTests(isShufflingTests)
.setPathToXmlTestOutput(Optional.fromNullable(pathToXmlTestOutput))
.setPathToJavaAgent(Optional.fromNullable(pathToJavaAgent))
.setCoverageReportFormat(coverageReportFormat)
.setCoverageReportTitle(coverageReportTitle)
.build();
}
private int runTestsInternal(
CommandRunnerParams params,
BuildEngine buildEngine,
Build build,
Iterable<TestRule> testRules)
throws InterruptedException, IOException {
if (!withDashArguments.isEmpty()) {
params.getBuckEventBus().post(ConsoleEvent.severe(
"Unexpected arguments after \"--\" when using internal runner"));
return 1;
}
ConcurrencyLimit concurrencyLimit = new ConcurrencyLimit(
getNumTestThreads(params.getBuckConfig()),
params.getBuckConfig().getLoadLimit());
try (
CommandThreadManager testPool = new CommandThreadManager(
"Test-Run",
params.getBuckConfig().getWorkQueueExecutionOrder(),
concurrencyLimit)) {
return TestRunning.runTests(
params,
testRules,
Preconditions.checkNotNull(build.getBuildContext()),
build.getExecutionContext(),
getTestRunningOptions(params),
testPool.getExecutor(),
buildEngine,
new DefaultStepRunner(build.getExecutionContext()));
} catch (ExecutionException e) {
params.getBuckEventBus().post(ConsoleEvent.severe(
MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
return 1;
}
}
private int runTestsExternal(
final CommandRunnerParams params,
Build build,
Iterable<String> command,
Iterable<TestRule> testRules)
throws InterruptedException, IOException {
TestRunningOptions options = getTestRunningOptions(params);
// Walk the test rules, collecting all the specs.
List<ExternalTestRunnerTestSpec> specs = Lists.newArrayList();
for (TestRule testRule : testRules) {
if (!(testRule instanceof ExternalTestRunnerRule)) {
params.getBuckEventBus().post(ConsoleEvent.severe(String.format(
"Test %s does not support external test running",
testRule.getBuildTarget())));
return 1;
}
ExternalTestRunnerRule rule = (ExternalTestRunnerRule) testRule;
specs.add(rule.getExternalTestRunnerSpec(build.getExecutionContext(), options));
}
// Serialize the specs to a file to pass into the test runner.
Path infoFile =
params.getCell().getFilesystem()
.resolve(BuckConstant.SCRATCH_PATH.resolve("external_runner_specs.json"));
Files.createDirectories(infoFile.getParent());
Files.deleteIfExists(infoFile);
params.getObjectMapper().writerWithDefaultPrettyPrinter().writeValue(infoFile.toFile(), specs);
// Launch and run the external test runner, forwarding it's stdout/stderr to the console.
// We wait for it to complete then returns its error code.
ListeningProcessExecutor processExecutor = new ListeningProcessExecutor();
ProcessExecutorParams processExecutorParams =
ProcessExecutorParams.builder()
.addAllCommand(command)
.addAllCommand(withDashArguments)
.addCommand("--buck-test-info", infoFile.toString())
.setDirectory(params.getCell().getFilesystem().getRootPath().toFile())
.build();
final WritableByteChannel stdout = Channels.newChannel(params.getConsole().getStdOut());
final WritableByteChannel stderr = Channels.newChannel(params.getConsole().getStdErr());
ListeningProcessExecutor.ProcessListener processListener =
new ListeningProcessExecutor.ProcessListener() {
@Override
public void onStart(ListeningProcessExecutor.LaunchedProcess process) {
}
@Override
public void onExit(int exitCode) {
}
@Override
public void onStdout(ByteBuffer buffer, boolean closed) {
try {
stdout.write(buffer);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public void onStderr(ByteBuffer buffer, boolean closed) {
try {
stderr.write(buffer);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
public boolean onStdinReady(ByteBuffer buffer) {
buffer.flip();
return false;
}
};
ListeningProcessExecutor.LaunchedProcess process =
processExecutor.launchProcess(processExecutorParams, processListener);
try {
return processExecutor.waitForProcess(process, Long.MAX_VALUE, TimeUnit.DAYS);
} finally {
processExecutor.destroyProcess(process, /* force */ false);
processExecutor.waitForProcess(process, Long.MAX_VALUE, TimeUnit.DAYS);
}
}
@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
LOG.debug("Running with arguments %s", getArguments());
// Post the build started event, setting it to the Parser recorded start time if appropriate.
BuildEvent.Started started = BuildEvent.started(getArguments());
if (params.getParser().getParseStartTime().isPresent()) {
params.getBuckEventBus().post(
started,
params.getParser().getParseStartTime().get());
} else {
params.getBuckEventBus().post(started);
}
// The first step is to parse all of the build files. This will populate the parser and find all
// of the test rules.
TargetGraph targetGraph;
ImmutableSet<BuildTarget> explicitBuildTargets;
try {
// If the user asked to run all of the tests, parse all of the build files looking for any
// test rules.
if (isRunAllTests()) {
targetGraph = params.getParser().buildTargetGraphForTargetNodeSpecs(
params.getBuckEventBus(),
params.getCell(),
getEnableProfiling(),
ImmutableList.of(
TargetNodePredicateSpec.of(
new Predicate<TargetNode<?>>() {
@Override
public boolean apply(TargetNode<?> input) {
return input.getType().isTestRule();
}
},
BuildFileSpec.fromRecursivePath(Paths.get(""))))).getSecond();
explicitBuildTargets = ImmutableSet.of();
// Otherwise, the user specified specific test targets to build and run, so build a graph
// around these.
} else {
LOG.debug("Parsing graph for arguments %s", getArguments());
Pair<ImmutableSet<BuildTarget>, TargetGraph> result = params.getParser()
.buildTargetGraphForTargetNodeSpecs(
params.getBuckEventBus(),
params.getCell(),
getEnableProfiling(),
parseArgumentsAsTargetNodeSpecs(
params.getBuckConfig(),
getArguments()));
targetGraph = result.getSecond();
explicitBuildTargets = result.getFirst();
LOG.debug("Got explicit build targets %s", explicitBuildTargets);
ImmutableSet.Builder<BuildTarget> testTargetsBuilder = ImmutableSet.builder();
for (TargetNode<?> node : targetGraph.getAll(explicitBuildTargets)) {
ImmutableSortedSet<BuildTarget> nodeTests = TargetNodes.getTestTargetsForNode(node);
if (!nodeTests.isEmpty()) {
LOG.debug("Got tests for target %s: %s", node.getBuildTarget(), nodeTests);
testTargetsBuilder.addAll(nodeTests);
}
}
ImmutableSet<BuildTarget> testTargets = testTargetsBuilder.build();
if (!testTargets.isEmpty()) {
LOG.debug("Got related test targets %s, building new target graph...", testTargets);
targetGraph = params.getParser().buildTargetGraph(
params.getBuckEventBus(),
params.getCell(),
getEnableProfiling(),
Iterables.concat(
explicitBuildTargets,
testTargets));
LOG.debug("Finished building new target graph with tests.");
}
}
} catch (BuildTargetException | BuildFileParseException e) {
params.getBuckEventBus().post(ConsoleEvent.severe(
MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
return 1;
}
TargetGraphToActionGraph targetGraphToActionGraph =
new TargetGraphToActionGraph(
params.getBuckEventBus(),
new BuildTargetNodeToBuildRuleTransformer());
Pair<ActionGraph, BuildRuleResolver> actionGraphAndResolver =
Preconditions.checkNotNull(targetGraphToActionGraph.apply(targetGraph));
// Look up all of the test rules in the action graph.
Iterable<TestRule> testRules = Iterables.filter(
actionGraphAndResolver.getFirst().getNodes(),
TestRule.class);
// Unless the user requests that we build filtered tests, filter them out here, before
// the build.
if (!isBuildFiltered(params.getBuckConfig())) {
testRules = filterTestRules(params.getBuckConfig(), explicitBuildTargets, testRules);
}
if (isDryRun()) {
printMatchingTestRules(params.getConsole(), testRules);
}
try (
CommandThreadManager pool = new CommandThreadManager(
"Test",
params.getBuckConfig().getWorkQueueExecutionOrder(),
getConcurrencyLimit(params.getBuckConfig()))) {
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
pool.getExecutor(),
params.getFileHashCache(),
getBuildEngineMode().or(params.getBuckConfig().getBuildEngineMode()),
params.getBuckConfig().getDependencySchedulingOrder(),
params.getBuckConfig().getBuildDepFiles(),
actionGraphAndResolver.getSecond());
try (Build build = createBuild(
params.getBuckConfig(),
actionGraphAndResolver.getFirst(),
actionGraphAndResolver.getSecond(),
params.getAndroidPlatformTargetSupplier(),
cachingBuildEngine,
params.getArtifactCache(),
params.getConsole(),
params.getBuckEventBus(),
getTargetDeviceOptional(),
params.getPlatform(),
params.getEnvironment(),
params.getObjectMapper(),
params.getClock(),
Optional.of(getAdbOptions(params.getBuckConfig())),
Optional.of(getTargetDeviceOptions()))) {
// Build all of the test rules.
int exitCode = build.executeAndPrintFailuresToEventBus(
testRules,
isKeepGoing(),
params.getBuckEventBus(),
params.getConsole(),
getPathToBuildReport(params.getBuckConfig()));
params.getBuckEventBus().post(BuildEvent.finished(started, exitCode));
if (exitCode != 0) {
return exitCode;
}
// If the user requests that we build tests that we filter out, then we perform
// the filtering here, after we've done the build but before we run the tests.
if (isBuildFiltered(params.getBuckConfig())) {
testRules =
filterTestRules(params.getBuckConfig(), explicitBuildTargets, testRules);
}
// Once all of the rules are built, then run the tests.
Optional<ImmutableList<String>> externalTestRunner =
params.getBuckConfig().getExternalTestRunner();
if (externalTestRunner.isPresent()) {
return runTestsExternal(
params,
build,
externalTestRunner.get(),
testRules);
}
return runTestsInternal(params, cachingBuildEngine, build, testRules);
}
}
}
@Override
public boolean isReadOnly() {
return false;
}
private void printMatchingTestRules(Console console, Iterable<TestRule> testRules) {
PrintStream out = console.getStdOut();
ImmutableList<TestRule> list = ImmutableList.copyOf(testRules);
out.println(String.format("MATCHING TEST RULES (%d):", list.size()));
out.println("");
if (list.isEmpty()) {
out.println(" (none)");
} else {
for (TestRule testRule : testRules) {
out.println(" " + testRule.getBuildTarget());
}
}
out.println("");
}
@VisibleForTesting
Iterable<TestRule> filterTestRules(
BuckConfig buckConfig,
ImmutableSet<BuildTarget> explicitBuildTargets,
Iterable<TestRule> testRules) {
ImmutableSortedSet.Builder<TestRule> builder =
ImmutableSortedSet.orderedBy(
new Comparator<TestRule>() {
@Override
public int compare(TestRule o1, TestRule o2) {
return o1.getBuildTarget().getFullyQualifiedName().compareTo(
o2.getBuildTarget().getFullyQualifiedName());
}
});
for (TestRule rule : testRules) {
boolean explicitArgument = explicitBuildTargets.contains(rule.getBuildTarget());
boolean matchesLabel = isMatchedByLabelOptions(buckConfig, rule.getLabels());
// We always want to run the rules that are given on the command line. Always. Unless we don't
// want to.
if (shouldExcludeWin() && !matchesLabel) {
continue;
}
// The testRules Iterable contains transitive deps of the arguments given on the command line,
// filter those out if such is the user's will.
if (shouldExcludeTransitiveTests() && !explicitArgument) {
continue;
}
// Normal behavior is to include all rules that match the given label as well as any that
// were explicitly specified by the user.
if (explicitArgument || matchesLabel) {
builder.add(rule);
}
}
return builder.build();
}
@Override
public String getShortDescription() {
return "builds and runs the tests for the specified target";
}
}
| apache-2.0 |
sai-pullabhotla/catatumbo | src/test/java/com/jmethods/catatumbo/entities/CharField.java | 1233 | /*
* Copyright 2016 Sai Pullabhotla.
*
* 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.jmethods.catatumbo.entities;
import com.jmethods.catatumbo.Entity;
import com.jmethods.catatumbo.Identifier;
/**
* @author Sai Pullabhotla
*
*/
@Entity
public class CharField {
@Identifier
private long id;
private char sex;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the sex
*/
public char getSex() {
return sex;
}
/**
* @param sex
* the sex to set
*/
public void setSex(char sex) {
this.sex = sex;
}
}
| apache-2.0 |
xuchengdong/cas4.1.9 | cas-server-core/src/main/java/org/jasig/cas/util/RegexUtils.java | 2640 | /*
* 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:
*
* 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.jasig.cas.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Utility class to assist with resource operations.
*
* @author Misagh Moayyed
* @since 4.1.4
*/
public final class RegexUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RegexUtils.class);
/**
* Instantiates a new Regex utils.
*/
private RegexUtils() {}
/**
* Check to see if the specified pattern is a valid regular expression.
*
* @param pattern the pattern
* @return whether this is a valid regex or not
*/
public static boolean isValidRegex(final String pattern) {
try {
LOGGER.debug("Pattern {} is a valid regex.", Pattern.compile(pattern).pattern());
return true;
} catch (final PatternSyntaxException exception) {
return false;
}
}
/**
* Concatenate all elements in the given collection to form a regex pattern.
*
* @param requiredValues the required values
* @param caseInsensitive the case insensitive
* @return the pattern
*/
public static Pattern concatenate(final Collection<String> requiredValues, final boolean caseInsensitive) {
final StringBuilder builder = new StringBuilder(requiredValues.size());
for (final String requiredValue : requiredValues) {
builder.append('(').append(requiredValue).append(")|");
}
final String pattern = StringUtils.removeEnd(builder.toString(), "|");
if (isValidRegex(pattern)) {
return Pattern.compile(pattern, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0);
}
return null;
}
}
| apache-2.0 |
cuba-platform/cuba | modules/web/src/com/haulmont/cuba/web/app/accessgroup/AccessGroupCompanion.java | 7178 | /*
* Copyright (c) 2008-2017 Haulmont.
*
* 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.haulmont.cuba.web.app.accessgroup;
import com.haulmont.cuba.gui.app.security.group.browse.GroupBrowser;
import com.haulmont.cuba.gui.app.security.group.browse.GroupChangeEvent;
import com.haulmont.cuba.gui.app.security.group.browse.UserGroupChangedEvent;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.gui.components.Tree;
import com.haulmont.cuba.gui.components.data.TableItems;
import com.haulmont.cuba.security.entity.Group;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.cuba.web.widgets.CubaTable;
import com.haulmont.cuba.web.widgets.CubaTableDragSourceExtension;
import com.haulmont.cuba.web.widgets.CubaTree;
import com.vaadin.server.Page;
import com.vaadin.shared.ui.grid.DropLocation;
import com.vaadin.shared.ui.grid.DropMode;
import com.vaadin.ui.components.grid.TreeGridDragSource;
import com.vaadin.ui.components.grid.TreeGridDropTarget;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
public class AccessGroupCompanion implements GroupBrowser.Companion {
// cross browser data type
protected final static String TRANSFER_DATA_TYPE = "text";
protected final static String TEXT_PLAIN_DATA_TYPE = "text/plain";
@Override
public void initDragAndDrop(Table<User> usersTable, Tree<Group> groupsTree,
Consumer<UserGroupChangedEvent> userGroupChangedHandler,
Consumer<GroupChangeEvent> groupChangeEventHandler) {
usersTable.withUnwrapped(CubaTable.class, CubaTableDragSourceExtension::new);
groupsTree.withUnwrapped(CubaTree.class, vTree -> {
// tree as drag source
//noinspection unchecked
TreeGridDragSource<Group> treeGridDragSource = new TreeGridDragSource<>(vTree.getCompositionRoot());
treeGridDragSource.setDragDataGenerator(TRANSFER_DATA_TYPE, group -> group.getId().toString());
// tree as drop target
//noinspection unchecked
TreeGridDropTarget<Group> treeGridDropTarget = new TreeGridDropTarget<>(vTree.getCompositionRoot(), DropMode.ON_TOP);
treeGridDropTarget.addTreeGridDropListener(event -> {
// if we drop users from table
if (event.getDragSourceExtension().isPresent() &&
event.getDragSourceExtension().get() instanceof CubaTableDragSourceExtension) {
// return if we drop user between rows
if (event.getDropLocation() == DropLocation.BELOW) {
return;
}
//noinspection unchecked
CubaTableDragSourceExtension<CubaTable> sourceExtension =
(CubaTableDragSourceExtension<CubaTable>) event.getDragSourceExtension().get();
List<Object> itemIds = sourceExtension.getLastDraggedItemIds();
TableItems<User> tableItems = usersTable.getItems();
List<User> users = new ArrayList<>();
for (Object id : itemIds) {
users.add(tableItems.getItem(id));
}
if (event.getDropTargetRow().isPresent()) {
Group group = event.getDropTargetRow().get();
userGroupChangedHandler.accept(new UserGroupChangedEvent(groupsTree, users, group));
}
// if we reorder groups inside tree
} else {
String draggedItemId = event.getDataTransferData().get(TEXT_PLAIN_DATA_TYPE);
if (isEdgeOrIE() && draggedItemId == null) {
draggedItemId = event.getDataTransferText();
}
if (draggedItemId == null) {
return;
}
String[] draggedItemIds = draggedItemId.split("\\r?\\n");
for (String itemId : draggedItemIds) {
Group draggedGroup = groupsTree.getItems().getItem(UUID.fromString(itemId));
if (event.getDropTargetRow().isPresent()) {
Group targetGroup = event.getDropTargetRow().get();
// if we drop to itself
if (targetGroup.getId().equals(draggedGroup.getId())) {
continue;
}
// if we drop parent to its child
//noinspection unchecked
if (isParentDroppedToChild(draggedGroup, targetGroup, vTree)) {
continue;
}
// if we drop child to the same parent
if (draggedGroup.getParent() != null
&& (draggedGroup.getParent().getId().equals(targetGroup.getId()))) {
continue;
}
groupChangeEventHandler.accept(new GroupChangeEvent(groupsTree, draggedGroup.getId(), targetGroup.getId()));
// if we drop group to empty space make it root
} else if (event.getDropLocation() == DropLocation.EMPTY) {
groupChangeEventHandler.accept(new GroupChangeEvent(groupsTree, draggedGroup.getId(), null));
}
}
}
});
});
}
protected boolean isParentDroppedToChild(Group parent, Group child, CubaTree<Group> vTree) {
if (!vTree.hasChildren(parent)) {
return false;
}
return checkAllChildrenRecursively(vTree.getChildren(parent), child, vTree);
}
protected boolean checkAllChildrenRecursively(Collection<Group> children, Group dropOver, CubaTree<Group> vTree) {
for (Group group : children) {
if (group.equals(dropOver)) {
return true;
} else if (vTree.hasChildren(group)) {
if (checkAllChildrenRecursively(vTree.getChildren(group), dropOver, vTree)) {
return true;
}
}
}
return false;
}
protected boolean isEdgeOrIE() {
return Page.getCurrent().getWebBrowser().isIE()
|| Page.getCurrent().getWebBrowser().isEdge();
}
}
| apache-2.0 |
WhiteBearSolutions/WBSAirback | packages/wbsairback-tomcat/wbsairback-tomcat-7.0.22/java/org/apache/catalina/filters/RemoteIpFilter.java | 41632 | /*
* 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.filters;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.AccessLog;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* <p>
* Servlet filter to integrate "X-Forwarded-For" and "X-Forwarded-Proto" HTTP headers.
* </p>
* <p>
* Most of the design of this Servlet Filter is a port of <a
* href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces the apparent client remote
* IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g.
* "X-Forwarded-For").
* </p>
* <p>
* Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a
* proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").
* </p>
* <p>
* This servlet filter proceeds as follows:
* </p>
* <p>
* If the incoming <code>request.getRemoteAddr()</code> matches the servlet filter's list of internal proxies :
* <ul>
* <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http
* header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li>
* <li>For each ip/host of the list:
* <ul>
* <li>if it matches the internal proxies list, the ip/host is swallowed</li>
* <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li>
* <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li>
* </ul>
* </li>
* <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-for</code>) equals to the value of
* <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>,
* <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the
* <code>$httpsServerPort</code> configuration parameter.</li>
* </ul>
* </p>
* <p>
* <strong>Configuration parameters:</strong>
* <table border="1">
* <tr>
* <th>XForwardedFilter property</th>
* <th>Description</th>
* <th>Equivalent mod_remoteip directive</th>
* <th>Format</th>
* <th>Default Value</th>
* </tr>
* <tr>
* <td>remoteIpHeader</td>
* <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from the requesting client
* </td>
* <td>RemoteIPHeader</td>
* <td>Compliant http header name</td>
* <td>x-forwarded-for</td>
* </tr>
* <tr>
* <td>internalProxies</td>
* <td>Regular expression that matches the IP addresses of internal proxies.
* If they appear in the <code>remoteIpHeader</code> value, they will be
* trusted and will not appear
* in the <code>proxiesHeader</code> value</td>
* <td>RemoteIPInternalProxy</td>
* <td>Regular expression (in the syntax supported by
* {@link java.util.regex.Pattern java.util.regex})</td>
* <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3} <br/>
* By default, 10/8, 192.168/16, 169.254/16 and 127/8 are allowed ; 172.16/12 has not been enabled by default because it is complex to
* describe with regular expressions</td>
* </tr>
* </tr>
* <tr>
* <td>proxiesHeader</td>
* <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in the incoming
* <code>remoteIpHeader</code></td>
* <td>RemoteIPProxiesHeader</td>
* <td>Compliant http header name</td>
* <td>x-forwarded-by</td>
* </tr>
* <tr>
* <td>trustedProxies</td>
* <td>Regular expression that matches the IP addresses of trusted proxies.
* If they appear in the <code>remoteIpHeader</code> value, they will be
* trusted and will appear in the <code>proxiesHeader</code> value</td>
* <td>RemoteIPTrustedProxy</td>
* <td>Regular expression (in the syntax supported by
* {@link java.util.regex.Pattern java.util.regex})</td>
* <td> </td>
* </tr>
* <tr>
* <td>protocolHeader</td>
* <td>Name of the http header read by this servlet filter that holds the flag that this request</td>
* <td>N/A</td>
* <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td>
* <td><code>null</code></td>
* </tr>
* <tr>
* <td>protocolHeaderHttpsValue</td>
* <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td>
* <td>N/A</td>
* <td>String like <code>https</code> or <code>ON</code></td>
* <td><code>https</code></td>
* </tr>
* <tr>
* <td>httpServerPort</td>
* <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td>
* <td>N/A</td>
* <td>integer</td>
* <td>80</td>
* </tr>
* <tr>
* <td>httpsServerPort</td>
* <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td>
* <td>N/A</td>
* <td>integer</td>
* <td>443</td>
* </tr>
* </table>
* </p>
* <p>
* <p>
* <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g.
* <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as the JVM doesn't have a
* library similar to <a
* href="http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, we rely on
* regular expressions.
* </p>
* <hr/>
* <p>
* <strong>Sample with internal proxies</strong>
* </p>
* <p>
* XForwardedFilter configuration:
* </p>
* <code><pre>
* <filter>
* <filter-name>RemoteIpFilter</filter-name>
* <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
* <init-param>
* <param-name>internalProxies</param-name>
* <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpHeader</param-name>
* <param-value>x-forwarded-for</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpProxiesHeader</param-name>
* <param-value>x-forwarded-by</param-value>
* </init-param>
* <init-param>
* <param-name>protocolHeader</param-name>
* <param-value>x-forwarded-proto</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>RemoteIpFilter</filter-name>
* <url-pattern>/*</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping></pre></code>
* <p>
* Request values:
* <table border="1">
* <tr>
* <th>property</th>
* <th>Value Before RemoteIpFilter</th>
* <th>Value After RemoteIpFilter</th>
* </tr>
* <tr>
* <td>request.remoteAddr</td>
* <td>192.168.0.10</td>
* <td>140.211.11.130</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-for']</td>
* <td>140.211.11.130, 192.168.0.10</td>
* <td>null</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-by']</td>
* <td>null</td>
* <td>null</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-proto']</td>
* <td>https</td>
* <td>https</td>
* </tr>
* <tr>
* <td>request.scheme</td>
* <td>http</td>
* <td>https</td>
* </tr>
* <tr>
* <td>request.secure</td>
* <td>false</td>
* <td>true</td>
* </tr>
* <tr>
* <td>request.serverPort</td>
* <td>80</td>
* <td>443</td>
* </tr>
* </table>
* Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request.
* <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
* </p>
* <hr/>
* <p>
* <strong>Sample with trusted proxies</strong>
* </p>
* <p>
* RemoteIpFilter configuration:
* </p>
* <code><pre>
* <filter>
* <filter-name>RemoteIpFilter</filter-name>
* <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
* <init-param>
* <param-name>internalProxies</param-name>
* <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpHeader</param-name>
* <param-value>x-forwarded-for</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpProxiesHeader</param-name>
* <param-value>x-forwarded-by</param-value>
* </init-param>
* <init-param>
* <param-name>trustedProxies</param-name>
* <param-value>proxy1|proxy2</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>RemoteIpFilter</filter-name>
* <url-pattern>/*</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping></pre></code>
* <p>
* Request values:
* <table border="1">
* <tr>
* <th>property</th>
* <th>Value Before RemoteIpFilter</th>
* <th>Value After RemoteIpFilter</th>
* </tr>
* <tr>
* <td>request.remoteAddr</td>
* <td>192.168.0.10</td>
* <td>140.211.11.130</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-for']</td>
* <td>140.211.11.130, proxy1, proxy2</td>
* <td>null</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-by']</td>
* <td>null</td>
* <td>proxy1, proxy2</td>
* </tr>
* </table>
* Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
* are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
* </p>
* <hr/>
* <p>
* <strong>Sample with internal and trusted proxies</strong>
* </p>
* <p>
* RemoteIpFilter configuration:
* </p>
* <code><pre>
* <filter>
* <filter-name>RemoteIpFilter</filter-name>
* <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
* <init-param>
* <param-name>internalProxies</param-name>
* <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpHeader</param-name>
* <param-value>x-forwarded-for</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpProxiesHeader</param-name>
* <param-value>x-forwarded-by</param-value>
* </init-param>
* <init-param>
* <param-name>trustedProxies</param-name>
* <param-value>proxy1|proxy2</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>RemoteIpFilter</filter-name>
* <url-pattern>/*</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping></pre></code>
* <p>
* Request values:
* <table border="1">
* <tr>
* <th>property</th>
* <th>Value Before RemoteIpFilter</th>
* <th>Value After RemoteIpFilter</th>
* </tr>
* <tr>
* <td>request.remoteAddr</td>
* <td>192.168.0.10</td>
* <td>140.211.11.130</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-for']</td>
* <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td>
* <td>null</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-by']</td>
* <td>null</td>
* <td>proxy1, proxy2</td>
* </tr>
* </table>
* Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
* are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in
* <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
* </p>
* <hr/>
* <p>
* <strong>Sample with an untrusted proxy</strong>
* </p>
* <p>
* RemoteIpFilter configuration:
* </p>
* <code><pre>
* <filter>
* <filter-name>RemoteIpFilter</filter-name>
* <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
* <init-param>
* <param-name>internalProxies</param-name>
* <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpHeader</param-name>
* <param-value>x-forwarded-for</param-value>
* </init-param>
* <init-param>
* <param-name>remoteIpProxiesHeader</param-name>
* <param-value>x-forwarded-by</param-value>
* </init-param>
* <init-param>
* <param-name>trustedProxies</param-name>
* <param-value>proxy1|proxy2</param-value>
* </init-param>
* </filter>
*
* <filter-mapping>
* <filter-name>RemoteIpFilter</filter-name>
* <url-pattern>/*</url-pattern>
* <dispatcher>REQUEST</dispatcher>
* </filter-mapping></pre></code>
* <p>
* Request values:
* <table border="1">
* <tr>
* <th>property</th>
* <th>Value Before RemoteIpFilter</th>
* <th>Value After RemoteIpFilter</th>
* </tr>
* <tr>
* <td>request.remoteAddr</td>
* <td>192.168.0.10</td>
* <td>untrusted-proxy</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-for']</td>
* <td>140.211.11.130, untrusted-proxy, proxy1</td>
* <td>140.211.11.130</td>
* </tr>
* <tr>
* <td>request.header['x-forwarded-by']</td>
* <td>null</td>
* <td>proxy1</td>
* </tr>
* </table>
* Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds
* <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we can not trust that
* <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP
* verified by <code>proxy1</code>.
* </p>
* <hr/>
*/
public class RemoteIpFilter implements Filter {
public static class XForwardedRequest extends HttpServletRequestWrapper {
static final ThreadLocal<SimpleDateFormat[]> threadLocalDateFormats = new ThreadLocal<SimpleDateFormat[]>() {
@Override
protected SimpleDateFormat[] initialValue() {
return new SimpleDateFormat[] {
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
};
}
};
protected Map<String, List<String>> headers;
protected int localPort;
protected String remoteAddr;
protected String remoteHost;
protected String scheme;
protected boolean secure;
protected int serverPort;
public XForwardedRequest(HttpServletRequest request) {
super(request);
this.localPort = request.getLocalPort();
this.remoteAddr = request.getRemoteAddr();
this.remoteHost = request.getRemoteHost();
this.scheme = request.getScheme();
this.secure = request.isSecure();
this.serverPort = request.getServerPort();
headers = new HashMap<String, List<String>>();
for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
String header = headerNames.nextElement();
headers.put(header, Collections.list(request.getHeaders(header)));
}
}
@Override
public long getDateHeader(String name) {
String value = getHeader(name);
if (value == null) {
return -1;
}
DateFormat[] dateFormats = threadLocalDateFormats.get();
Date date = null;
for (int i = 0; ((i < dateFormats.length) && (date == null)); i++) {
DateFormat dateFormat = dateFormats[i];
try {
date = dateFormat.parse(value);
} catch (Exception ParseException) {
// Ignore
}
}
if (date == null) {
throw new IllegalArgumentException(value);
}
return date.getTime();
}
@Override
public String getHeader(String name) {
Map.Entry<String, List<String>> header = getHeaderEntry(name);
if (header == null || header.getValue() == null || header.getValue().isEmpty()) {
return null;
}
return header.getValue().get(0);
}
protected Map.Entry<String, List<String>> getHeaderEntry(String name) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return entry;
}
}
return null;
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(headers.keySet());
}
@Override
public Enumeration<String> getHeaders(String name) {
Map.Entry<String, List<String>> header = getHeaderEntry(name);
if (header == null || header.getValue() == null) {
return Collections.enumeration(Collections.<String>emptyList());
}
return Collections.enumeration(header.getValue());
}
@Override
public int getIntHeader(String name) {
String value = getHeader(name);
if (value == null) {
return -1;
}
return Integer.parseInt(value);
}
@Override
public int getLocalPort() {
return localPort;
}
@Override
public String getRemoteAddr() {
return this.remoteAddr;
}
@Override
public String getRemoteHost() {
return this.remoteHost;
}
@Override
public String getScheme() {
return scheme;
}
@Override
public int getServerPort() {
return serverPort;
}
@Override
public boolean isSecure() {
return secure;
}
public void removeHeader(String name) {
Map.Entry<String, List<String>> header = getHeaderEntry(name);
if (header != null) {
headers.remove(header.getKey());
}
}
public void setHeader(String name, String value) {
List<String> values = Arrays.asList(value);
Map.Entry<String, List<String>> header = getHeaderEntry(name);
if (header == null) {
headers.put(name, values);
} else {
header.setValue(values);
}
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
public void setSecure(boolean secure) {
this.secure = secure;
}
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
}
/**
* {@link Pattern} for a comma delimited string that support whitespace characters
*/
private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*");
protected static final String HTTP_SERVER_PORT_PARAMETER = "httpServerPort";
protected static final String HTTPS_SERVER_PORT_PARAMETER = "httpsServerPort";
protected static final String INTERNAL_PROXIES_PARAMETER = "internalProxies";
/**
* Logger
*/
private static final Log log = LogFactory.getLog(RemoteIpFilter.class);
protected static final String PROTOCOL_HEADER_PARAMETER = "protocolHeader";
protected static final String PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER = "protocolHeaderHttpsValue";
protected static final String PORT_HEADER_PARAMETER = "portHeader";
protected static final String CHANGE_LOCAL_PORT_PARAMETER = "changeLocalPort";
protected static final String PROXIES_HEADER_PARAMETER = "proxiesHeader";
protected static final String REMOTE_IP_HEADER_PARAMETER = "remoteIpHeader";
protected static final String TRUSTED_PROXIES_PARAMETER = "trustedProxies";
/**
* Convert a given comma delimited list of regular expressions into an array of String
*
* @return array of patterns (non <code>null</code>)
*/
protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern
.split(commaDelimitedStrings);
}
/**
* Convert an array of strings in a comma delimited string
*/
protected static String listToCommaDelimitedString(List<String> stringList) {
if (stringList == null) {
return "";
}
StringBuilder result = new StringBuilder();
for (Iterator<String> it = stringList.iterator(); it.hasNext();) {
Object element = it.next();
if (element != null) {
result.append(element);
if (it.hasNext()) {
result.append(", ");
}
}
}
return result.toString();
}
/**
* @see #setHttpServerPort(int)
*/
private int httpServerPort = 80;
/**
* @see #setHttpsServerPort(int)
*/
private int httpsServerPort = 443;
/**
* @see #setInternalProxies(String)
*/
private Pattern internalProxies = Pattern.compile(
"10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
"192\\.168\\.\\d{1,3}\\.\\d{1,3}|" +
"169\\.254\\.\\d{1,3}\\.\\d{1,3}|" +
"127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
/**
* @see #setProtocolHeader(String)
*/
private String protocolHeader = null;
private String protocolHeaderHttpsValue = "https";
private String portHeader = null;
private boolean changeLocalPort = false;
/**
* @see #setProxiesHeader(String)
*/
private String proxiesHeader = "X-Forwarded-By";
/**
* @see #setRemoteIpHeader(String)
*/
private String remoteIpHeader = "X-Forwarded-For";
/**
* @see #setRequestAttributesEnabled(boolean)
*/
private boolean requestAttributesEnabled = true;
/**
* @see #setTrustedProxies(String)
*/
private Pattern trustedProxies = null;
@Override
public void destroy() {
// NOOP
}
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (internalProxies != null &&
internalProxies.matcher(request.getRemoteAddr()).matches()) {
String remoteIp = null;
// In java 6, proxiesHeaderValue should be declared as a java.util.Deque
LinkedList<String> proxiesHeaderValue = new LinkedList<String>();
StringBuilder concatRemoteIpHeaderValue = new StringBuilder();
for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) {
if (concatRemoteIpHeaderValue.length() > 0) {
concatRemoteIpHeaderValue.append(", ");
}
concatRemoteIpHeaderValue.append(e.nextElement());
}
String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString());
int idx;
// loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain
for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) {
String currentRemoteIp = remoteIpHeaderValue[idx];
remoteIp = currentRemoteIp;
if (internalProxies.matcher(currentRemoteIp).matches()) {
// do nothing, internalProxies IPs are not appended to the
} else if (trustedProxies != null &&
trustedProxies.matcher(currentRemoteIp).matches()) {
proxiesHeaderValue.addFirst(currentRemoteIp);
} else {
idx--; // decrement idx because break statement doesn't do it
break;
}
}
// continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader
LinkedList<String> newRemoteIpHeaderValue = new LinkedList<String>();
for (; idx >= 0; idx--) {
String currentRemoteIp = remoteIpHeaderValue[idx];
newRemoteIpHeaderValue.addFirst(currentRemoteIp);
}
XForwardedRequest xRequest = new XForwardedRequest(request);
if (remoteIp != null) {
xRequest.setRemoteAddr(remoteIp);
xRequest.setRemoteHost(remoteIp);
if (proxiesHeaderValue.size() == 0) {
xRequest.removeHeader(proxiesHeader);
} else {
String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue);
xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies);
}
if (newRemoteIpHeaderValue.size() == 0) {
xRequest.removeHeader(remoteIpHeader);
} else {
String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue);
xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue);
}
}
if (protocolHeader != null) {
String protocolHeaderValue = request.getHeader(protocolHeader);
if (protocolHeaderValue == null) {
// don't modify the secure,scheme and serverPort attributes of the request
} else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) {
xRequest.setSecure(true);
xRequest.setScheme("https");
setPorts(xRequest, httpsServerPort);
} else {
xRequest.setSecure(false);
xRequest.setScheme("http");
setPorts(xRequest, httpServerPort);
}
}
if (log.isDebugEnabled()) {
log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr()
+ "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure()
+ "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='"
+ concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='"
+ (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='"
+ xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='"
+ xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='"
+ xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'");
}
if (requestAttributesEnabled) {
request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE,
request.getRemoteAddr());
request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE,
request.getRemoteHost());
request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE,
request.getProtocol());
request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE,
Integer.valueOf(request.getServerPort()));
}
chain.doFilter(xRequest, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '"
+ request.getRemoteAddr() + "'");
}
chain.doFilter(request, response);
}
}
private void setPorts(XForwardedRequest xrequest, int defaultPort) {
int port = defaultPort;
if (getPortHeader() != null) {
String portHeaderValue = xrequest.getHeader(getPortHeader());
if (portHeaderValue != null) {
try {
port = Integer.parseInt(portHeaderValue);
} catch (NumberFormatException nfe) {
log.debug("Invalid port value [" + portHeaderValue +
"] provided in header [" + getPortHeader() + "]");
}
}
}
xrequest.setServerPort(port);
if (isChangeLocalPort()) {
xrequest.setLocalPort(port);
}
}
/**
* Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwareded-for</code> is not empty.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);
} else {
chain.doFilter(request, response);
}
}
public boolean isChangeLocalPort() {
return changeLocalPort;
}
public int getHttpsServerPort() {
return httpsServerPort;
}
public Pattern getInternalProxies() {
return internalProxies;
}
public String getProtocolHeader() {
return protocolHeader;
}
public String getPortHeader() {
return portHeader;
}
public String getProtocolHeaderHttpsValue() {
return protocolHeaderHttpsValue;
}
public String getProxiesHeader() {
return proxiesHeader;
}
public String getRemoteIpHeader() {
return remoteIpHeader;
}
/**
* @see #setRequestAttributesEnabled(boolean)
* @return <code>true</code> if the attributes will be logged, otherwise
* <code>false</code>
*/
public boolean getRequestAttributesEnabled() {
return requestAttributesEnabled;
}
public Pattern getTrustedProxies() {
return trustedProxies;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) {
setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER));
}
if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) {
setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER));
}
if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) {
setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER));
}
if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) {
setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER));
}
if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) {
setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER)));
}
if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) {
setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER));
}
if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) {
setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER));
}
if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) {
setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER));
}
if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) {
try {
setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER)));
} catch (NumberFormatException e) {
throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage());
}
}
if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) {
try {
setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER)));
} catch (NumberFormatException e) {
throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage());
}
}
}
/**
* <p>
* If <code>true</code>, the return values for both {@link
* ServletRequest#getLocalPort()} and {@link ServletRequest#getServerPort()}
* wil be modified by this Filter rather than just
* {@link ServletRequest#getServerPort()}.
* </p>
* <p>
* Default value : <code>false</code>
* </p>
*/
public void setChangeLocalPort(boolean changeLocalPort) {
this.changeLocalPort = changeLocalPort;
}
/**
* <p>
* Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and
* has a value different of {@link #protocolHeaderHttpsValue}).
* </p>
* <p>
* Default value : 80
* </p>
*/
public void setHttpServerPort(int httpServerPort) {
this.httpServerPort = httpServerPort;
}
/**
* <p>
* Server Port value if the {@link #protocolHeader} indicates HTTPS
* </p>
* <p>
* Default value : 443
* </p>
*/
public void setHttpsServerPort(int httpsServerPort) {
this.httpsServerPort = httpsServerPort;
}
/**
* <p>
* Regular expression that defines the internal proxies.
* </p>
* <p>
* Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}
* </p>
*/
public void setInternalProxies(String internalProxies) {
if (internalProxies == null || internalProxies.length() == 0) {
this.internalProxies = null;
} else {
this.internalProxies = Pattern.compile(internalProxies);
}
}
/**
* <p>
* Header that holds the incoming port, usally named
* <code>X-Forwarded-Port</code>. If <code>null</code>,
* {@link #httpServerPort} or {@link #httpsServerPort} will be used.
* </p>
* <p>
* Default value : <code>null</code>
* </p>
*/
public void setPortHeader(String portHeader) {
this.portHeader = portHeader;
}
/**
* <p>
* Header that holds the incoming protocol, usally named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and
* request.secure will not be modified.
* </p>
* <p>
* Default value : <code>null</code>
* </p>
*/
public void setProtocolHeader(String protocolHeader) {
this.protocolHeader = protocolHeader;
}
/**
* <p>
* Case insensitive value of the protocol header to indicate that the incoming http request uses HTTPS.
* </p>
* <p>
* Default value : <code>https</code>
* </p>
*/
public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
this.protocolHeaderHttpsValue = protocolHeaderHttpsValue;
}
/**
* <p>
* The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP
* addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header,
* while any intermediate RemoteIPInternalProxy addresses are discarded.
* </p>
* <p>
* Name of the http header that holds the list of trusted proxies that has been traversed by the http request.
* </p>
* <p>
* The value of this header can be comma delimited.
* </p>
* <p>
* Default value : <code>X-Forwarded-By</code>
* </p>
*/
public void setProxiesHeader(String proxiesHeader) {
this.proxiesHeader = proxiesHeader;
}
/**
* <p>
* Name of the http header from which the remote ip is extracted.
* </p>
* <p>
* The value of this header can be comma delimited.
* </p>
* <p>
* Default value : <code>X-Forwarded-For</code>
* </p>
*/
public void setRemoteIpHeader(String remoteIpHeader) {
this.remoteIpHeader = remoteIpHeader;
}
/**
* Should this filter set request attributes for IP address, Hostname,
* protocol and port used for the request? This are typically used in
* conjunction with an {@link AccessLog} which will otherwise log the
* original values. Default is <code>true</code>.
*
* The attributes set are:
* <ul>
* <li>org.apache.catalina.RemoteAddr</li>
* <li>org.apache.catalina.RemoteHost</li>
* <li>org.apache.catalina.Protocol</li>
* <li>org.apache.catalina.ServerPost</li>
* </ul>
*
* @param requestAttributesEnabled <code>true</code> causes the attributes
* to be set, <code>false</code> disables
* the setting of the attributes.
*/
public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
this.requestAttributesEnabled = requestAttributesEnabled;
}
/**
* <p>
* Regular expression defining proxies that are trusted when they appear in
* the {@link #remoteIpHeader} header.
* </p>
* <p>
* Default value : empty list, no external proxy is trusted.
* </p>
*/
public void setTrustedProxies(String trustedProxies) {
if (trustedProxies == null || trustedProxies.length() == 0) {
this.trustedProxies = null;
} else {
this.trustedProxies = Pattern.compile(trustedProxies);
}
}
}
| apache-2.0 |
tianzhidao28/SpringQuickService | src/test/java/com/rocyuan/zero/security/SecurityUtilsUnitTest.java | 2093 | package com.rocyuan.zero.security;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the SecurityUtils utility class.
*
* @see SecurityUtils
*/
public class SecurityUtilsUnitTest {
@Test
public void testgetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
String login = SecurityUtils.getCurrentUserLogin();
assertThat(login).isEqualTo("admin");
}
@Test
public void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
public void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
}
| apache-2.0 |
cping/LGame | Java/Loon-Neo/live2d/loon/live2d/util/TouchManager.java | 3009 | package loon.live2d.util;
import loon.utils.MathUtils;
public class TouchManager {
static boolean SCALING_ENABLED = true;
private float startY;
private float startX;
private float lastX = 0;
private float lastY = 0;
private float lastX1 = 0;
private float lastY1 = 0;
private float lastX2 = 0;
private float lastY2 = 0;
private float lastTouchDistance = -1;
private float moveX;
private float moveY;
private float scale;
private boolean touchSingle;
private boolean flipAvailable;
public void touchBegan(float x1, float y1, float x2, float y2) {
float dist = distance(x1, y1, x2, y2);
float centerX = (lastX1 + lastX2) * 0.5f;
float centerY = (-lastY1 - lastY2) * 0.5f;
lastX = centerX;
lastY = centerY;
startX = centerX;
startY = centerY;
lastTouchDistance = dist;
flipAvailable = true;
touchSingle = false;
}
public void touchBegan(float x, float y) {
lastX = x;
lastY = -y;
startX = x;
startY = -y;
lastTouchDistance = -1;
flipAvailable = true;
touchSingle = true;
}
public void touchesMoved(float x, float y) {
lastX = x;
lastY = -y;
lastTouchDistance = -1;
touchSingle = true;
}
public void touchesMoved(float x1, float y1, float x2, float y2) {
float dist = distance(x1, y1, x2, y2);
float centerX = (x1 + x2) * 0.5f;
float centerY = (-y1 + -y2) * 0.5f;
if (lastTouchDistance > 0) {
scale = MathUtils.pow(dist / lastTouchDistance, 0.75f);
moveX = calcShift(x1 - lastX1, x2 - lastX2);
moveY = calcShift(-y1 - lastY1, -y2 - lastY2);
} else {
scale = 1;
moveX = 0;
moveY = 0;
}
lastX = centerX;
lastY = centerY;
lastX1 = x1;
lastY1 = -y1;
lastX2 = x2;
lastY2 = -y2;
lastTouchDistance = dist;
touchSingle = false;
}
public float getCenterX() {
return lastX;
}
public float getCenterY() {
return lastY;
}
public float getDeltaX() {
return moveX;
}
public float getDeltaY() {
return moveY;
}
public float getStartX() {
return startX;
}
public float getStartY() {
return startY;
}
public float getScale() {
return scale;
}
public float getX() {
return lastX;
}
public float getY() {
return lastY;
}
public float getX1() {
return lastX1;
}
public float getY1() {
return lastY1;
}
public float getX2() {
return lastX2;
}
public float getY2() {
return lastY2;
}
private float distance(float x1, float y1, float x2, float y2) {
return (float) MathUtils.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
* (y1 - y2));
}
private float calcShift(float v1, float v2) {
if ((v1 > 0) != (v2 > 0))
return 0;
float fugou = v1 > 0 ? 1 : -1;
float a1 = MathUtils.abs(v1);
float a2 = MathUtils.abs(v2);
return fugou * ((a1 < a2) ? a1 : a2);
}
public float getFlickDistance() {
return distance(startX, startY, lastX, lastY);
}
public boolean isSingleTouch() {
return touchSingle;
}
public boolean isFlickAvailable() {
return flipAvailable;
}
public void disableFlick() {
flipAvailable = false;
}
}
| apache-2.0 |
XueweiKent/LockedTransaction | src/java/org/apache/cassandra/index/sasi/plan/Expression.java | 11997 | /*
* 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.index.sasi.plan;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.cql3.Operator;
import org.apache.cassandra.index.sasi.analyzer.AbstractAnalyzer;
import org.apache.cassandra.index.sasi.conf.ColumnIndex;
import org.apache.cassandra.index.sasi.disk.OnDiskIndex;
import org.apache.cassandra.index.sasi.utils.TypeUtil;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Expression
{
private static final Logger logger = LoggerFactory.getLogger(Expression.class);
public enum Op
{
EQ, MATCH, PREFIX, SUFFIX, CONTAINS, NOT_EQ, RANGE;
public static Op valueOf(Operator operator)
{
switch (operator)
{
case EQ:
return EQ;
case NEQ:
return NOT_EQ;
case LT:
case GT:
case LTE:
case GTE:
return RANGE;
case LIKE_PREFIX:
return PREFIX;
case LIKE_SUFFIX:
return SUFFIX;
case LIKE_CONTAINS:
return CONTAINS;
case LIKE_MATCHES:
return MATCH;
default:
throw new IllegalArgumentException("unknown operator: " + operator);
}
}
}
private final QueryController controller;
public final AbstractAnalyzer analyzer;
public final ColumnIndex index;
public final AbstractType<?> validator;
public final boolean isLiteral;
@VisibleForTesting
protected Op operation;
public Bound lower, upper;
public List<ByteBuffer> exclusions = new ArrayList<>();
public Expression(Expression other)
{
this(other.controller, other.index);
operation = other.operation;
}
public Expression(QueryController controller, ColumnIndex columnIndex)
{
this.controller = controller;
this.index = columnIndex;
this.analyzer = columnIndex.getAnalyzer();
this.validator = columnIndex.getValidator();
this.isLiteral = columnIndex.isLiteral();
}
@VisibleForTesting
public Expression(String name, AbstractType<?> validator)
{
this(null, new ColumnIndex(UTF8Type.instance, ColumnDefinition.regularDef("sasi", "internal", name, validator), null));
}
public Expression setLower(Bound newLower)
{
lower = newLower == null ? null : new Bound(newLower.value, newLower.inclusive);
return this;
}
public Expression setUpper(Bound newUpper)
{
upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive);
return this;
}
public Expression setOp(Op op)
{
this.operation = op;
return this;
}
public Expression add(Operator op, ByteBuffer value)
{
boolean lowerInclusive = false, upperInclusive = false;
switch (op)
{
case LIKE_PREFIX:
case LIKE_SUFFIX:
case LIKE_CONTAINS:
case LIKE_MATCHES:
case EQ:
lower = new Bound(value, true);
upper = lower;
operation = Op.valueOf(op);
break;
case NEQ:
// index expressions are priority sorted
// and NOT_EQ is the lowest priority, which means that operation type
// is always going to be set before reaching it in case of RANGE or EQ.
if (operation == null)
{
operation = Op.NOT_EQ;
lower = new Bound(value, true);
upper = lower;
}
else
exclusions.add(value);
break;
case LTE:
upperInclusive = true;
case LT:
operation = Op.RANGE;
upper = new Bound(value, upperInclusive);
break;
case GTE:
lowerInclusive = true;
case GT:
operation = Op.RANGE;
lower = new Bound(value, lowerInclusive);
break;
}
return this;
}
public Expression addExclusion(ByteBuffer value)
{
exclusions.add(value);
return this;
}
public boolean isSatisfiedBy(ByteBuffer value)
{
if (!TypeUtil.isValid(value, validator))
{
int size = value.remaining();
if ((value = TypeUtil.tryUpcast(value, validator)) == null)
{
logger.error("Can't cast value for {} to size accepted by {}, value size is {}.",
index.getColumnName(),
validator,
FBUtilities.prettyPrintMemory(size));
return false;
}
}
if (lower != null)
{
// suffix check
if (isLiteral)
{
if (!validateStringValue(value, lower.value))
return false;
}
else
{
// range or (not-)equals - (mainly) for numeric values
int cmp = validator.compare(lower.value, value);
// in case of (NOT_)EQ lower == upper
if (operation == Op.EQ || operation == Op.NOT_EQ)
return cmp == 0;
if (cmp > 0 || (cmp == 0 && !lower.inclusive))
return false;
}
}
if (upper != null && lower != upper)
{
// string (prefix or suffix) check
if (isLiteral)
{
if (!validateStringValue(value, upper.value))
return false;
}
else
{
// range - mainly for numeric values
int cmp = validator.compare(upper.value, value);
if (cmp < 0 || (cmp == 0 && !upper.inclusive))
return false;
}
}
// as a last step let's check exclusions for the given field,
// this covers EQ/RANGE with exclusions.
for (ByteBuffer term : exclusions)
{
if (isLiteral && validateStringValue(value, term))
return false;
else if (validator.compare(term, value) == 0)
return false;
}
return true;
}
private boolean validateStringValue(ByteBuffer columnValue, ByteBuffer requestedValue)
{
analyzer.reset(columnValue.duplicate());
while (analyzer.hasNext())
{
ByteBuffer term = analyzer.next();
boolean isMatch = false;
switch (operation)
{
case EQ:
case MATCH:
// Operation.isSatisfiedBy handles conclusion on !=,
// here we just need to make sure that term matched it
case NOT_EQ:
isMatch = validator.compare(term, requestedValue) == 0;
break;
case PREFIX:
isMatch = ByteBufferUtil.startsWith(term, requestedValue);
break;
case SUFFIX:
isMatch = ByteBufferUtil.endsWith(term, requestedValue);
break;
case CONTAINS:
isMatch = ByteBufferUtil.contains(term, requestedValue);
break;
}
if (isMatch)
return true;
}
return false;
}
public Op getOp()
{
return operation;
}
public void checkpoint()
{
if (controller == null)
return;
controller.checkpoint();
}
public boolean hasLower()
{
return lower != null;
}
public boolean hasUpper()
{
return upper != null;
}
public boolean isLowerSatisfiedBy(OnDiskIndex.DataTerm term)
{
if (!hasLower())
return true;
int cmp = term.compareTo(validator, lower.value, false);
return cmp > 0 || cmp == 0 && lower.inclusive;
}
public boolean isUpperSatisfiedBy(OnDiskIndex.DataTerm term)
{
if (!hasUpper())
return true;
int cmp = term.compareTo(validator, upper.value, false);
return cmp < 0 || cmp == 0 && upper.inclusive;
}
public boolean isIndexed()
{
return index.isIndexed();
}
public String toString()
{
return String.format("Expression{name: %s, op: %s, lower: (%s, %s), upper: (%s, %s), exclusions: %s}",
index.getColumnName(),
operation,
lower == null ? "null" : validator.getString(lower.value),
lower != null && lower.inclusive,
upper == null ? "null" : validator.getString(upper.value),
upper != null && upper.inclusive,
Iterators.toString(Iterators.transform(exclusions.iterator(), validator::getString)));
}
public int hashCode()
{
return new HashCodeBuilder().append(index.getColumnName())
.append(operation)
.append(validator)
.append(lower).append(upper)
.append(exclusions).build();
}
public boolean equals(Object other)
{
if (!(other instanceof Expression))
return false;
if (this == other)
return true;
Expression o = (Expression) other;
return Objects.equals(index.getColumnName(), o.index.getColumnName())
&& validator.equals(o.validator)
&& operation == o.operation
&& Objects.equals(lower, o.lower)
&& Objects.equals(upper, o.upper)
&& exclusions.equals(o.exclusions);
}
public static class Bound
{
public final ByteBuffer value;
public final boolean inclusive;
public Bound(ByteBuffer value, boolean inclusive)
{
this.value = value;
this.inclusive = inclusive;
}
public boolean equals(Object other)
{
if (!(other instanceof Bound))
return false;
Bound o = (Bound) other;
return value.equals(o.value) && inclusive == o.inclusive;
}
}
}
| apache-2.0 |
charles-cooper/idylfin | src/com/opengamma/analytics/financial/model/interestrate/definition/HullWhiteOneFactorPiecewiseConstantDataBundle.java | 1714 | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.interestrate.definition;
import org.apache.commons.lang.Validate;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
/**
* Class describing the data required to price interest rate derivatives with Hull-White one factor model (curves and model parameters).
*/
public class HullWhiteOneFactorPiecewiseConstantDataBundle extends YieldCurveBundle {
/**
* The Hull-White one factor model parameters.
*/
private final HullWhiteOneFactorPiecewiseConstantParameters _parameters;
/**
* Constructor from Hull-White parameters and curve bundle.
* @param hullWhiteParameters The Hull-White model parameters.
* @param curves Curve bundle.
*/
public HullWhiteOneFactorPiecewiseConstantDataBundle(final HullWhiteOneFactorPiecewiseConstantParameters hullWhiteParameters, final YieldCurveBundle curves) {
super(curves);
Validate.notNull(hullWhiteParameters, "Hull-White parameters");
_parameters = hullWhiteParameters;
}
@Override
/**
* Create a new copy of the bundle using a new map and the same curve and curve names. The same HullWhiteOneFactorPiecewiseConstantParameters is used.
* @return The bundle.
*/
public HullWhiteOneFactorPiecewiseConstantDataBundle copy() {
return new HullWhiteOneFactorPiecewiseConstantDataBundle(_parameters, this);
}
/**
* Gets the Hull-White one factor parameters.
* @return The parameters.
*/
public HullWhiteOneFactorPiecewiseConstantParameters getHullWhiteParameter() {
return _parameters;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/transform/ListEntitledApplicationsResultJsonUnmarshaller.java | 3331 | /*
* 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.appstream.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.appstream.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListEntitledApplicationsResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListEntitledApplicationsResultJsonUnmarshaller implements Unmarshaller<ListEntitledApplicationsResult, JsonUnmarshallerContext> {
public ListEntitledApplicationsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ListEntitledApplicationsResult listEntitledApplicationsResult = new ListEntitledApplicationsResult();
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 listEntitledApplicationsResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("EntitledApplications", targetDepth)) {
context.nextToken();
listEntitledApplicationsResult.setEntitledApplications(new ListUnmarshaller<EntitledApplication>(EntitledApplicationJsonUnmarshaller
.getInstance())
.unmarshall(context));
}
if (context.testExpression("NextToken", targetDepth)) {
context.nextToken();
listEntitledApplicationsResult.setNextToken(context.getUnmarshaller(String.class).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 listEntitledApplicationsResult;
}
private static ListEntitledApplicationsResultJsonUnmarshaller instance;
public static ListEntitledApplicationsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListEntitledApplicationsResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
software-engineering-amsterdam/poly-ql | eenass/QLanguage/src/ast/types/IntType.java | 407 | package ast.types;
import ast.visitors.TypeVisitor;
public class IntType extends Type{
@Override
public <T> T accept(TypeVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public boolean isCompatibleTo(Type type) {
return (this.isCompatibleToInt() && !type.isCompatibleToBool() && !type.isCompatibleToStr());
}
@Override
public boolean isCompatibleToInt(){
return true;
}
}
| apache-2.0 |
surech/halarious | halarious-core/src/test/java/ch/halarious/core/examples/ManufacturerResource.java | 1347 | /*
* Copyright 2014 Stefan Urech
* 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 ch.halarious.core.examples;
import ch.halarious.core.HalBaseResource;
import ch.halarious.core.HalLink;
/**
* Created by surech on 15.01.14.
*/
public class ManufacturerResource extends HalBaseResource {
@HalLink
private String self;
@HalLink
private String homepage;
private String name;
public ManufacturerResource(String self, String homepage, String name) {
this.self = self;
this.homepage = homepage;
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| apache-2.0 |
farmerbb/Taskbar | app/src/main/java/com/farmerbb/taskbar/activity/BackupRestoreActivity.java | 6639 | /* Copyright 2020 Braden Farmer
*
* 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.farmerbb.taskbar.activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import com.farmerbb.taskbar.R;
import com.farmerbb.taskbar.backup.BackupUtils;
import com.farmerbb.taskbar.backup.JSONBackupAgent;
import com.farmerbb.taskbar.util.U;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class BackupRestoreActivity extends AbstractProgressActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int enter = getResources().getIdentifier("activity_close_enter", "anim", "android");
int exit = getResources().getIdentifier("activity_close_exit", "anim", "android");
overridePendingTransition(enter, exit);
int requestCode = getIntent().getIntExtra("request_code", -1);
Uri uri = getIntent().getParcelableExtra("uri");
boolean isExport = requestCode == U.EXPORT;
boolean isImport = requestCode == U.IMPORT;
TextView textView = findViewById(R.id.progress_message);
if(isExport) textView.setText(R.string.tb_backing_up_settings);
if(isImport) textView.setText(R.string.tb_restoring_settings);
if(savedInstanceState != null) return;
new Thread(() -> {
if(isExport) exportData(uri);
if(isImport) importData(uri);
finish();
overridePendingTransition(enter, exit);
}).start();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void exportData(Uri uri) {
try {
ZipOutputStream output = new ZipOutputStream(
new BufferedOutputStream(getContentResolver().openOutputStream(uri))
);
output.putNextEntry(new ZipEntry("backup.json"));
JSONObject json = new JSONObject();
BackupUtils.backup(this, new JSONBackupAgent(json));
output.write(json.toString().getBytes());
output.closeEntry();
File imagesDir = new File(getFilesDir(), "tb_images");
imagesDir.mkdirs();
for(String filename : U.getImageFilenames()) {
File customImage = new File(imagesDir, filename);
if(customImage.exists()) {
output.putNextEntry(new ZipEntry("tb_images/" + filename));
BufferedInputStream input = new BufferedInputStream(new FileInputStream(customImage));
byte[] data = new byte[input.available()];
if(data.length > 0) {
input.read(data);
input.close();
}
output.write(data);
output.closeEntry();
}
}
output.close();
setResult(R.string.tb_backup_successful);
} catch (Throwable e) {
setResult(R.string.tb_backup_failed);
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void importData(Uri uri) {
File importedFile = new File(getFilesDir(), "temp.zip");
File statusFile = new File(getFilesDir(), "restore_in_progress");
boolean pointOfNoReturn = false;
try {
InputStream is = new BufferedInputStream(getContentResolver().openInputStream(uri));
byte[] zipData = new byte[is.available()];
if(zipData.length > 0) {
OutputStream os = new BufferedOutputStream(new FileOutputStream(importedFile));
is.read(zipData);
os.write(zipData);
is.close();
os.close();
}
ZipFile zipFile = new ZipFile(importedFile);
ZipEntry backupJsonEntry = zipFile.getEntry("backup.json");
if(backupJsonEntry == null) {
// Backup file is invalid; fail immediately
throw new Exception();
}
byte[] data = new byte[(int) backupJsonEntry.getSize()];
InputStream input = new BufferedInputStream(zipFile.getInputStream(backupJsonEntry));
input.read(data);
input.close();
JSONObject json = new JSONObject(new String(data));
// We are at the point of no return.
pointOfNoReturn = true;
statusFile.createNewFile();
BackupUtils.restore(this, new JSONBackupAgent(json));
File imagesDir = new File(getFilesDir(), "tb_images");
imagesDir.mkdirs();
for(String filename : U.getImageFilenames()) {
File customImage = new File(imagesDir, filename);
if(customImage.exists()) customImage.delete();
ZipEntry customImageEntry = zipFile.getEntry("tb_images/" + filename);
if(customImageEntry != null) {
data = new byte[(int) customImageEntry.getSize()];
input = new BufferedInputStream(zipFile.getInputStream(customImageEntry));
input.read(data);
input.close();
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(customImage));
if(data.length > 0) {
output.write(data);
output.close();
}
}
}
statusFile.renameTo(new File(getFilesDir(), "restore_successful"));
} catch (Throwable e) {
if(!pointOfNoReturn)
setResult(R.string.tb_backup_file_invalid);
} finally {
importedFile.delete();
if(pointOfNoReturn)
U.restartApp(this, false);
}
}
}
| apache-2.0 |
everttigchelaar/camel-svn | examples/camel-example-guice-jms/src/test/java/org/apache/camel/example/guice/jms/IntegrationTest.java | 1288 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.guice.jms;
import junit.framework.TestCase;
import org.apache.camel.guice.Main;
/**
* @version
*/
public class IntegrationTest extends TestCase {
public void testCamelRulesDeployCorrectlyInGuice() throws Exception {
// let's boot up the Guicey JNDI context for 2 seconds to check that it works OK
Main.main("-duration", "2s", "-o", "target/site/cameldoc", "-j", "/guicejndi.properties");
}
} | apache-2.0 |
spdx/tools | Test/org/spdx/rdfparser/model/pointer/TestLineCharPointer.java | 6573 | /**
* Copyright (c) 2016 Source Auditor 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.spdx.rdfparser.model.pointer;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spdx.rdfparser.IModelContainer;
import org.spdx.rdfparser.InvalidSPDXAnalysisException;
import org.spdx.rdfparser.SpdxRdfConstants;
import org.spdx.rdfparser.model.ModelContainerForTest;
import org.spdx.rdfparser.model.SpdxElement;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
/**
* @author Gary
*
*/
public class TestLineCharPointer {
String REFERENCED_ELEMENT_NAME1 = "Element1";
String REFERENCED_ELEMENT_NAME2 = "Element2";
SpdxElement REFERENCED1;
SpdxElement REFERENCED2;
Resource REFERENCED_RESOURCE1;
Resource REFERENCED_RESOURCE2;
Model model;
IModelContainer modelContainer;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
this.model = ModelFactory.createDefaultModel();
modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
REFERENCED1 = new SpdxElement(REFERENCED_ELEMENT_NAME1, "", null, null);
REFERENCED_RESOURCE1 = REFERENCED1.createResource(modelContainer);
REFERENCED2 = new SpdxElement(REFERENCED_ELEMENT_NAME2, "", null, null);
REFERENCED_RESOURCE2 = REFERENCED2.createResource(modelContainer);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link org.spdx.rdfparser.model.pointer.LineCharPointer#getType(org.apache.jena.rdf.model.Model)}.
* @throws InvalidSPDXAnalysisException
*/
@Test
public void testGetType() throws InvalidSPDXAnalysisException {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
lcp.createResource(modelContainer);
assertEquals(SpdxRdfConstants.RDF_POINTER_NAMESPACE + SpdxRdfConstants.CLASS_POINTER_LINE_CHAR_POINTER,
lcp.getType(model).toString());
}
/**
* Test method for {@link org.spdx.rdfparser.model.pointer.LineCharPointer#verify()}.
* @throws InvalidSPDXAnalysisException
*/
@Test
public void testVerify() throws InvalidSPDXAnalysisException {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
lcp.createResource(modelContainer);
List<String> result = lcp.verify();
assertEquals(0, result.size());
// Null referenced
LineCharPointer lcp2 = new LineCharPointer(null, 15);
lcp2.createResource(modelContainer);
result = lcp2.verify();
assertEquals(1, result.size());
LineCharPointer lcp3 = new LineCharPointer(REFERENCED1, -1);
lcp3.createResource(modelContainer);
result = lcp3.verify();
assertEquals(1, result.size());
}
/**
* Test method for {@link org.spdx.rdfparser.model.pointer.LineCharPointer#equivalent(org.spdx.rdfparser.model.IRdfModel)}.
* @throws InvalidSPDXAnalysisException
*/
@Test
public void testEquivalent() throws InvalidSPDXAnalysisException {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
LineCharPointer lcp2 = new LineCharPointer(REFERENCED1, 15);
assertTrue(lcp.equivalent(lcp2));
lcp.createResource(modelContainer);
assertTrue(lcp.equivalent(lcp2));
lcp2.createResource(modelContainer);
assertTrue(lcp.equivalent(lcp2));
LineCharPointer lcp3 = new LineCharPointer(REFERENCED1, 55);
lcp3.createResource(modelContainer);
assertFalse(lcp.equivalent(lcp3));
assertFalse(lcp3.equivalent(lcp));
LineCharPointer lcp4 = new LineCharPointer(REFERENCED2, 15);
lcp4.createResource(modelContainer);
assertFalse(lcp.equivalent(lcp4));
assertFalse(lcp4.equivalent(lcp));
}
/**
* Test method for {@link org.spdx.rdfparser.model.pointer.LineCharPointer#setLineNumber(java.lang.Integer)}.
* @throws InvalidSPDXAnalysisException
*/
@Test
public void testSetLineNumber() throws InvalidSPDXAnalysisException {
LineCharPointer bop = new LineCharPointer(REFERENCED1, 15);
assertEquals(new Integer(15), bop.getLineNumber());
Resource r = bop.createResource(modelContainer);
assertEquals(new Integer(15), bop.getLineNumber());
LineCharPointer bop2 = new LineCharPointer(modelContainer, r.asNode());
assertEquals(new Integer(15), bop2.getLineNumber());
bop.setLineNumber(55);
assertEquals(new Integer(55), bop.getLineNumber());
assertEquals(new Integer(55), bop2.getLineNumber());
}
/**
* Test method for {@link org.spdx.rdfparser.model.pointer.SinglePointer#setReference(org.spdx.rdfparser.model.SpdxElement)}.
* @throws InvalidSPDXAnalysisException
*/
@Test
public void testSetReference() throws InvalidSPDXAnalysisException {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
assertEquals(REFERENCED1.getName(), lcp.getReference().getName());
Resource r = lcp.createResource(modelContainer);
assertEquals(REFERENCED1.getName(), lcp.getReference().getName());
LineCharPointer lcp2 = new LineCharPointer(modelContainer, r.asNode());
assertEquals(REFERENCED1.getName(), lcp2.getReference().getName());
lcp.setReference(REFERENCED2);
assertEquals(REFERENCED2.getName(), lcp.getReference().getName());
assertEquals(REFERENCED2.getName(), lcp2.getReference().getName());
}
@Test
public void testClone() throws InvalidSPDXAnalysisException {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
lcp.createResource(modelContainer);
LineCharPointer lcp2 = lcp.clone();
lcp2.createResource(modelContainer);
assertTrue(lcp2.equivalent(lcp2));
lcp2.getReference().setName("New Name");
assertFalse(lcp2.equivalent(lcp));
}
@Test
public void testCompareTo() {
LineCharPointer lcp = new LineCharPointer(REFERENCED1, 15);
LineCharPointer lcp2 = new LineCharPointer(REFERENCED1, 15);
LineCharPointer lcp3 = new LineCharPointer(REFERENCED2, 15);
LineCharPointer lcp4 = new LineCharPointer(REFERENCED1, 18);
assertEquals(0, lcp.compareTo(lcp2));
assertTrue(lcp.compareTo(lcp3) < 0);
assertTrue(lcp4.compareTo(lcp) > 0);
}
}
| apache-2.0 |
LorenzReinhart/ONOSnew | providers/openflow/group/src/test/java/org/onosproject/provider/of/group/impl/OpenFlowGroupProviderTest.java | 13322 | /*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.of.group.impl;
import com.google.common.collect.Lists;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.core.GroupId;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.group.DefaultGroupBucket;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.group.GroupOperation;
import org.onosproject.net.group.GroupOperations;
import org.onosproject.net.group.GroupProvider;
import org.onosproject.net.group.GroupProviderRegistry;
import org.onosproject.net.group.GroupProviderService;
import org.onosproject.net.provider.AbstractProviderService;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.openflow.controller.Dpid;
import org.onosproject.openflow.controller.OpenFlowController;
import org.onosproject.openflow.controller.OpenFlowEventListener;
import org.onosproject.openflow.controller.OpenFlowMessageListener;
import org.onosproject.openflow.controller.OpenFlowSwitch;
import org.onosproject.openflow.controller.OpenFlowSwitchListener;
import org.onosproject.openflow.controller.PacketListener;
import org.onosproject.openflow.controller.RoleState;
import org.projectfloodlight.openflow.protocol.OFFactories;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupMod;
import org.projectfloodlight.openflow.protocol.OFGroupModFailedCode;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupType;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFMeterFeatures;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.protocol.errormsg.OFGroupModFailedErrorMsg;
import org.projectfloodlight.openflow.types.OFGroup;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.*;
public class OpenFlowGroupProviderTest {
OpenFlowGroupProvider provider = new OpenFlowGroupProvider();
private final OpenFlowController controller = new TestController();
GroupProviderRegistry providerRegistry = new TestGroupProviderRegistry();
GroupProviderService providerService;
private DeviceId deviceId = DeviceId.deviceId("of:0000000000000001");
private Dpid dpid1 = Dpid.dpid(deviceId.uri());
@Before
public void setUp() {
provider.controller = controller;
provider.providerRegistry = providerRegistry;
provider.activate();
}
@Test
public void basics() {
assertNotNull("registration expected", providerService);
assertEquals("incorrect provider", provider, providerService.provider());
}
@Test
public void addGroup() {
GroupId groupId = new GroupId(1);
List<GroupBucket> bucketList = Lists.newArrayList();
TrafficTreatment.Builder builder = DefaultTrafficTreatment.builder();
builder.setOutput(PortNumber.portNumber(1));
GroupBucket bucket =
DefaultGroupBucket.createSelectGroupBucket(builder.build());
bucketList.add(bucket);
GroupBuckets buckets = new GroupBuckets(bucketList);
List<GroupOperation> operationList = Lists.newArrayList();
GroupOperation operation = GroupOperation.createAddGroupOperation(groupId,
GroupDescription.Type.SELECT, buckets);
operationList.add(operation);
GroupOperations operations = new GroupOperations(operationList);
provider.performGroupOperation(deviceId, operations);
final Dpid dpid = Dpid.dpid(deviceId.uri());
TestOpenFlowSwitch sw = (TestOpenFlowSwitch) controller.getSwitch(dpid);
assertNotNull("Switch should not be nul", sw);
assertNotNull("OFGroupMsg should not be null", sw.msg);
}
@Test
public void groupModFailure() {
TestOpenFlowGroupProviderService testProviderService =
(TestOpenFlowGroupProviderService) providerService;
GroupId groupId = new GroupId(1);
List<GroupBucket> bucketList = Lists.newArrayList();
TrafficTreatment.Builder builder = DefaultTrafficTreatment.builder();
builder.setOutput(PortNumber.portNumber(1));
GroupBucket bucket =
DefaultGroupBucket.createSelectGroupBucket(builder.build());
bucketList.add(bucket);
GroupBuckets buckets = new GroupBuckets(bucketList);
List<GroupOperation> operationList = Lists.newArrayList();
GroupOperation operation = GroupOperation.createAddGroupOperation(groupId,
GroupDescription.Type.SELECT, buckets);
operationList.add(operation);
GroupOperations operations = new GroupOperations(operationList);
provider.performGroupOperation(deviceId, operations);
OFGroupModFailedErrorMsg.Builder errorBuilder =
OFFactories.getFactory(OFVersion.OF_13).errorMsgs().buildGroupModFailedErrorMsg();
OFGroupMod.Builder groupBuilder = OFFactories.getFactory(OFVersion.OF_13).buildGroupModify();
groupBuilder.setGroupType(OFGroupType.ALL);
groupBuilder.setGroup(OFGroup.of(1));
errorBuilder.setCode(OFGroupModFailedCode.GROUP_EXISTS);
errorBuilder.setXid(provider.getXidAndAdd(0) - 1);
controller.processPacket(dpid1, errorBuilder.build());
assertNotNull("Operation failed should not be null",
testProviderService.failedOperation);
}
@Test
public void groupStatsEvent() {
TestOpenFlowGroupProviderService testProviderService =
(TestOpenFlowGroupProviderService) providerService;
OFGroupStatsReply.Builder rep1 =
OFFactories.getFactory(OFVersion.OF_13).buildGroupStatsReply();
rep1.setXid(1);
controller.processPacket(dpid1, rep1.build());
OFGroupDescStatsReply.Builder rep2 =
OFFactories.getFactory(OFVersion.OF_13).buildGroupDescStatsReply();
assertNull("group entries is not set yet", testProviderService.getGroupEntries());
rep2.setXid(2);
controller.processPacket(dpid1, rep2.build());
assertNotNull("group entries should be set", testProviderService.getGroupEntries());
}
@After
public void tearDown() {
provider.deactivate();
provider.providerRegistry = null;
provider.controller = null;
}
private class TestOpenFlowGroupProviderService
extends AbstractProviderService<GroupProvider>
implements GroupProviderService {
Collection<Group> groups = null;
GroupOperation failedOperation = null;
protected TestOpenFlowGroupProviderService(GroupProvider provider) {
super(provider);
}
@Override
public void groupOperationFailed(DeviceId deviceId, GroupOperation operation) {
this.failedOperation = operation;
}
@Override
public void pushGroupMetrics(DeviceId deviceId, Collection<Group> groupEntries) {
this.groups = groupEntries;
}
@Override
public void notifyOfFailovers(Collection<Group> groups) {
}
public Collection<Group> getGroupEntries() {
return groups;
}
}
private class TestController implements OpenFlowController {
OpenFlowEventListener eventListener = null;
List<OpenFlowSwitch> switches = Lists.newArrayList();
public TestController() {
OpenFlowSwitch testSwitch = new TestOpenFlowSwitch();
switches.add(testSwitch);
}
@Override
public void addListener(OpenFlowSwitchListener listener) {
}
@Override
public void removeListener(OpenFlowSwitchListener listener) {
}
@Override
public void addMessageListener(OpenFlowMessageListener listener) {
}
@Override
public void removeMessageListener(OpenFlowMessageListener listener) {
}
@Override
public void addPacketListener(int priority, PacketListener listener) {
}
@Override
public void removePacketListener(PacketListener listener) {
}
@Override
public void addEventListener(OpenFlowEventListener listener) {
this.eventListener = listener;
}
@Override
public void removeEventListener(OpenFlowEventListener listener) {
}
@Override
public void write(Dpid dpid, OFMessage msg) {
}
@Override
public CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg) {
return null;
}
@Override
public void processPacket(Dpid dpid, OFMessage msg) {
eventListener.handleMessage(dpid, msg);
}
@Override
public void setRole(Dpid dpid, RoleState role) {
}
@Override
public Iterable<OpenFlowSwitch> getSwitches() {
return switches;
}
@Override
public Iterable<OpenFlowSwitch> getMasterSwitches() {
return null;
}
@Override
public Iterable<OpenFlowSwitch> getEqualSwitches() {
return null;
}
@Override
public OpenFlowSwitch getSwitch(Dpid dpid) {
return switches.get(0);
}
@Override
public OpenFlowSwitch getMasterSwitch(Dpid dpid) {
return null;
}
@Override
public OpenFlowSwitch getEqualSwitch(Dpid dpid) {
return null;
}
}
private class TestGroupProviderRegistry implements GroupProviderRegistry {
@Override
public GroupProviderService register(GroupProvider provider) {
providerService = new TestOpenFlowGroupProviderService(provider);
return providerService;
}
@Override
public void unregister(GroupProvider provider) {
}
@Override
public Set<ProviderId> getProviders() {
return null;
}
}
private class TestOpenFlowSwitch implements OpenFlowSwitch {
OFMessage msg = null;
@Override
public void sendMsg(OFMessage msg) {
this.msg = msg;
}
@Override
public void sendMsg(List<OFMessage> msgs) {
}
@Override
public void handleMessage(OFMessage fromSwitch) {
}
@Override
public void setRole(RoleState role) {
}
@Override
public RoleState getRole() {
return null;
}
@Override
public List<OFPortDesc> getPorts() {
return null;
}
@Override
public OFMeterFeatures getMeterFeatures() {
return null;
}
@Override
public OFFactory factory() {
return OFFactories.getFactory(OFVersion.OF_13);
}
@Override
public String getStringId() {
return null;
}
@Override
public long getId() {
return 0;
}
@Override
public String manufacturerDescription() {
return null;
}
@Override
public String datapathDescription() {
return null;
}
@Override
public String hardwareDescription() {
return null;
}
@Override
public String softwareDescription() {
return null;
}
@Override
public String serialNumber() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public void disconnectSwitch() {
}
@Override
public void returnRoleReply(RoleState requested, RoleState response) {
}
@Override
public Device.Type deviceType() {
return Device.Type.SWITCH;
}
@Override
public String channelId() {
return null;
}
}
} | apache-2.0 |
tanhaichao/leopard-data | leopard-redis/src/main/java/io/leopard/redis/memory/IRedisHashes.java | 715 | package io.leopard.redis.memory;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface IRedisHashes extends IRedisKey {
Long hset(String key, String field, String value);
String hget(String key, String field);
Long hsetnx(String key, String field, String value);
String hmset(String key, Map<String, String> hash);
List<String> hmget(String key, String... fields);
Long hincrBy(String key, String field, long value);
Boolean hexists(String key, String field);
Long hdel(String key, String... field);
Long hlen(String key);
Set<String> hkeys(String key);
List<String> hvals(String key);
Map<String, String> hgetAll(String key);
}
| apache-2.0 |