text
stringlengths 7
1.01M
|
|---|
package com.compomics.coss.controller.matching;
import com.compomics.ms2io.model.Peak;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
*
* @author Genet
*/
public class MatchedPeaksNGTest {
public MatchedPeaksNGTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
/**
* Test of matchedPeaks method, of class MatchedPeaks.
*/
@Test
public void testMatchedPeaks() {
System.out.println("matchedPeaks");
List<Double> ar1 = null;
List<Double> ar2 = null;
int m = 0;
int n = 0;
double fragTolerance = 0.0;
MatchedPeaks instance = new MatchedPeaks();
int[] expResult = null;
int[] result = instance.matchedPeaks(ar1, ar2, m, n, fragTolerance);
assertEquals(result, expResult);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getMatchedPeaks method, of class MatchedPeaks.
*/
@Test
public void testGetMatchedPeaks() {
System.out.println("getMatchedPeaks");
ArrayList<Peak> filteredExpMS2_1 = null;
ArrayList<Peak> filteredExpMS2_2 = null;
double fragTolerance = 0.0;
MatchedPeaks instance = new MatchedPeaks();
Map expResult = null;
Map result = null;// instance.getMatchedPeaks(filteredExpMS2_1, filteredExpMS2_2, fragTolerance);
assertEquals(result, expResult);
}
}
|
package io.freefair.gradle.plugins.android.quality;
import com.android.build.gradle.api.BaseVariant;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Collection;
/**
* Copy of {@link org.gradle.api.plugins.quality.CodeQualityExtension} which uses {@link BaseVariant variants}
*
* @author Lars Grefer
* @see org.gradle.api.plugins.quality.CodeQualityExtension
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class VariantBasedCodeQualityExtension extends AndroidCodeQualityExtension {
private Collection<BaseVariant> variants;
}
|
class Exercicio09 {
public static void main(String[] args) {
int n = 3;
int[][] myArray = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
myArray[i][j] = myFunc.randInt(0, n * n);
System.out.print(myArray[i][j] + " ");
if ((j + 1) % 3 == 0) {
System.out.print("\n");
}
}
}
System.out.println("-----");
for (int i = 0; i < n; i++) {
System.out.print(myArray[i][i] + " " );
}
}
}
|
package com.sequenceiq.cloudbreak.core.flow2.stack.upscale;
import com.sequenceiq.flow.core.FlowState;
import com.sequenceiq.flow.core.RestartAction;
import com.sequenceiq.cloudbreak.core.flow2.restart.DisableOnGCPRestartAction;
import com.sequenceiq.cloudbreak.core.flow2.restart.FillInMemoryStateStoreRestartAction;
public enum StackUpscaleState implements FlowState {
INIT_STATE,
UPSCALE_FAILED_STATE,
UPSCALE_PREVALIDATION_STATE,
ADD_INSTANCES_STATE(DisableOnGCPRestartAction.class),
ADD_INSTANCES_FINISHED_STATE,
EXTEND_METADATA_STATE,
EXTEND_METADATA_FINISHED_STATE,
GATEWAY_TLS_SETUP_STATE,
RE_REGISTER_WITH_CLUSTER_PROXY_STATE,
BOOTSTRAP_NEW_NODES_STATE,
EXTEND_HOST_METADATA_STATE,
EXTEND_HOST_METADATA_FINISHED_STATE,
FINAL_STATE;
private Class<? extends RestartAction> restartAction = FillInMemoryStateStoreRestartAction.class;
StackUpscaleState() {
}
StackUpscaleState(Class<? extends RestartAction> restartAction) {
this.restartAction = restartAction;
}
@Override
public Class<? extends RestartAction> restartAction() {
return restartAction;
}
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v201905;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BillingSource.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="BillingSource">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CONTRACTED"/>
* <enumeration value="DFP_VOLUME"/>
* <enumeration value="THIRD_PARTY_VOLUME"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "BillingSource")
@XmlEnum
public enum BillingSource {
/**
*
* Charge based on the quantity of impressions, clicks, or days booked, regardless of
* what actually delivered.
*
*
*/
CONTRACTED,
/**
*
* Charge based on what actually delivered, as counted by Ad Manager.
*
*
*/
DFP_VOLUME,
/**
*
* Charge based on what actually delivered, as counted by the third party ads server.
*
*
*/
THIRD_PARTY_VOLUME,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static BillingSource fromValue(String v) {
return valueOf(v);
}
}
|
package dll.library;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.win32.StdCallLibrary;
import java.io.File;
/**
* @描述: SDK对外开放的实现各种业务的同步接口
* 包含 sdk_func.h、sdk_tollgate_func.h
* 他们的实现都在imos_sdk.dll中
* @作者: REN
* @时间: 2019/1/3 15:32
*/
public interface IMOSLibrary extends StdCallLibrary {
public static final String JNA_LIBRARY_NAME = "imos_sdk";
//设置为false
String result = System.setProperty("jna.protected","false");
String debug = System.setProperty("jna.debug_load", "true");
public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance("imos"+ File.separator+"redist"+File.separator+IMOSLibrary.JNA_LIBRARY_NAME);
public static final IMOSLibrary INSTANCE = Native.load(HWPuSDKLibrary.JNA_LIBRARY_NAME, IMOSLibrary.class);
}
|
package com.xiaochen.progressroundbutton;
/**
* Created by tanfujun on 10/26/16.
*/
public interface ButtonController {
int getPressedColor(int color);
int getLighterColor(int color);
int getDarkerColor(int color);
boolean enablePress();
boolean enableGradient();
}
|
package utils;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class DateUtils {
public static LocalDateTime toLocalDateTime(Timestamp date) {
return LocalDateTime.ofEpochSecond(date.getTime(), 0, ZoneOffset.UTC);
}
}
|
package org.jboss.resteasy.test.client;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.logging.Logger;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import javax.ws.rs.client.ClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClientEngine;
import org.jboss.resteasy.test.client.resource.ClientExecutorShutdownTestResource;
import org.jboss.resteasy.spi.HttpResponseCodes;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import static org.junit.Assert.fail;
/**
* @tpSubChapter Resteasy-client
* @tpChapter Client tests
* @tpSince RESTEasy 3.0.16
* @tpTestCaseDetails https://issues.jboss.org/browse/RESTEASY-621
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ClientExecutorShutdownTest extends ClientTestBase{
private static Logger log = Logger.getLogger(ClientExecutorShutdownTest.class);
@Path("/test")
public interface TestService {
@POST
Response post();
}
@Deployment
public static Archive<?> deploy() {
WebArchive war = TestUtil.prepareArchive(ClientExecutorShutdownTest.class.getSimpleName());
war.addClass(ClientExecutorShutdownTest.class);
war.addClass(ClientTestBase.class);
return TestUtil.finishContainerPrepare(war, null, ClientExecutorShutdownTestResource.class);
}
/**
* @tpTestDetails Verify that if ApacheHttpClient4Executor creates its own HttpClient,
* then ApacheHttpClient4Executor.finalize() will close the HttpClient's
* org.apache.http.conn.ClientConnectionManager.
* @tpPassCrit ApacheHttpClient4Executor.finalize() will close the connection
* @tpSince RESTEasy 3.0.16
*/
@Test
public void testApacheHttpClient4ExecutorNonSharedHttpClientFinalize() throws Throwable {
ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
ResteasyClient client = ((ResteasyClientBuilder)ClientBuilder.newBuilder()).httpEngine(engine).build();
Response response = client.target(generateURL("/test")).request().post(null);
Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
engine.finalize();
HttpClient httpClient = engine.getHttpClient();
HttpPost post = new HttpPost(generateURL("/test"));
try {
httpClient.execute(post);
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
log.info("Got expected IllegalStateException");
}
}
/**
* @tpTestDetails Verify that if ApacheHttpClient4Executor creates its own HttpClient,
* then ApacheHttpClient4Executor.close() will close the HttpClient's
* org.apache.http.conn.ClientConnectionManager.
* @tpPassCrit ApacheHttpClient4Executor.close() will close the connection
* @tpSince RESTEasy 3.0.16
*/
@Test
public void testApacheHttpClient4ExecutorNonSharedHttpClientClose() throws Throwable {
ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine();
ResteasyClient client = ((ResteasyClientBuilder)ClientBuilder.newBuilder()).httpEngine(engine).build();
Response response = client.target(generateURL("/test")).request().post(null);
Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
engine.close();
HttpClient httpClient = engine.getHttpClient();
HttpPost post = new HttpPost(generateURL("/test"));
try {
httpClient.execute(post);
fail("Expected IllegalStateException");
} catch (IllegalStateException e) {
log.info("Got expected IllegalStateException");
}
}
/**
* @tpTestDetails Verify that if ApacheHttpClient4Executor receives an HttpClient through
* a constructor, then ApacheHttpClient4Executor.finalize() will not close the
* HttpClient's org.apache.http.conn.ClientConnectionManager.
* @tpPassCrit ApacheHttpClient4Executor.finalize() will not close the connection
* @tpSince RESTEasy 3.0.16
*/
@Test
public void testApacheHttpClient4ExecutorSharedHttpClientFinalize() throws Throwable {
HttpClient httpClient = HttpClientBuilder.create().build();
ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(httpClient, false);
ResteasyClient client = ((ResteasyClientBuilder)ClientBuilder.newBuilder()).httpEngine(engine).build();
Response response = client.target(generateURL("/test")).request().post(null);
Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
engine.finalize();
Assert.assertEquals("Original httpclient and engine httpclient are not the same instance",
httpClient, engine.getHttpClient());
HttpPost post = new HttpPost(generateURL("/test"));
HttpResponse httpResponse = httpClient.execute(post);
Assert.assertEquals("The httpclient was closed and it shouldn't", HttpResponseCodes.SC_NO_CONTENT,
httpResponse.getStatusLine().getStatusCode());
}
/**
* @tpTestDetails Verify that if ApacheHttpClient4Executor receives an HttpClient through
* a constructor, then ApacheHttpClient4Executor.close() will not close the
* HttpClient's org.apache.http.conn.ClientConnectionManager.
* @tpPassCrit ApacheHttpClient4Executor.close() will not close the connection
* @tpSince RESTEasy 3.0.16
*/
@Test
public void testApacheHttpClient4ExecutorSharedHttpClientClose() throws Throwable {
HttpClient httpClient = HttpClientBuilder.create().build();
ApacheHttpClient43Engine engine = new ApacheHttpClient43Engine(httpClient, false);
ResteasyClient client = ((ResteasyClientBuilder)ClientBuilder.newBuilder()).httpEngine(engine).build();
Response response = client.target(generateURL("/test")).request().post(null);
Assert.assertEquals("Original httpclient and engine httpclient are not the same instance",
HttpResponseCodes.SC_NO_CONTENT, response.getStatus());
engine.close();
Assert.assertEquals(httpClient, engine.getHttpClient());
HttpPost post = new HttpPost(generateURL("/test"));
HttpResponse httpResponse = httpClient.execute(post);
Assert.assertEquals("The httpclient was closed and it shouldn't", HttpResponseCodes.SC_NO_CONTENT,
httpResponse.getStatusLine().getStatusCode());
}
}
|
package com.microsoft.azure.mobile.cordova;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.push.Push;
public class AppCenterPushPlugin extends CordovaPlugin {
private static final String SENDER_ID = "FIREBASE_SENDER_ID";
private CordovaPushListener listener;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
AppCenterShared.configureAppCenter(
cordova.getActivity().getApplication(),
webView.getPreferences());
// For some reason Cordova reads SENDER_ID preference as double.
// Because of this Pushes does not work properly,
// as workaround SENDER_ID value should be wrapped by single quotes.
String senderId = webView.getPreferences().getString(SENDER_ID, null).replace("'", "");
Push.setSenderId(senderId);
listener = new CordovaPushListener();
Push.setListener(listener);
AppCenter.start(Push.class);
}
@Override
public boolean execute(String action, JSONArray args,
final CallbackContext callbackContext) throws JSONException {
if (action.equals("isEnabled")) {
AppCenterUtils.sendBooleanPluginResultFromFuture(Push.isEnabled(), callbackContext);
return true;
} else if (action.equals("setEnabled")) {
Boolean enabled = args.getBoolean(0);
AppCenterUtils.sendVoidPluginResultFromFuture(Push.setEnabled(enabled), callbackContext);
return true;
} else if (action.equals("sendAndClearInitialNotification")) {
listener.sendAndClearInitialNotification();
return true;
} else if (action.equals("registerEventsCallback")) {
listener.setEventsCallbackContext(callbackContext);
return true;
}
return false;
}
}
|
/*
* Copyright 2003-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.ast.expr;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.MethodNode;
/**
* A method call on an object or class
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class MethodCallExpression extends Expression {
private Expression objectExpression;
private Expression method;
private Expression arguments;
private boolean spreadSafe = false;
private boolean safe = false;
private boolean implicitThis;
// type spec for generics
private GenericsType[] genericsTypes = null;
private boolean usesGenerics = false;
private MethodNode target;
public static final Expression NO_ARGUMENTS = new TupleExpression();
public MethodCallExpression(Expression objectExpression, String method, Expression arguments) {
this(objectExpression,new ConstantExpression(method),arguments);
}
public MethodCallExpression(Expression objectExpression, Expression method, Expression arguments) {
this.objectExpression = objectExpression;
this.method = method;
if (!(arguments instanceof TupleExpression)){
this.arguments = new TupleExpression(arguments);
} else {
this.arguments = arguments;
}
//TODO: set correct type here
// if setting type and a methodcall is the last expression in a method,
// then the method will return null if the method itself is not void too!
// (in bytecode after call: aconst_null, areturn)
this.setType(ClassHelper.DYNAMIC_TYPE);
this.setImplicitThis(true);
}
public void visit(GroovyCodeVisitor visitor) {
visitor.visitMethodCallExpression(this);
}
public Expression transformExpression(ExpressionTransformer transformer) {
MethodCallExpression answer =
new MethodCallExpression(transformer.transform(objectExpression), transformer.transform(method), transformer.transform(arguments));
answer.setSafe(safe);
answer.setSpreadSafe(spreadSafe);
answer.setImplicitThis(implicitThis);
answer.setSourcePosition(this);
answer.setMethodTarget(target);
answer.copyNodeMetaData(this);
return answer;
}
public Expression getArguments() {
return arguments;
}
public void setArguments(Expression arguments) {
if (!(arguments instanceof TupleExpression)){
this.arguments = new TupleExpression(arguments);
} else {
this.arguments = arguments;
}
}
public Expression getMethod() {
return method;
}
public void setMethod(Expression method) {
this.method = method;
}
/**
* This method returns the method name as String if it is no dynamic
* calculated method name, but a constant.
*/
public String getMethodAsString() {
if (! (method instanceof ConstantExpression)) return null;
ConstantExpression constant = (ConstantExpression) method;
return constant.getText();
}
public void setObjectExpression(Expression objectExpression) {
this.objectExpression = objectExpression;
}
public Expression getObjectExpression() {
return objectExpression;
}
public String getText() {
String object = objectExpression.getText();
String meth = method.getText();
String args = arguments.getText();
String spread = spreadSafe ? "*" : "";
String dereference = safe ? "?" : "";
return object + spread + dereference + "." + meth + args;
}
/**
* @return is this a safe method call, i.e. if true then if the source object is null
* then this method call will return null rather than throwing a null pointer exception
*/
public boolean isSafe() {
return safe;
}
public void setSafe(boolean safe) {
this.safe = safe;
}
public boolean isSpreadSafe() {
return spreadSafe;
}
public void setSpreadSafe(boolean value) {
spreadSafe = value;
}
/**
* @return true if no object expression was specified otherwise if
* some expression was specified for the object on which to evaluate
* the method then return false
*/
public boolean isImplicitThis() {
return implicitThis;
}
public void setImplicitThis(boolean implicitThis) {
this.implicitThis = implicitThis;
}
public String toString() {
return super.toString()
+ "[object: "
+ objectExpression
+ " method: "
+ method
+ " arguments: "
+ arguments
+ "]";
}
public GenericsType[] getGenericsTypes() {
return genericsTypes;
}
public void setGenericsTypes(GenericsType[] genericsTypes) {
usesGenerics = usesGenerics || genericsTypes != null;
this.genericsTypes = genericsTypes;
}
public boolean isUsingGenerics() {
return usesGenerics;
}
/**
* Sets a method call target for a direct method call.
* WARNING: A method call made this way will run outside of the MOP!
* @param mn the target as MethodNode, mn==null means no target
*/
public void setMethodTarget(MethodNode mn) {
this.target = mn;
if (mn!=null) {
setType(target.getReturnType());
} else {
setType(ClassHelper.OBJECT_TYPE);
}
}
/**
* @return the target as method node if set
*/
public MethodNode getMethodTarget() {
return target;
}
}
|
package com.macro.mall.dao;
import com.macro.mall.dto.ProductAttrInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 自定义商品属性Dao
* Created by macro on 2018/5/23.
*/
public interface PmsProductAttributeDao {
/**
* 获取商品属性信息
*/
List<ProductAttrInfo> getProductAttrInfo(@Param("id") Long productCategoryId);
}
|
package com.burhanrashid52.photoediting;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
public class PropertiesBSFragment extends BottomSheetDialogFragment implements SeekBar.OnSeekBarChangeListener {
public PropertiesBSFragment() {
// Required empty public constructor
}
private Properties mProperties;
public interface Properties {
void onColorChanged(int colorCode);
void onOpacityChanged(int opacity);
void onBrushSizeChanged(int brushSize);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bottom_properties_dialog, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView rvColor = view.findViewById(R.id.rvColors);
SeekBar sbOpacity = view.findViewById(R.id.sbOpacity);
SeekBar sbBrushSize = view.findViewById(R.id.sbSize);
sbOpacity.setOnSeekBarChangeListener(this);
sbBrushSize.setOnSeekBarChangeListener(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
rvColor.setLayoutManager(layoutManager);
rvColor.setHasFixedSize(true);
ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(getActivity());
colorPickerAdapter.setOnColorPickerClickListener(new ColorPickerAdapter.OnColorPickerClickListener() {
@Override
public void onColorPickerClickListener(int colorCode) {
if (mProperties != null) {
dismiss();
mProperties.onColorChanged(colorCode);
}
}
});
rvColor.setAdapter(colorPickerAdapter);
}
public void setPropertiesChangeListener(Properties properties) {
mProperties = properties;
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
switch (seekBar.getId()) {
case R.id.sbOpacity:
if (mProperties != null) {
mProperties.onOpacityChanged(i);
}
break;
case R.id.sbSize:
if (mProperties != null) {
mProperties.onBrushSizeChanged(i);
}
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
|
//
// MIT License
//
// Copyright (c) 2021 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package cloud.commandframework.fabric.argument;
import cloud.commandframework.ArgumentDescription;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.brigadier.argument.WrappedBrigadierParser;
import cloud.commandframework.context.CommandContext;
import io.leangen.geantyref.TypeToken;
import net.minecraft.commands.arguments.coordinates.SwizzleArgument;
import net.minecraft.core.Direction;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
/**
* An argument for a set of {@link net.minecraft.core.Direction.Axis axes}, described in Vanilla as a "swizzle".
*
* @param <C> the sender type
* @since 1.5.0
*/
public final class AxisArgument<C> extends CommandArgument<C, EnumSet<Direction.Axis>> {
private static final TypeToken<EnumSet<Direction.Axis>> TYPE = new TypeToken<EnumSet<Direction.Axis>>() {
};
AxisArgument(
final boolean required,
final @NonNull String name,
final @NonNull String defaultValue,
final @Nullable BiFunction<CommandContext<C>, String, List<String>> suggestionsProvider,
final @NonNull ArgumentDescription defaultDescription
) {
super(
required,
name,
new WrappedBrigadierParser<>(SwizzleArgument.swizzle()),
defaultValue,
TYPE,
suggestionsProvider,
defaultDescription
);
}
/**
* Create a new {@link Builder}.
*
* @param name Name of the argument
* @param <C> Command sender type
* @return Created builder
* @since 1.5.0
*/
public static <C> @NonNull Builder<C> builder(final @NonNull String name) {
return new Builder<>(name);
}
/**
* Create a new required {@link AxisArgument}.
*
* @param name Component name
* @param <C> Command sender type
* @return Created argument
* @since 1.5.0
*/
public static <C> @NonNull AxisArgument<C> of(final @NonNull String name) {
return AxisArgument.<C>builder(name).asRequired().build();
}
/**
* Create a new optional {@link AxisArgument}.
*
* @param name Component name
* @param <C> Command sender type
* @return Created argument
* @since 1.5.0
*/
public static <C> @NonNull AxisArgument<C> optional(final @NonNull String name) {
return AxisArgument.<C>builder(name).asOptional().build();
}
/**
* Create a new optional {@link AxisArgument} with the specified default value.
*
* @param name Argument name
* @param defaultValue Default axes to include
* @param <C> Command sender type
* @return Created argument
* @since 1.5.0
*/
public static <C> @NonNull AxisArgument<C> optional(
final @NonNull String name,
final @NonNull Set<Direction.@NonNull Axis> defaultValue
) {
return AxisArgument.<C>builder(name).asOptionalWithDefault(defaultValue).build();
}
/**
* Builder for {@link AxisArgument}.
*
* @param <C> sender type
* @since 1.5.0
*/
public static final class Builder<C> extends TypedBuilder<C, EnumSet<Direction.Axis>, Builder<C>> {
Builder(final @NonNull String name) {
super(TYPE, name);
}
/**
* Build a new {@link AxisArgument}.
*
* @return Constructed argument
* @since 1.5.0
*/
@Override
public @NonNull AxisArgument<C> build() {
return new AxisArgument<>(
this.isRequired(),
this.getName(),
this.getDefaultValue(),
this.getSuggestionsProvider(),
this.getDefaultDescription()
);
}
/**
* Sets the command argument to be optional, with the specified default value.
*
* @param defaultValue default value
* @return this builder
* @see CommandArgument.Builder#asOptionalWithDefault(String)
* @since 1.5.0
*/
public @NonNull Builder<C> asOptionalWithDefault(final @NonNull Set<Direction.@NonNull Axis> defaultValue) {
if (defaultValue.isEmpty()) {
throw new IllegalArgumentException("Default value must include at least one Axis!");
}
final StringBuilder builder = new StringBuilder();
for (final Direction.Axis axis : defaultValue) {
builder.append(axis.getName());
}
return this.asOptionalWithDefault(builder.toString());
}
}
}
|
/*
* Copyright 2020 ConsenSys AG.
*
* 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 tech.pegasys.teku.ssz.backing.containers;
import tech.pegasys.teku.ssz.backing.SszData;
import tech.pegasys.teku.ssz.backing.tree.TreeNode;
import tech.pegasys.teku.ssz.backing.view.AbstractSszImmutableContainer;
/** Autogenerated by tech.pegasys.teku.ssz.backing.ContainersGenerator */
public class Container7<
C extends Container7<C, V0, V1, V2, V3, V4, V5, V6>,
V0 extends SszData,
V1 extends SszData,
V2 extends SszData,
V3 extends SszData,
V4 extends SszData,
V5 extends SszData,
V6 extends SszData>
extends AbstractSszImmutableContainer {
protected Container7(ContainerSchema7<C, V0, V1, V2, V3, V4, V5, V6> schema) {
super(schema);
}
protected Container7(
ContainerSchema7<C, V0, V1, V2, V3, V4, V5, V6> schema, TreeNode backingNode) {
super(schema, backingNode);
}
protected Container7(
ContainerSchema7<C, V0, V1, V2, V3, V4, V5, V6> schema,
V0 arg0,
V1 arg1,
V2 arg2,
V3 arg3,
V4 arg4,
V5 arg5,
V6 arg6) {
super(schema, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
}
protected V0 getField0() {
return getAny(0);
}
protected V1 getField1() {
return getAny(1);
}
protected V2 getField2() {
return getAny(2);
}
protected V3 getField3() {
return getAny(3);
}
protected V4 getField4() {
return getAny(4);
}
protected V5 getField5() {
return getAny(5);
}
protected V6 getField6() {
return getAny(6);
}
}
|
package top.ningg.design;
/**
* 单例模式: 懒汉模式.(延迟加载对象)
*
* 参考: https://www.cnblogs.com/garryfu/p/7976546.html
*/
public class Singleton {
// 构造方法: 私有
private Singleton() {
}
// 对象实例: 不创建
private static Singleton singleton = null;
// 对外方法: 加锁
public static synchronized Singleton getInstance() {
if (null == singleton) {
singleton = new Singleton();
}
return singleton;
}
// 改进并发度:获取实例
public static Singleton getInstanceHighPerformance() {
// 双重检查
if (null == singleton) {
synchronized (Singleton.class) {
singleton = new Singleton();
}
}
return singleton;
}
}
|
/**
* Copyright 2016-2017 Seznam.cz, a.s.
*
* 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 cz.seznam.euphoria.operator.test;
import cz.seznam.euphoria.core.client.dataset.Dataset;
import cz.seznam.euphoria.core.client.dataset.windowing.Session;
import cz.seznam.euphoria.core.client.dataset.windowing.Time;
import cz.seznam.euphoria.core.client.dataset.windowing.TimeInterval;
import cz.seznam.euphoria.core.client.dataset.windowing.WindowedElement;
import cz.seznam.euphoria.core.client.dataset.windowing.Windowing;
import cz.seznam.euphoria.core.client.flow.Flow;
import cz.seznam.euphoria.core.client.io.Collector;
import cz.seznam.euphoria.core.client.operator.AssignEventTime;
import cz.seznam.euphoria.core.client.operator.Join;
import cz.seznam.euphoria.core.client.operator.MapElements;
import cz.seznam.euphoria.core.client.triggers.NoopTrigger;
import cz.seznam.euphoria.core.client.triggers.Trigger;
import cz.seznam.euphoria.core.client.util.Either;
import cz.seznam.euphoria.core.client.util.Pair;
import cz.seznam.euphoria.core.client.util.Triple;
import cz.seznam.euphoria.operator.test.accumulators.SnapshotProvider;
import cz.seznam.euphoria.operator.test.junit.AbstractOperatorTest;
import cz.seznam.euphoria.operator.test.junit.Processing;
import org.junit.Test;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* Test operator {@code Join}.
*/
@Processing(Processing.Type.ALL)
public class JoinTest extends AbstractOperatorTest {
static abstract class JoinTestCase<LEFT, RIGHT, OUT> implements TestCase<OUT> {
@Override
public Dataset<OUT> getOutput(Flow flow, boolean bounded) {
Dataset<LEFT> left =
flow.createInput(getLeftInput().asListDataSource(bounded));
Dataset<RIGHT> right =
flow.createInput(getRightInput().asListDataSource(bounded));
return getOutput(left, right);
}
protected abstract Dataset<OUT> getOutput(
Dataset<LEFT> left, Dataset<RIGHT> right);
protected abstract Partitions<LEFT> getLeftInput();
protected abstract Partitions<RIGHT> getRightInput();
}
@Processing(Processing.Type.BOUNDED)
@Test
public void batchJoinOuter() {
execute(new JoinTestCase<Integer, Long, Pair<Integer, String>>() {
@Override
protected Dataset<Pair<Integer, String>> getOutput(
Dataset<Integer> left, Dataset<Long> right) {
return Join.of(left, right)
.by(e -> e, e -> (int) (e % 10))
.using((Integer l, Long r, Collector<String> c) -> c.collect(l + "+" + r))
.setPartitioner(e -> e % 2)
.outer()
.output();
}
@Override
protected Partitions<Integer> getLeftInput() {
return Partitions
.add(1, 2, 3, 0)
.add(4, 3, 2, 1)
.build();
}
@Override
protected Partitions<Long> getRightInput() {
return Partitions
.add(11L, 12L)
.add(13L, 14L, 15L)
.build();
}
@Override
public int getNumOutputPartitions() {
return 2;
}
@Override
public void validate(Partitions<Pair<Integer, String>> partitions) {
assertEquals(2, partitions.size());
List<Pair<Integer, String>> first = partitions.get(0);
assertUnorderedEquals(Arrays.asList(Pair.of(0, "0+null"),
Pair.of(2, "2+12"), Pair.of(2, "2+12"), Pair.of(4, "4+14")), first);
List<Pair<Integer, String>> second = partitions.get(1);
assertUnorderedEquals(Arrays.asList(
Pair.of(1, "1+11"), Pair.of(1, "1+11"),
Pair.of(3, "3+13"), Pair.of(3, "3+13"), Pair.of(5, "null+15")),
second);
}
});
}
@Processing(Processing.Type.BOUNDED)
@Test
public void batchJoinInner() {
execute(new JoinTestCase<Integer, Long, Pair<Integer, String>>() {
@Override
protected Dataset<Pair<Integer, String>> getOutput(
Dataset<Integer> left, Dataset<Long> right) {
return Join.of(left, right)
.by(e -> e, e -> (int) (e % 10))
.using((Integer l, Long r, Collector<String> c) -> {
c.collect(l + "+" + r);
})
.setPartitioner(e -> e % 2)
.output();
}
@Override
protected Partitions<Integer> getLeftInput() {
return Partitions
.add(1, 2, 3, 0)
.add(4, 3, 2, 1)
.build();
}
@Override
protected Partitions<Long> getRightInput() {
return Partitions
.add(11L, 12L)
.add(13L, 14L, 15L)
.build();
}
@Override
public int getNumOutputPartitions() {
return 2;
}
@Override
public void validate(Partitions<Pair<Integer, String>> partitions) {
assertEquals(2, partitions.size());
List<Pair<Integer, String>> first = partitions.get(0);
assertUnorderedEquals(Arrays.asList(
Pair.of(2, "2+12"), Pair.of(2, "2+12"), Pair.of(4, "4+14")), first);
List<Pair<Integer, String>> second = partitions.get(1);
assertUnorderedEquals(Arrays.asList(
Pair.of(1, "1+11"), Pair.of(1, "1+11"),
Pair.of(3, "3+13"), Pair.of(3, "3+13")),
second);
}
});
}
/**
* Stable windowing for test purposes.
*/
static class EvenOddWindowing
implements Windowing<Either<Integer, Long>, IntWindow> {
@Override
public Iterable<IntWindow> assignWindowsToElement(
WindowedElement<?, Either<Integer, Long>> input) {
int element;
Either<Integer, Long> unwrapped = input.getElement();
if (unwrapped.isLeft()) {
element = unwrapped.left();
} else {
element = (int) (long) unwrapped.right();
}
final int label = element % 2 == 0 ? 0 : element;
return Collections.singleton(new IntWindow(label));
}
@Override
public Trigger<IntWindow> getTrigger() {
return NoopTrigger.get();
}
}
@Test
public void windowJoin() {
execute(new JoinTestCase<Integer, Long, Pair<Integer, String>>() {
@Override
protected Dataset<Pair<Integer, String>> getOutput(
Dataset<Integer> left, Dataset<Long> right) {
return Join.of(left, right)
.by(e -> e, e -> (int) (e % 10))
.using((Integer l, Long r, Collector<String> c) -> {
c.collect(l + "+" + r);
})
.setNumPartitions(2)
.setPartitioner(e -> e % 2)
.outer()
.windowBy(new EvenOddWindowing())
.output();
}
@Override
protected Partitions<Integer> getLeftInput() {
return Partitions.add(1, 2, 3, 0, 4, 3, 2, 1, 5, 6).build();
}
@Override
protected Partitions<Long> getRightInput() {
return Partitions.add(11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L).build();
}
@Override
public int getNumOutputPartitions() {
return 2;
}
@Override
public void validate(Partitions<Pair<Integer, String>> partitions) {
assertEquals(2, partitions.size());
// all even elements for one window
// all odd elements are each element in separate window
List<Pair<Integer, String>> first = partitions.get(0);
assertUnorderedEquals(Arrays.asList(Pair.of(0, "0+null"),
Pair.of(2, "2+12"), Pair.of(2, "2+12"), Pair.of(4, "4+14"),
Pair.of(6, "6+16"), Pair.of(8, "null+18")), first);
List<Pair<Integer, String>> second = partitions.get(1);
assertUnorderedEquals(Arrays.asList(
Pair.of(1, "1+null"), Pair.of(1, "1+null"), Pair.of(1, "null+11"),
Pair.of(3, "3+null"), Pair.of(3, "3+null"), Pair.of(3, "null+13"),
Pair.of(5, "5+null"), Pair.of(5, "null+15"), Pair.of(7, "null+17")),
second);
}
});
}
// ~ all of the inputs fall into the same session window (on the same key)
// ~ we expect the result to reflect this fact
// ~ note: no early triggering
@Test
public void innerJoinOnSessionWindowingNoEarlyTriggering() {
execute(new JoinTestCase<
Pair<String, Long>,
Pair<String, Long>,
Triple<TimeInterval, String, String>>() {
@Override
protected Partitions<Pair<String, Long>> getLeftInput() {
return Partitions.add(Pair.of("fi", 1L), Pair.of("fa", 2L)).build();
}
@Override
protected Partitions<Pair<String, Long>> getRightInput() {
return Partitions.add(Pair.of("ha", 1L), Pair.of("ho", 4L)).build();
}
@Override
public int getNumOutputPartitions() {
return 1;
}
@Override
protected Dataset<Triple<TimeInterval, String, String>>
getOutput(Dataset<Pair<String, Long>> left, Dataset<Pair<String, Long>> right) {
left = AssignEventTime.of(left).using(Pair::getSecond).output();
right = AssignEventTime.of(right).using(Pair::getSecond).output();
Dataset<Pair<String, Triple<TimeInterval, String, String>>> joined =
Join.of(left, right)
.by(p -> "", p -> "")
.using((Pair<String, Long> l, Pair<String, Long> r, Collector<Triple<TimeInterval, String, String>> c) ->
c.collect(Triple.of((TimeInterval) c.getWindow(), l.getFirst(), r.getFirst())))
.windowBy(Session.of(Duration.ofMillis(10)))
.setNumPartitions(1)
.output();
return MapElements.of(joined).using(Pair::getSecond).output();
}
@Override
public void validate(Partitions<Triple<TimeInterval, String, String>> partitions) {
TimeInterval expectedWindow = new TimeInterval(1, 14);
assertUnorderedEquals(
Arrays.asList(
Triple.of(expectedWindow, "fi", "ha"),
Triple.of(expectedWindow, "fi", "ho"),
Triple.of(expectedWindow, "fa", "ha"),
Triple.of(expectedWindow, "fa", "ho")),
partitions.get(0));
}
});
}
@Test
public void testJoinAccumulators() {
execute(new JoinTestCase<
Pair<String, Long>,
Pair<String, Long>,
Triple<TimeInterval, String, String>>() {
@Override
protected Partitions<Pair<String, Long>> getLeftInput() {
return Partitions.add(Pair.of("fi", 1L), Pair.of("fa", 3L)).build();
}
@Override
protected Partitions<Pair<String, Long>> getRightInput() {
return Partitions.add(Pair.of("ha", 1L), Pair.of("ho", 4L)).build();
}
@Override
public int getNumOutputPartitions() {
return 1;
}
@Override
protected Dataset<Triple<TimeInterval, String, String>>
getOutput(Dataset<Pair<String, Long>> left, Dataset<Pair<String, Long>> right) {
left = AssignEventTime.of(left).using(Pair::getSecond).output();
right = AssignEventTime.of(right).using(Pair::getSecond).output();
Dataset<Pair<String, Triple<TimeInterval, String, String>>> joined =
Join.of(left, right)
.by(p -> "", p -> "")
.using((Pair<String, Long> l, Pair<String, Long> r, Collector<Triple<TimeInterval, String, String>> c) -> {
TimeInterval window = (TimeInterval) c.getWindow();
c.getCounter("cntr").increment(10);
c.getHistogram("hist-" + l.getFirst().charAt(1)).add(2345, 8);
c.collect(Triple.of(window, l.getFirst(), r.getFirst()));
})
.windowBy(Time.of(Duration.ofMillis(3)))
.setNumPartitions(1)
.output();
return MapElements.of(joined).using(Pair::getSecond).output();
}
@Override
public void validate(Partitions<Triple<TimeInterval, String, String>> partitions) {
assertUnorderedEquals(
Arrays.asList(
Triple.of(new TimeInterval(0, 3), "fi", "ha"),
Triple.of(new TimeInterval(3, 6), "fa", "ho")),
partitions.get(0));
}
@Override
public void validateAccumulators(SnapshotProvider snapshots) {
Map<String, Long> counters = snapshots.getCounterSnapshots();
assertEquals(Long.valueOf(20L), counters.get("cntr"));
Map<String, Map<Long, Long>> histograms = snapshots.getHistogramSnapshots();
Map<Long, Long> hist = histograms.get("hist-i");
assertEquals(1, hist.size());
assertEquals(Long.valueOf(8), hist.get(2345L));
hist = histograms.get("hist-a");
assertEquals(1, hist.size());
assertEquals(Long.valueOf(8), hist.get(2345L));
}
});
}
}
|
/*
* Copyright (C) 2020 - Amir Hossein Aghajari
*
* 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.aghajari.emojiview.search;
public interface AXUISearchAdapter {
void searchFor (String value);
}
|
package com.github.hwywl.model;
import lombok.*;
/**
* @author: YI
* @description: SQL的连接条件
* @date: create in 2021/3/8 17:08
*/
@Data
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
public class Condition {
/**
* 属性名称
*/
String field;
/**
* 与上一条语句的连接符
*/
String aboveConditions;
/**
* 属性名称和属性值之间的连接符
*/
String middleConditions;
/**
* 属性的值
*/
String fieldValue;
}
|
package com.example.android.xpensemanager;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
|
package com.novoda.downloadmanager.lib;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.novoda.notils.logger.simple.Log;
class ConcurrentDownloadsLimitProvider {
private static final int DEFAULT_MAX_CONCURRENT_DOWNLOADS = 5;
private static final String METADATA_MAX_CONCURRENT_DOWNLOADS = "com.novoda.downloadmanager.MaxConcurrentDownloads";
private final PackageManager packageManager;
private final String packageName;
static ConcurrentDownloadsLimitProvider newInstance(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getApplicationContext().getPackageName();
return new ConcurrentDownloadsLimitProvider(packageManager, packageName);
}
ConcurrentDownloadsLimitProvider(PackageManager packageManager, String packageName) {
this.packageManager = packageManager;
this.packageName = packageName;
}
public int getConcurrentDownloadsLimit() {
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
return getMaximumConcurrentDownloads(applicationInfo.metaData);
} catch (PackageManager.NameNotFoundException e) {
Log.e("Application info not found for: " + packageName + " " + e.getMessage());
return DEFAULT_MAX_CONCURRENT_DOWNLOADS;
}
}
private int getMaximumConcurrentDownloads(Bundle bundle) {
if (bundle == null) {
return DEFAULT_MAX_CONCURRENT_DOWNLOADS;
}
return bundle.getInt(METADATA_MAX_CONCURRENT_DOWNLOADS, DEFAULT_MAX_CONCURRENT_DOWNLOADS);
}
}
|
/*
* Copyright 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.retail.v2alpha.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcCallableFactory;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientStreamingCallable;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StreamingCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.OperationsStub;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC callable factory implementation for the UserEventService service API.
*
* <p>This class is for advanced usage.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class GrpcUserEventServiceCallableFactory implements GrpcStubCallableFactory {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createPagedCallable(grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBatchingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
GrpcCallSettings<RequestT, Operation> grpcCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
OperationsStub operationsStub) {
return GrpcCallableFactory.createOperationCallable(
grpcCallSettings, callSettings, clientContext, operationsStub);
}
@Override
public <RequestT, ResponseT>
BidiStreamingCallable<RequestT, ResponseT> createBidiStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createBidiStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createServerStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT>
ClientStreamingCallable<RequestT, ResponseT> createClientStreamingCallable(
GrpcCallSettings<RequestT, ResponseT> grpcCallSettings,
StreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return GrpcCallableFactory.createClientStreamingCallable(
grpcCallSettings, callSettings, clientContext);
}
}
|
/*
* 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.beam.runners.flink.translation;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Iterables;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.beam.runners.flink.translation.types.CoderTypeInformation;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.AppliedPTransform;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PInput;
import org.apache.beam.sdk.values.POutput;
import org.apache.beam.sdk.values.PValue;
import org.apache.beam.sdk.values.TaggedPValue;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
/**
* Helper for keeping track of which {@link DataStream DataStreams} map
* to which {@link PTransform PTransforms}.
*/
public class FlinkStreamingTranslationContext {
private final StreamExecutionEnvironment env;
private final PipelineOptions options;
/**
* Keeps a mapping between the output value of the PTransform (in Dataflow) and the
* Flink Operator that produced it, after the translation of the correspondinf PTransform
* to its Flink equivalent.
* */
private final Map<PValue, DataStream<?>> dataStreams;
private AppliedPTransform<?, ?, ?> currentTransform;
public FlinkStreamingTranslationContext(StreamExecutionEnvironment env, PipelineOptions options) {
this.env = checkNotNull(env);
this.options = checkNotNull(options);
this.dataStreams = new HashMap<>();
}
public StreamExecutionEnvironment getExecutionEnvironment() {
return env;
}
public PipelineOptions getPipelineOptions() {
return options;
}
@SuppressWarnings("unchecked")
public <T> DataStream<T> getInputDataStream(PValue value) {
return (DataStream<T>) dataStreams.get(value);
}
public void setOutputDataStream(PValue value, DataStream<?> set) {
if (!dataStreams.containsKey(value)) {
dataStreams.put(value, set);
}
}
/**
* Sets the AppliedPTransform which carries input/output.
* @param currentTransform
*/
public void setCurrentTransform(AppliedPTransform<?, ?, ?> currentTransform) {
this.currentTransform = currentTransform;
}
@SuppressWarnings("unchecked")
public <T> TypeInformation<WindowedValue<T>> getTypeInfo(PCollection<T> collection) {
Coder<T> valueCoder = collection.getCoder();
WindowedValue.FullWindowedValueCoder<T> windowedValueCoder =
WindowedValue.getFullCoder(
valueCoder,
collection.getWindowingStrategy().getWindowFn().windowCoder());
return new CoderTypeInformation<>(windowedValueCoder);
}
@SuppressWarnings("unchecked")
public <T extends PValue> T getInput(PTransform<T, ?> transform) {
return (T) Iterables.getOnlyElement(currentTransform.getInputs()).getValue();
}
public <T extends PInput> List<TaggedPValue> getInputs(PTransform<T, ?> transform) {
return currentTransform.getInputs();
}
@SuppressWarnings("unchecked")
public <T extends PValue> T getOutput(PTransform<?, T> transform) {
return (T) Iterables.getOnlyElement(currentTransform.getOutputs()).getValue();
}
public <OutputT extends POutput> List<TaggedPValue> getOutputs(PTransform<?, OutputT> transform) {
return currentTransform.getOutputs();
}
}
|
/***************************************************************************
* Copyright (c) 2013-2014 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.vhadoop.vhm.vc;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLException;
import com.vmware.vhadoop.api.vhm.VCActions;
import com.vmware.vhadoop.api.vhm.VCActions.VMEventData;
import com.vmware.vhadoop.util.CompoundStatus;
import com.vmware.vhadoop.util.ExternalizedParameters;
import com.vmware.vhadoop.util.LogFormatter;
import com.vmware.vhadoop.util.ThreadLocalCompoundStatus;
import com.vmware.vhadoop.util.VhmLevel;
import com.vmware.vim.binding.impl.vim.event.EventExImpl;
import com.vmware.vim.binding.impl.vmodl.TypeNameImpl;
import com.vmware.vim.binding.vim.Folder;
import com.vmware.vim.binding.vim.PerformanceManager;
import com.vmware.vim.binding.vim.ServiceInstance;
import com.vmware.vim.binding.vim.ServiceInstanceContent;
import com.vmware.vim.binding.vim.SessionManager;
import com.vmware.vim.binding.vim.Task;
import com.vmware.vim.binding.vim.TaskInfo;
import com.vmware.vim.binding.vim.VirtualMachine;
import com.vmware.vim.binding.vim.VirtualMachine.PowerState;
import com.vmware.vim.binding.vim.alarm.Alarm;
import com.vmware.vim.binding.vim.alarm.AlarmManager;
import com.vmware.vim.binding.vim.event.Event.EventSeverity;
import com.vmware.vim.binding.vim.event.EventEx;
import com.vmware.vim.binding.vim.event.EventManager;
import com.vmware.vim.binding.vim.fault.HostConnectFault;
import com.vmware.vim.binding.vim.fault.InvalidEvent;
import com.vmware.vim.binding.vim.fault.VimFault;
import com.vmware.vim.binding.vim.net.IpConfigInfo;
import com.vmware.vim.binding.vim.net.IpConfigInfo.IpAddress;
import com.vmware.vim.binding.vim.option.OptionValue;
import com.vmware.vim.binding.vim.version.version8;
import com.vmware.vim.binding.vim.view.ContainerView;
import com.vmware.vim.binding.vim.view.ViewManager;
import com.vmware.vim.binding.vim.vm.GuestInfo.NicInfo;
import com.vmware.vim.binding.vmodl.DynamicProperty;
import com.vmware.vim.binding.vmodl.ManagedObjectReference;
import com.vmware.vim.binding.vmodl.TypeName;
import com.vmware.vim.binding.vmodl.fault.RequestCanceled;
import com.vmware.vim.binding.vmodl.query.InvalidCollectorVersion;
import com.vmware.vim.binding.vmodl.query.InvalidProperty;
import com.vmware.vim.binding.vmodl.query.PropertyCollector;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.Change;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.Filter;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.FilterSpec;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.FilterUpdate;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.ObjectContent;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.ObjectSpec;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.ObjectUpdate;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.ObjectUpdate.Kind;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.PropertySpec;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.RetrieveOptions;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.RetrieveResult;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.SelectionSpec;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.TraversalSpec;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.UpdateSet;
import com.vmware.vim.binding.vmodl.query.PropertyCollector.WaitOptions;
import com.vmware.vim.vmomi.client.Client;
import com.vmware.vim.vmomi.client.exception.ConnectionException;
import com.vmware.vim.vmomi.client.exception.TransportProtocolException;
import com.vmware.vim.vmomi.client.http.HttpClientConfiguration;
import com.vmware.vim.vmomi.client.http.ThumbprintVerifier;
import com.vmware.vim.vmomi.client.http.impl.HttpConfigurationImpl;
import com.vmware.vim.vmomi.core.types.VmodlContext;
public class VcVlsi {
public static final String SERENGETI_MASTERVM_NAME_POSTFIX = "-master-";
public static final String SERENGETI_MASTERVM_NAME_POSTFIX_GUI = "-ComputeMaster-";
private static final Logger _log = Logger.getLogger(VcVlsi.class.getName());
static final String VC_PROP_VM_NAME = "name";
static final String VC_PROP_VM_EXTRA_CONFIG = "config.extraConfig";
static final String VC_PROP_VM_UUID = "config.uuid";
static final String VC_PROP_VM_NUM_CPU = "config.hardware.numCPU";
static final String VC_PROP_VM_POWER_STATE = "runtime.powerState";
static final String VC_PROP_VM_HOST = "runtime.host";
static final String VC_PROP_VM_GUEST_NIC_INFO = "guest.net";
static final String VC_PROP_VM_GUEST_HOSTNAME = "guest.hostName";
static final String VC_MOREF_TYPE_TASK = "Task";
static final String VC_MOREF_TYPE_VM = "VirtualMachine";
static final String VC_MOREF_TYPE_FOLDER = "Folder";
static final String VC_MOREF_TYPE_CONTAINER_VIEW = "ContainerView";
private static final TypeNameImpl typeTask = new TypeNameImpl(VC_MOREF_TYPE_TASK);
private static final TypeNameImpl typeVM = new TypeNameImpl(VC_MOREF_TYPE_VM);
private static final TypeNameImpl typeFolder = new TypeNameImpl(VC_MOREF_TYPE_FOLDER);
private static final TypeNameImpl typeContainerView = new TypeNameImpl(VC_MOREF_TYPE_CONTAINER_VIEW);
private static final int propertyCollectorTimeout = ExternalizedParameters.get().getInt("VC_PROPERTY_COLLECTOR_TIMEOUT");
static final String VHM_EXTRA_CONFIG_PREFIX = "vhmInfo.";
static final String VHM_EXTRA_CONFIG_UUID = "vhmInfo.serengeti.uuid";
static final String VHM_EXTRA_CONFIG_MASTER_UUID = "vhmInfo.masterVM.uuid";
static final String VHM_EXTRA_CONFIG_MASTER_MOREF = "vhmInfo.masterVM.moid";
static final String VHM_EXTRA_CONFIG_MASTER_CLUSTERNAME = "vhmInfo.masterVM.clusterName";
static final String VHM_EXTRA_CONFIG_ELASTIC = "vhmInfo.elastic";
static final String VHM_EXTRA_CONFIG_AUTOMATION_ENABLE = "vhmInfo.vhm.enable";
static final String VHM_EXTRA_CONFIG_AUTOMATION_MIN_INSTANCES = "vhmInfo.min.computeNodeNum";
static final String VHM_EXTRA_CONFIG_AUTOMATION_INSTANCE_RANGE = "vhmInfo.instanceRange.computeNodeNum";
static final String VHM_EXTRA_CONFIG_JOB_TRACKER_PORT = "vhmInfo.jobtracker.port";
private static final String TASK_INFO_STATE = "info.state";
static final String WAIT_FOR_UPDATES_CANCELED_STATUS = "VC_WAIT_FOR_UPDATES_CANCELED";
static final String WAIT_FOR_UPDATES_INVALID_COLLECTOR_VERSION_STATUS = "VC_WAIT_FOR_UPDATES_INVALID_COLLECTOR_VERSION";
static final String WAIT_FOR_UPDATES_INVALID_PROPERTY_STATUS = "VC_WAIT_FOR_UPDATES_INVALID_PROPERTY";
static final String WAIT_FOR_UPDATES_NO_CLUSTERS = "VC_WAIT_FOR_UPDATES_NO_CLUSTERS";
private final String VC_ALARM_NAME_BASE = ExternalizedParameters.get().getString("VC_ALARM_NAME_BASE");
private ThreadLocalCompoundStatus _threadLocalStatus;
private PropertyCollector _blockedPropertyCollectorSingleton; /* Only one thread will ever be blocked on the PropertyCollector */
private Object _propertyCollectorLock = new Object();
private Alarm _alarmSingleton;
private Object _alarmLock = new Object();
static {
VmodlContext.initContext(new String[] { "com.vmware.vim.binding.vim" });
}
void setThreadLocalCompoundStatus(ThreadLocalCompoundStatus tlcs) {
_threadLocalStatus = tlcs;
}
private CompoundStatus getCompoundStatus() {
if (_threadLocalStatus == null) {
return new CompoundStatus("DUMMY_STATUS");
}
return _threadLocalStatus.get();
}
private ThumbprintVerifier getThumbprintVerifier(final String vcThumbprint) {
return new ThumbprintVerifier() {
@Override
public Result verify(String thumbprint) {
if (vcThumbprint == null) {
return Result.MATCH;
} else if (thumbprint.equalsIgnoreCase(vcThumbprint)) {
return Result.MATCH;
} else {
_log.log(Level.SEVERE, "VHM: thumbprint from vhm.properties does not match thumbprint from vCenter - "+thumbprint);
return Result.MISMATCH;
}
}
@Override
public void onSuccess(X509Certificate[] chain, String thumbprint,
Result verifyResult, boolean trustedChain,
boolean verifiedAssertions) throws SSLException {
}
};
}
private ServiceInstance getServiceInstance(Client vcClient) {
ManagedObjectReference svcRef = new ManagedObjectReference();
svcRef.setType("ServiceInstance");
svcRef.setValue("ServiceInstance");
return vcClient.createStub(ServiceInstance.class, svcRef);
}
private ServiceInstanceContent getServiceInstanceContent(Client vcClient) throws ConnectionException {
ServiceInstance svc = getServiceInstance(vcClient);
return svc.retrieveContent();
}
/*
* Create a temporary connection to VC to login using extension certificate via sdkTunnel,
* and get the session ticket to use for the normal connection.
*/
private String getSessionTicket(String vcIP, String keyStoreFile, String keyStorePwd, String vcExtKey, String vcThumbprint, long timeoutMillis)
throws ConnectionException, URISyntaxException, IOException, GeneralSecurityException, VimFault {
URI uri = new URI("https://sdkTunnel:8089/sdk/vimService");
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream is = null;
try {
is = new FileInputStream(keyStoreFile);
keyStore.load(is, keyStorePwd.toCharArray());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}
HttpConfigurationImpl httpConfig = new HttpConfigurationImpl();
httpConfig.setKeyStore(keyStore);
httpConfig.setDefaultProxy(vcIP, 80, "http");
httpConfig.getKeyStoreConfig().setKeyAlias(keyStore.aliases().nextElement());
httpConfig.getKeyStoreConfig().setKeyPassword(keyStorePwd);
httpConfig.setTimeoutMs((int)timeoutMillis);
httpConfig.setThumbprintVerifier(getThumbprintVerifier(vcThumbprint));
HttpClientConfiguration clientConfig = HttpClientConfiguration.Factory.newInstance();
clientConfig.setHttpConfiguration(httpConfig);
Client newClient = Client.Factory.createClient(uri, version8.class, clientConfig);
ServiceInstanceContent sic = getServiceInstanceContent(newClient);
SessionManager sm = newClient.createStub(SessionManager.class, sic.getSessionManager());
sm.loginExtensionByCertificate(vcExtKey, null);
String ticket = sm.acquireSessionTicket(null);
return ticket;
}
public Client connect(VcCredentials credentials, boolean useKey, Client cloneClient, long timeoutMillis)
throws ConnectionException, HostConnectFault, IOException, VimFault, GeneralSecurityException, URISyntaxException {
String sessionTicket = null;
if (cloneClient != null) {
ServiceInstanceContent sic = getServiceInstanceContent(cloneClient);
SessionManager sm = cloneClient.createStub(SessionManager.class, sic.getSessionManager());
sessionTicket = sm.acquireCloneTicket();
} else if (useKey) {
sessionTicket = getSessionTicket(credentials.vcIP, credentials.keyStoreFile, credentials.keyStorePwd, credentials.vcExtKey, credentials.vcThumbprint, timeoutMillis);
}
URI uri = new URI("https", null, credentials.vcIP, 443, "/sdk", null, null);
// each VLSI call consumes an executor thread for the duration of the blocking call
ThreadPoolExecutor executor =
new ThreadPoolExecutor(1, // core pool size
4, // max pool size
10, TimeUnit.SECONDS, // max thread idle time
new LinkedBlockingQueue<Runnable>()); // work queue
HttpConfigurationImpl httpConfig = new HttpConfigurationImpl();
httpConfig.setTimeoutMs((int)timeoutMillis);
httpConfig.setThumbprintVerifier(getThumbprintVerifier(credentials.vcThumbprint));
HttpClientConfiguration clientConfig = HttpClientConfiguration.Factory.newInstance();
clientConfig.setHttpConfiguration(httpConfig);
clientConfig.setExecutor(executor);
Client newClient = Client.Factory.createClient(uri, version8.class, clientConfig);
if (newClient != null) {
ServiceInstanceContent sic = getServiceInstanceContent(newClient);
SessionManager sm = newClient.createStub(SessionManager.class, sic.getSessionManager());
if (cloneClient != null) {
sm.cloneSession(sessionTicket);
} else {
if (useKey) {
sm.loginBySessionTicket(sessionTicket);
} else {
sm.login(credentials.user, credentials.password, null);
}
}
}
return newClient;
}
public boolean testConnection(Client vcClient) {
if (vcClient == null) {
return false;
}
// Test the operation of the current connection using the standard simple call for this purpose.
Calendar vcTime = null;
try {
ServiceInstance si = getServiceInstance(vcClient);
vcTime = si.currentTime();
} catch (Exception e) {
/* We don't really care what the exception was, we just don't want it propogating */
} finally {
if (vcTime == null) {
_log.log(Level.INFO, "testConnection found VC connection dropped; caller will reconnect");
}
}
return (vcTime != null);
}
private Folder getRootFolder(Client client) throws ConnectionException {
ServiceInstanceContent sic = getServiceInstanceContent(client);
return client.createStub(Folder.class, sic.getRootFolder());
}
/**
* Property filters are used a lot when querying the JAX-WS API for information about VC entities
* The code is pretty ugly, so it makes sense to encapsulate it in a utility class.
* The class is dual-purpose - it can be created with either constructor depending on the need.
* Properties can then be added to the filter and once that's completed,
* retrieveProperties() or getPropertyCollector() can be called, depending on the requirement
*
*/
public class PropertyFilter {
PropertyCollector _propertyCollector;
Filter _filter;
PropertySpec _propertySpec;
FilterSpec _propertyFilterSpec;
boolean _initialized = false;
ContainerView _containerView;
Client _vcClient;
public PropertyFilter(Client vcClient, ContainerView containerView, TypeName type) {
_vcClient = vcClient;
_containerView = containerView;
TraversalSpec tSpec = getTraversalSpecFromView();
ObjectSpec objectSpec = new ObjectSpec();
objectSpec.setObj(containerView._getRef());
objectSpec.setSelectSet(new SelectionSpec[] {tSpec});
_propertyFilterSpec = new FilterSpec();
_propertyFilterSpec.setObjectSet(new ObjectSpec[] {objectSpec});
_propertySpec = new PropertySpec();
_propertySpec.setAll(Boolean.FALSE);
_propertySpec.setType(type);
}
public PropertyFilter(Client vcClient, Task task) {
_vcClient = vcClient;
ObjectSpec objectSpec = new ObjectSpec();
objectSpec.setObj(task._getRef());
objectSpec.setSkip(Boolean.FALSE);
_propertyFilterSpec = new FilterSpec();
_propertyFilterSpec.setObjectSet(new ObjectSpec[] {objectSpec});
_propertySpec = new PropertySpec();
_propertySpec.setType(typeTask);
}
private TraversalSpec getTraversalSpecFromView() {
// Create a traversal spec that starts from the ListView object
// and traverses to its "view" property containing the managed object references.
TraversalSpec viewToObject = new TraversalSpec();
viewToObject.setName("viewToObject");
viewToObject.setType(typeContainerView);
viewToObject.setPath("view");
viewToObject.setSkip(false);
return viewToObject;
}
public void setPropToFilter(String property) throws InvalidProperty, ConnectionException {
_propertySpec.setPathSet(new String[] {property});
init();
}
public void setPropsToFilter(String[] properties) throws InvalidProperty, ConnectionException {
_propertySpec.setPathSet(properties);
init();
}
private void init() throws InvalidProperty, ConnectionException {
if (!_initialized) {
_propertyFilterSpec.setPropSet(new PropertySpec [] {_propertySpec});
ServiceInstanceContent sic = getServiceInstanceContent(_vcClient);
_propertyCollector = _vcClient.createStub(PropertyCollector.class, sic.getPropertyCollector());
_filter = _vcClient.createStub(Filter.class, _propertyCollector.createFilter(_propertyFilterSpec, true));
}
_initialized = true;
}
public PropertyCollector getPropertyCollector() throws InvalidProperty, ConnectionException {
init();
return _propertyCollector;
}
public RetrieveResult retrieveProperties() throws InvalidProperty, ConnectionException {
init();
RetrieveOptions retrieveOptions = new RetrieveOptions();
return _propertyCollector.retrievePropertiesEx(new FilterSpec[] {_propertyFilterSpec}, retrieveOptions);
}
public RetrieveResult continueRetrieve(String token) throws InvalidProperty {
return _propertyCollector.continueRetrievePropertiesEx(token);
}
public void cleanup() {
if (_filter != null) {
_filter.destroy();
}
if (_containerView != null) {
_containerView.destroy();
}
}
}
private List<ManagedObjectReference> findObjectsInFolder(Client client, Folder baseFolder, TypeName type, String restrictToName)
throws InvalidProperty, ConnectionException {
if (baseFolder == null) {
return null;
}
List<ManagedObjectReference> resultRefs = new ArrayList<ManagedObjectReference>();
ServiceInstanceContent sic = getServiceInstanceContent(client);
ViewManager viewMgr = client.createStub(ViewManager.class, sic.getViewManager());
ContainerView cView = client.createStub(ContainerView.class,
viewMgr.createContainerView(baseFolder._getRef(), new TypeName[] {type}, true));
PropertyFilter propFilter = new PropertyFilter(client, cView, type);
propFilter.setPropToFilter("name");
RetrieveResult rr = propFilter.retrieveProperties();
boolean done = false;
while ((rr != null) && !done) {
ObjectContent[] oca = rr.getObjects();
for (ObjectContent oc : oca) {
if (restrictToName == null) {
resultRefs.add(oc.getObj());
} else {
// filter out by name
DynamicProperty[] dps = oc.getPropSet();
for (DynamicProperty dp : dps) {
if (dp.getName().equals("name") && dp.getVal().equals(restrictToName)) {
resultRefs.add(oc.getObj());
done = true;
break;
}
}
}
}
if (rr.getToken() == null) {
done = true;
} else if (!done) {
// get the next batch of results from VC
rr = propFilter.continueRetrieve(rr.getToken());
}
}
propFilter.cleanup();
return resultRefs;
}
Folder getFolderForName(Client client, Folder baseFolder, String restrictToName) throws InvalidProperty {
if (baseFolder == null) {
baseFolder = getRootFolder(client);
}
List<ManagedObjectReference> refs = findObjectsInFolder(client, baseFolder, typeFolder, restrictToName);
if (refs.size() > 0) {
return client.createStub(Folder.class, refs.get(0));
}
return null;
}
private PropertyFilter setupWaitForUpdates(Client vcClient, Folder baseFolder, TypeName type, String[] statePropsToGet)
throws InvalidProperty, ConnectionException {
PropertyFilter propFilter = null;
ServiceInstanceContent sic = getServiceInstanceContent(vcClient);
ViewManager viewMgr = vcClient.createStub(ViewManager.class, sic.getViewManager());
ContainerView cView = vcClient.createStub(ContainerView.class,
viewMgr.createContainerView(baseFolder._getRef(), new TypeName[] {type}, true));
propFilter = new PropertyFilter(vcClient, cView, type);
propFilter.setPropsToFilter(statePropsToGet);
return propFilter;
}
private UpdateSet callWaitForUpdates(PropertyCollector propCollector, String version) throws InvalidCollectorVersion {
UpdateSet updateSet = null;
if (version == null) {
version = "";
}
WaitOptions waitOptions = new WaitOptions();
waitOptions.setMaxWaitSeconds(propertyCollectorTimeout);
synchronized(_propertyCollectorLock) {
_blockedPropertyCollectorSingleton = propCollector;
}
try {
updateSet = propCollector.waitForUpdatesEx(version, waitOptions);
} finally {
synchronized(_propertyCollectorLock) {
_blockedPropertyCollectorSingleton = null;
}
}
return updateSet;
}
/* TODO: Why is this not called anywhere? */
private void cleanupWaitForUpdates(PropertyFilter propFilter) {
propFilter.cleanup();
}
private static Map<String, Set<String>> getNicInfo(NicInfo[] nicInfoArray) {
Map<String, Set<String>> nicAndIpAddressMap = new HashMap<String, Set<String>>();
if (nicInfoArray != null) {
for (NicInfo nicInfo : nicInfoArray) {
String networkName = nicInfo.getNetwork();
IpConfigInfo ipConfigInfo = nicInfo.getIpConfig();
if ((ipConfigInfo != null) && (networkName != null)) {
IpAddress[] ipAddressObjects = ipConfigInfo.getIpAddress();
if (ipAddressObjects != null) {
Set<String> ipAddressSet = new HashSet<String>();
for (IpAddress ipAddressObj : ipAddressObjects) {
String ipAddress = ipAddressObj.getIpAddress();
if (ipAddress != null) {
ipAddressSet.add(ipAddress);
}
}
nicAndIpAddressMap.put(networkName, ipAddressSet);
}
}
}
}
return nicAndIpAddressMap;
}
private static VMEventData parseObjUpdate(Logger logger, ObjectUpdate obj) {
VMEventData vmData = new VMEventData();
vmData._vmMoRef = obj.getObj().getValue();
Kind kind = obj.getKind();
logger.log(Level.FINE, "Pobj kind= " + kind + " obj= " + obj.getObj().getValue());
if (kind == Kind.leave) {
vmData._isLeaving = true;
} else if (kind == Kind.modify || kind == Kind.enter) {
vmData._isLeaving = false;
for (Change pc : obj.getChangeSet()) {
String pcName = pc.getName();
Object pcValue = pc.getVal();
logger.log(Level.FINE, "Pobj prop= " + pcName + " val= " + pcValue);
if (pcValue != null) {
if (pcName.equals(VC_PROP_VM_UUID)) {
vmData._myUUID = (String)pcValue;
} else if (pcName.equals(VC_PROP_VM_NUM_CPU)) {
vmData._vCPUs = (Integer)pcValue;
} else if (pcName.equals(VC_PROP_VM_NAME)) {
vmData._myName = (String)pcValue;
/* Update this as early as possible. Doesn't matter if the key already exists */
logger.log(Level.FINE, "Associating vmId "+vmData._vmMoRef+" with name "+vmData._myName);
LogFormatter._vmIdToNameMapper.put(vmData._vmMoRef, vmData._myName);
} else if (pcName.equals(VC_PROP_VM_POWER_STATE)) {
PowerState ps = (PowerState)pcValue;
if (ps == PowerState.poweredOn) {
vmData._powerState = true;
} else {
vmData._powerState = false;
}
} else if (pcName.equals(VC_PROP_VM_HOST)) {
vmData._hostMoRef = ((ManagedObjectReference)pcValue).getValue();
} else if (pcName.equals(VC_PROP_VM_GUEST_NIC_INFO)) {
vmData._nicAndIpAddressMap = getNicInfo((NicInfo[])pcValue);
} else if (pcName.equals(VC_PROP_VM_GUEST_HOSTNAME)) {
vmData._dnsName = (String)pcValue;
} else if (pcName.equals(VC_PROP_VM_EXTRA_CONFIG)) {
// extraConfig updates can be returned as an array (pcName == config.extraConfig), or individual key (below)
OptionValue[] ecl = (OptionValue[]) pcValue;
for (OptionValue ec : ecl) {
if (ec.getKey().startsWith(VHM_EXTRA_CONFIG_PREFIX)) {
VcVlsiHelper.parseExtraConfig(vmData, ec.getKey(), (String)ec.getValue());
}
}
} else if (pcName.lastIndexOf(VC_PROP_VM_EXTRA_CONFIG) >= 0) {
// individual extraConfig entries (pcName = config.extraConfig["xxx"].value)
String [] parts = pcName.split("\"",3);
if (parts.length > 1) {
if (parts[1].startsWith(VHM_EXTRA_CONFIG_PREFIX)) {
// sometimes pcValue is a String, and sometimes its OptionValue...
String valueString;
if (pcValue instanceof String) {
valueString = (String)pcValue;
} else {
valueString = (String) ((OptionValue)pcValue).getValue();
}
VcVlsiHelper.parseExtraConfig(vmData, parts[1], valueString);
}
}
} else {
logger.log(Level.WARNING, "Unexpected update: prop= " + pcName + " val= " + pcValue);
}
}
}
}
return vmData;
}
private String pcVMsInFolder(Client vcClient, Folder folder, String version, List<VMEventData> vmDataList)
throws ConnectionException, InvalidCollectorVersion, InvalidProperty {
if (version == null) {
version = "";
}
if (version.equals("")) {
String [] props = {VC_PROP_VM_NAME, VC_PROP_VM_EXTRA_CONFIG, VC_PROP_VM_UUID, VC_PROP_VM_NUM_CPU,
VC_PROP_VM_POWER_STATE, VC_PROP_VM_HOST, VC_PROP_VM_GUEST_NIC_INFO, VC_PROP_VM_GUEST_HOSTNAME};
setupWaitForUpdates(vcClient, folder, typeVM, props);
}
ServiceInstanceContent sic = getServiceInstanceContent(vcClient);
PropertyCollector propertyCollector = vcClient.createStub(PropertyCollector.class, sic.getPropertyCollector());
UpdateSet updateSet = null;
try {
updateSet = callWaitForUpdates(propertyCollector, version);
} catch (ConnectionException e) {
Throwable cause = e.getCause();
/*
* SocketTimeoutException is caused when we hit SESSION_TIME_OUT
* If that happens, hide the exception, and just return with no changes
*/
if ((cause != null) && (cause instanceof SocketTimeoutException)) {
return version;
}
throw e;
}
if (updateSet != null) {
version = updateSet.getVersion();
FilterUpdate[] updates = updateSet.getFilterSet();
//_log.log(Level.INFO, "WFU new version= " + version + " fs= " + updates);
if (updates != null) {
for (FilterUpdate pfu : updates) {
ObjectUpdate[] objectSet = pfu.getObjectSet();
for (ObjectUpdate obj : objectSet) {
VMEventData vmData = parseObjUpdate(_log, obj);
if (vmData != null) {
vmDataList.add(vmData);
}
}
}
}
}
return version;
}
boolean waitForTask(Client client, Task task) {
CompoundStatus status = new CompoundStatus("waitForTask");
boolean result = false;
PropertyFilter propFilter = new PropertyFilter(client, task);
try {
propFilter.setPropsToFilter(new String [] {TASK_INFO_STATE });
UpdateSet updateSet = null;
String version = "";
WaitOptions waitOptions = new WaitOptions();
waitOptions.setMaxWaitSeconds(propertyCollectorTimeout);
_mainLoop: while (true) {
_log.log(Level.INFO, "WFT waiting vesrion=" + version);
updateSet = propFilter.getPropertyCollector().waitForUpdatesEx(version, waitOptions);
if (updateSet != null) {
version = updateSet.getVersion();
FilterUpdate[] updates = updateSet.getFilterSet();
if (updates != null) {
for (FilterUpdate pfu : updates) {
ObjectUpdate[] objectSet = pfu.getObjectSet();
for (ObjectUpdate obj : objectSet) {
Kind kind = obj.getKind();
if (kind == Kind.modify || kind == Kind.enter || kind == Kind.leave) {
for (Change pc : obj.getChangeSet()) {
String pcName = pc.getName();
Object pcValue = pc.getVal();
if (pcName.lastIndexOf(TASK_INFO_STATE) >= 0) {
TaskInfo.State state = (TaskInfo.State)pcValue;
if (state == TaskInfo.State.error) {
result = false;
break _mainLoop;
} else if (state == TaskInfo.State.success) {
result = true;
break _mainLoop;
}
}
}
}
}
}
}
}
}
status.registerTaskSucceeded();
} catch (ConnectionException e) {
reportException("Error connecting to vCenter: "+e.getMessage(), status);
} catch (Exception e) {
reportException("Unexpected exception waiting for task completion", e, status);
} finally {
propFilter.cleanup();
}
getCompoundStatus().addStatus(status);
return result;
}
public String waitForUpdates(Client client, String baseFolderName, String version, List<VMEventData> vmDataList) {
CompoundStatus status = new CompoundStatus("waitForUpdates");
String newVersion = version;
/* There is an expectation that this method should never return null */
if (newVersion == null) {
newVersion = "";
}
try {
Folder f = getFolderForName(client, null, baseFolderName);
if (f == null) {
// This is normal state when user hasn't created any hadoop clusters yet
_log.log(Level.INFO, "No found clusters for hadoop UUID " + baseFolderName);
newVersion = WAIT_FOR_UPDATES_NO_CLUSTERS;
} else {
newVersion = pcVMsInFolder(client, f, version, vmDataList);
}
status.registerTaskSucceeded();
} catch (RequestCanceled e) {
_log.info("waitForUpdates request has been canceled");
newVersion = WAIT_FOR_UPDATES_CANCELED_STATUS;
} catch (InvalidCollectorVersion e) {
_log.info("propertyCollector version has become stale");
newVersion = WAIT_FOR_UPDATES_INVALID_COLLECTOR_VERSION_STATUS;
} catch (InvalidProperty e) {
_log.info("propertyCollector property is invalid: "+e);
newVersion = WAIT_FOR_UPDATES_INVALID_PROPERTY_STATUS;
} catch (ConnectionException e) {
reportException("Error connecting to vCenter: "+e.getMessage(), status);
} catch (TransportProtocolException e) {
reportException("Error connecting to vCenter: "+e.getMessage(), status);
} catch (Exception e) {
reportException("Unexpected exception waiting for updates", e, status);
}
getCompoundStatus().addStatus(status);
return newVersion;
}
public List<String> getVMsInFolder(Client client, String baseFolderName, String folderName) {
CompoundStatus status = new CompoundStatus("getVMsInFolder");
List<String> result = null;
try {
Folder baseFolder = getFolderForName(client, null, baseFolderName);
Folder folder = getFolderForName(client, baseFolder, folderName);
List<ManagedObjectReference> refs = findObjectsInFolder(client, folder, typeVM, null);
if ((refs != null) && (refs.size() > 0)) {
result = new ArrayList<String>();
for (ManagedObjectReference ref : refs) {
result.add(ref.getValue());
}
}
status.registerTaskSucceeded();
} catch (com.vmware.vim.binding.vmodl.fault.RequestCanceled e) {
_log.info("getVMsInFolder has been canceled");
} catch (ConnectionException e) {
reportException("Error connecting to vCenter: "+e.getMessage(), status);
} catch (Exception e) {
reportException("Unexpected exception in getVMsInFolder", e, status);
}
getCompoundStatus().addStatus(status);
return result;
}
private void reportException(String msg, CompoundStatus status) {
reportException(msg, null, status);
}
private void reportException(String msg, Exception e, CompoundStatus status) {
if (e != null) {
/* Stack trace at INFO level to comply with PSP */
_log.log(Level.INFO, msg, e);
msg += ": "+e.getMessage();
}
_log.log(Level.WARNING, msg);
status.registerTaskFailed(false, msg);
}
public Map<String, Task> powerOnVMs(Client client, Set<String> vmMoRefs) {
CompoundStatus status = new CompoundStatus(VCActions.VC_POWER_ON_STATUS_KEY);
Map<String, Task> result = new HashMap<String, Task>();
for (String moRef : vmMoRefs) {
ManagedObjectReference ref = new ManagedObjectReference();
ref.setValue(moRef);
VirtualMachine vm = client.createStub(VirtualMachine.class, ref);
try {
ManagedObjectReference taskRef = vm.powerOn(null);
Task task = client.createStub(Task.class, taskRef);
result.put(moRef, task);
status.registerTaskSucceeded();
} catch (Exception e) {
reportException("Error powering on VM: "+e.getMessage(), status);
}
}
getCompoundStatus().addStatus(status);
return result;
}
public Map<String, Task> powerOffVMs(Client client, Set<String> vmMoRefs) {
CompoundStatus status = new CompoundStatus(VCActions.VC_POWER_OFF_STATUS_KEY);
Map<String, Task> result = new HashMap<String, Task>();
for (String moRef : vmMoRefs) {
ManagedObjectReference ref = new ManagedObjectReference();
ref.setValue(moRef);
VirtualMachine vm = client.createStub(VirtualMachine.class, ref);
try {
ManagedObjectReference taskRef = vm.powerOff();
Task task = client.createStub(Task.class, taskRef);
result.put(moRef, task);
status.registerTaskSucceeded();
} catch (Exception e) {
reportException("Error powering off VM: "+e.getMessage(), status);
}
}
getCompoundStatus().addStatus(status);
return result;
}
public void cancelWaitForUpdates() {
synchronized(_propertyCollectorLock) {
if (_blockedPropertyCollectorSingleton != null) {
_blockedPropertyCollectorSingleton.cancelWaitForUpdates();
}
}
}
public PerformanceManager getPerformanceManager(Client client) {
try {
ServiceInstanceContent sic = getServiceInstanceContent(client);
return client.createStub(PerformanceManager.class, sic.getPerfManager());
} catch (Exception e) {
_log.info("Cannot connect to VC performance manager");
return null;
}
}
private EventManager getEventManager(Client client) {
try {
ServiceInstanceContent sic = getServiceInstanceContent(client);
return client.createStub(EventManager.class, sic.getEventManager());
} catch (Exception e) {
_log.info("Cannot connect to VC event manager");
return null;
}
}
private AlarmManager getAlarmManager(Client client) {
try {
ServiceInstanceContent sic = getServiceInstanceContent(client);
return client.createStub(AlarmManager.class, sic.getAlarmManager());
} catch (Exception e) {
_log.info("Cannot connect to VC alarm manager");
return null;
}
}
public boolean postEventForVM(Client client, String vmMoRef, EventSeverity level, String message) {
EventManager eventManager = getEventManager(client);
if (eventManager == null) {
return false;
}
ManagedObjectReference ref = new ManagedObjectReference();
ref.setValue(vmMoRef);
ref.setType("VirtualMachine");
EventEx event = new EventExImpl();
event.setCreatedTime(Calendar.getInstance());
event.setUserName("Big Data Extensions");
event.setEventTypeId("com.vmware.vhadoop.vhm.vc.events."+level.name());
event.setSeverity(level.name());
event.setMessage(message);
event.setObjectId(ref.getValue());
event.setObjectType(new TypeNameImpl("VirtualMachine"));
try {
_log.log(VhmLevel.USER, "VHM: <%V"+vmMoRef+"%V> - "+message);
eventManager.postEvent(event, null);
return true;
} catch (InvalidEvent e) {
_log.log(Level.INFO, "VHM: <%V"+vmMoRef+"%V> - failed to log "+level.name()+" event with vCenter", e);
}
return false;
}
private Alarm getAlarm(Client client, String rootFolderName) {
synchronized(_alarmLock) {
if (_alarmSingleton != null) {
return _alarmSingleton;
}
AlarmManager manager = getAlarmManager(client);
if (manager == null) {
return null;
}
Folder root;
try {
root = getFolderForName(client, null, rootFolderName);
ManagedObjectReference[] existing = manager.getAlarm(root._getRef());
for (ManagedObjectReference m : existing) {
Alarm a = client.createStub(Alarm.class, m);
if (a.getInfo().getName().startsWith(VC_ALARM_NAME_BASE)) {
_alarmSingleton = a;
return _alarmSingleton;
}
}
} catch (InvalidProperty e) {
_log.info("VHM: unable to get reference to alarm "+VC_ALARM_NAME_BASE+" on vApp folder "+rootFolderName);
_log.log(Level.FINER, "VHM: exception while getting reference to top level alarm", e);
} catch (NullPointerException e) {
/* almost any of the values returned from vlsi client or their subsequent calls could be null but
* will not be most of the time. It's much clearer to just have one catch here than tests on
* ever access given we do the same thing in response.
*/
_log.info("VHM: unable to get reference to alarm "+VC_ALARM_NAME_BASE+" on vApp folder "+rootFolderName);
_log.log(Level.FINER, "VHM: exception while getting reference to top level alarm", e);
}
}
return null;
}
void acknowledgeAlarm(Client client, String rootFolderName, String vmMoRef) {
AlarmManager alarmMgr = getAlarmManager(client);
if (alarmMgr == null) {
return;
}
/* acknowledge the alarm */
Alarm alarm = getAlarm(client, rootFolderName);
if (alarm != null) {
ManagedObjectReference moRef = new ManagedObjectReference();
moRef.setValue(vmMoRef);
moRef.setType("VirtualMachine");
alarmMgr.acknowledgeAlarm(alarm._getRef(), moRef);
}
}
}
/*
VirtualMachine vm = getVMForName(f, "xxxxx");
_log.log(Level.INFO, "TPC vm.name = " + vm.getName());
_log.log(Level.INFO, "TPC vm = " + vm);
PowerState ps = vm.getRuntime().getPowerState();
_log.log(Level.INFO, "TPC vm ps = " + ps);
ManagedObjectReference taskRef;
if (ps == PowerState.poweredOn) {
taskRef = vm.powerOff();
} else {
taskRef = vm.powerOn(null);
}
Task t = defaultClient.createStub(Task.class, taskRef);
boolean success = waitForTask(t);
_log.log(Level.INFO, "TPC task success=" + success);
ps = vm.getRuntime().getPowerState();
_log.log(Level.INFO, "TPC vm new ps = " + ps);
*/
|
package Ass7;
public class Song {
private String songName;
private int trackNumber;
public Song(String songName, int trackNumber )
{
this.songName = songName;
this.trackNumber = trackNumber;
}
public String getSongName()
{
return songName;
}
public void setSongName( String songName )
{
this.songName = songName;
}
public int getTrackNumber()
{
return trackNumber;
}
public void setTrackNumber( int trackNumber )
{
this.trackNumber = trackNumber;
}
}
|
package android.support.v4.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.os.SystemClock;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.AutoScrollHelper;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v4.widget.ExploreByTouchHelper;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.BaseSavedState;
import android.view.View.MeasureSpec;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import com.alipay.sdk.util.h;
import com.taobao.accs.data.Message;
import com.xunlei.tdlive.R;
import com.xunlei.tdlive.sdk.IHost;
import com.xunlei.xiazaibao.sdk.XZBDevice;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ViewPager extends ViewGroup {
private static final int CLOSE_ENOUGH = 2;
private static final Comparator<ItemInfo> COMPARATOR;
private static final boolean DEBUG = false;
private static final int DEFAULT_GUTTER_SIZE = 16;
private static final int DEFAULT_OFFSCREEN_PAGES = 1;
private static final int DRAW_ORDER_DEFAULT = 0;
private static final int DRAW_ORDER_FORWARD = 1;
private static final int DRAW_ORDER_REVERSE = 2;
private static final int INVALID_POINTER = -1;
private static final int[] LAYOUT_ATTRS;
private static final int MAX_SETTLE_DURATION = 600;
private static final int MIN_DISTANCE_FOR_FLING = 25;
private static final int MIN_FLING_VELOCITY = 400;
public static final int SCROLL_STATE_DRAGGING = 1;
public static final int SCROLL_STATE_IDLE = 0;
public static final int SCROLL_STATE_SETTLING = 2;
private static final String TAG = "ViewPager";
private static final boolean USE_CACHE = false;
private static final Interpolator sInterpolator;
private static final ViewPositionComparator sPositionComparator;
private int mActivePointerId;
private PagerAdapter mAdapter;
private OnAdapterChangeListener mAdapterChangeListener;
private int mBottomPageBounds;
private boolean mCalledSuper;
private int mChildHeightMeasureSpec;
private int mChildWidthMeasureSpec;
private int mCloseEnough;
private int mCurItem;
private int mDecorChildCount;
private int mDefaultGutterSize;
private int mDrawingOrder;
private ArrayList<View> mDrawingOrderedChildren;
private final Runnable mEndScrollRunnable;
private int mExpectedAdapterCount;
private long mFakeDragBeginTime;
private boolean mFakeDragging;
private boolean mFirstLayout;
private float mFirstOffset;
private int mFlingDistance;
private int mGutterSize;
private boolean mInLayout;
private float mInitialMotionX;
private float mInitialMotionY;
private OnPageChangeListener mInternalPageChangeListener;
private boolean mIsBeingDragged;
private boolean mIsScrollStarted;
private boolean mIsUnableToDrag;
private final ArrayList<ItemInfo> mItems;
private float mLastMotionX;
private float mLastMotionY;
private float mLastOffset;
private EdgeEffectCompat mLeftEdge;
private Drawable mMarginDrawable;
private int mMaximumVelocity;
private int mMinimumVelocity;
private boolean mNeedCalculatePageOffsets;
private PagerObserver mObserver;
private int mOffscreenPageLimit;
private OnPageChangeListener mOnPageChangeListener;
private List<OnPageChangeListener> mOnPageChangeListeners;
private int mPageMargin;
private PageTransformer mPageTransformer;
private boolean mPopulatePending;
private Parcelable mRestoredAdapterState;
private ClassLoader mRestoredClassLoader;
private int mRestoredCurItem;
private EdgeEffectCompat mRightEdge;
private int mScrollState;
private Scroller mScroller;
private boolean mScrollingCacheEnabled;
private Method mSetChildrenDrawingOrderEnabled;
private final ItemInfo mTempItem;
private final Rect mTempRect;
private int mTopPageBounds;
private int mTouchSlop;
private VelocityTracker mVelocityTracker;
public static interface OnPageChangeListener {
void onPageScrollStateChanged(int i);
void onPageScrolled(int i, float f, int i2);
void onPageSelected(int i);
}
static interface Decor {
}
static interface OnAdapterChangeListener {
void onAdapterChanged(PagerAdapter pagerAdapter, PagerAdapter pagerAdapter2);
}
static class ItemInfo {
Object object;
float offset;
int position;
boolean scrolling;
float widthFactor;
ItemInfo() {
}
}
public static class LayoutParams extends android.view.ViewGroup.LayoutParams {
int childIndex;
public int gravity;
public boolean isDecor;
boolean needsMeasure;
int position;
float widthFactor;
public LayoutParams() {
super(-1, -1);
this.widthFactor = 0.0f;
}
public LayoutParams(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.widthFactor = 0.0f;
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, LAYOUT_ATTRS);
this.gravity = obtainStyledAttributes.getInteger(SCROLL_STATE_IDLE, R.styleable.AppCompatTheme_homeAsUpIndicator);
obtainStyledAttributes.recycle();
}
}
class MyAccessibilityDelegate extends AccessibilityDelegateCompat {
MyAccessibilityDelegate() {
}
public void onInitializeAccessibilityEvent(View view, AccessibilityEvent accessibilityEvent) {
super.onInitializeAccessibilityEvent(view, accessibilityEvent);
accessibilityEvent.setClassName(ViewPager.class.getName());
AccessibilityRecordCompat asRecord = AccessibilityEventCompat.asRecord(accessibilityEvent);
asRecord.setScrollable(canScroll());
if (accessibilityEvent.getEventType() == 4096 && ViewPager.this.mAdapter != null) {
asRecord.setItemCount(ViewPager.this.mAdapter.getCount());
asRecord.setFromIndex(ViewPager.this.mCurItem);
asRecord.setToIndex(ViewPager.this.mCurItem);
}
}
public void onInitializeAccessibilityNodeInfo(View view, AccessibilityNodeInfoCompat accessibilityNodeInfoCompat) {
super.onInitializeAccessibilityNodeInfo(view, accessibilityNodeInfoCompat);
accessibilityNodeInfoCompat.setClassName(ViewPager.class.getName());
accessibilityNodeInfoCompat.setScrollable(canScroll());
if (ViewPager.this.canScrollHorizontally(SCROLL_STATE_DRAGGING)) {
accessibilityNodeInfoCompat.addAction((int) Message.FLAG_ERR);
}
if (ViewPager.this.canScrollHorizontally(INVALID_POINTER)) {
accessibilityNodeInfoCompat.addAction((int) Message.FLAG_REQ_BIT2);
}
}
public boolean performAccessibilityAction(View view, int i, Bundle bundle) {
if (super.performAccessibilityAction(view, i, bundle)) {
return true;
}
switch (i) {
case Message.FLAG_ERR:
if (!ViewPager.this.canScrollHorizontally(SCROLL_STATE_DRAGGING)) {
return false;
}
ViewPager.this.setCurrentItem(ViewPager.this.mCurItem + 1);
return true;
case Message.FLAG_REQ_BIT2:
if (!ViewPager.this.canScrollHorizontally(INVALID_POINTER)) {
return false;
}
ViewPager.this.setCurrentItem(ViewPager.this.mCurItem - 1);
return true;
default:
return false;
}
}
private boolean canScroll() {
return (ViewPager.this.mAdapter == null || ViewPager.this.mAdapter.getCount() <= 1) ? DEBUG : true;
}
}
public static interface PageTransformer {
void transformPage(View view, float f);
}
private class PagerObserver extends DataSetObserver {
private PagerObserver() {
}
public void onChanged() {
ViewPager.this.dataSetChanged();
}
public void onInvalidated() {
ViewPager.this.dataSetChanged();
}
}
public static class SavedState extends BaseSavedState {
public static final Creator<android.support.v4.view.ViewPager.SavedState> CREATOR;
Parcelable adapterState;
ClassLoader loader;
int position;
public SavedState(Parcelable parcelable) {
super(parcelable);
}
public void writeToParcel(Parcel parcel, int i) {
super.writeToParcel(parcel, i);
parcel.writeInt(this.position);
parcel.writeParcelable(this.adapterState, i);
}
public String toString() {
return new StringBuilder("FragmentPager.SavedState{").append(Integer.toHexString(System.identityHashCode(this))).append(" position=").append(this.position).append(h.d).toString();
}
static {
CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<android.support.v4.view.ViewPager.SavedState>() {
public final android.support.v4.view.ViewPager.SavedState createFromParcel(Parcel parcel, ClassLoader classLoader) {
return new android.support.v4.view.ViewPager.SavedState(parcel, classLoader);
}
public final android.support.v4.view.ViewPager.SavedState[] newArray(int i) {
return new android.support.v4.view.ViewPager.SavedState[i];
}
});
}
SavedState(Parcel parcel, ClassLoader classLoader) {
super(parcel);
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
this.position = parcel.readInt();
this.adapterState = parcel.readParcelable(classLoader);
this.loader = classLoader;
}
}
public static class SimpleOnPageChangeListener implements OnPageChangeListener {
public void onPageScrolled(int i, float f, int i2) {
}
public void onPageSelected(int i) {
}
public void onPageScrollStateChanged(int i) {
}
}
static class ViewPositionComparator implements Comparator<View> {
ViewPositionComparator() {
}
public int compare(View view, View view2) {
LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
LayoutParams layoutParams2 = (LayoutParams) view2.getLayoutParams();
if (layoutParams.isDecor != layoutParams2.isDecor) {
return layoutParams.isDecor ? SCROLL_STATE_DRAGGING : INVALID_POINTER;
} else {
return layoutParams.position - layoutParams2.position;
}
}
}
static {
LAYOUT_ATTRS = new int[]{16842931};
COMPARATOR = new Comparator<ItemInfo>() {
public final int compare(ItemInfo itemInfo, ItemInfo itemInfo2) {
return itemInfo.position - itemInfo2.position;
}
};
sInterpolator = new Interpolator() {
public final float getInterpolation(float f) {
float f2 = f - 1.0f;
return (f2 * (((f2 * f2) * f2) * f2)) + 1.0f;
}
};
sPositionComparator = new ViewPositionComparator();
}
public ViewPager(Context context) {
super(context);
this.mItems = new ArrayList();
this.mTempItem = new ItemInfo();
this.mTempRect = new Rect();
this.mRestoredCurItem = -1;
this.mRestoredAdapterState = null;
this.mRestoredClassLoader = null;
this.mFirstOffset = -3.4028235E38f;
this.mLastOffset = Float.MAX_VALUE;
this.mOffscreenPageLimit = 1;
this.mActivePointerId = -1;
this.mFirstLayout = true;
this.mNeedCalculatePageOffsets = false;
this.mEndScrollRunnable = new Runnable() {
public void run() {
ViewPager.this.setScrollState(SCROLL_STATE_IDLE);
ViewPager.this.populate();
}
};
this.mScrollState = 0;
initViewPager();
}
public ViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.mItems = new ArrayList();
this.mTempItem = new ItemInfo();
this.mTempRect = new Rect();
this.mRestoredCurItem = -1;
this.mRestoredAdapterState = null;
this.mRestoredClassLoader = null;
this.mFirstOffset = -3.4028235E38f;
this.mLastOffset = Float.MAX_VALUE;
this.mOffscreenPageLimit = 1;
this.mActivePointerId = -1;
this.mFirstLayout = true;
this.mNeedCalculatePageOffsets = false;
this.mEndScrollRunnable = new Runnable() {
public void run() {
ViewPager.this.setScrollState(SCROLL_STATE_IDLE);
ViewPager.this.populate();
}
};
this.mScrollState = 0;
initViewPager();
}
void initViewPager() {
setWillNotDraw(DEBUG);
setDescendantFocusability(AccessibilityNodeInfoCompat.ACTION_EXPAND);
setFocusable(true);
Context context = getContext();
this.mScroller = new Scroller(context, sInterpolator);
ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
float f = context.getResources().getDisplayMetrics().density;
this.mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(viewConfiguration);
this.mMinimumVelocity = (int) (400.0f * f);
this.mMaximumVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
this.mLeftEdge = new EdgeEffectCompat(context);
this.mRightEdge = new EdgeEffectCompat(context);
this.mFlingDistance = (int) (25.0f * f);
this.mCloseEnough = (int) (2.0f * f);
this.mDefaultGutterSize = (int) (16.0f * f);
ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());
if (ViewCompat.getImportantForAccessibility(this) == 0) {
ViewCompat.setImportantForAccessibility(this, SCROLL_STATE_DRAGGING);
}
ViewCompat.setOnApplyWindowInsetsListener(this, new OnApplyWindowInsetsListener() {
private final Rect mTempRect;
{
this.mTempRect = new Rect();
}
public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat windowInsetsCompat) {
WindowInsetsCompat onApplyWindowInsets = ViewCompat.onApplyWindowInsets(view, windowInsetsCompat);
if (onApplyWindowInsets.isConsumed()) {
return onApplyWindowInsets;
}
Rect rect = this.mTempRect;
rect.left = onApplyWindowInsets.getSystemWindowInsetLeft();
rect.top = onApplyWindowInsets.getSystemWindowInsetTop();
rect.right = onApplyWindowInsets.getSystemWindowInsetRight();
rect.bottom = onApplyWindowInsets.getSystemWindowInsetBottom();
int childCount = ViewPager.this.getChildCount();
for (int i = SCROLL_STATE_IDLE; i < childCount; i++) {
WindowInsetsCompat dispatchApplyWindowInsets = ViewCompat.dispatchApplyWindowInsets(ViewPager.this.getChildAt(i), onApplyWindowInsets);
rect.left = Math.min(dispatchApplyWindowInsets.getSystemWindowInsetLeft(), rect.left);
rect.top = Math.min(dispatchApplyWindowInsets.getSystemWindowInsetTop(), rect.top);
rect.right = Math.min(dispatchApplyWindowInsets.getSystemWindowInsetRight(), rect.right);
rect.bottom = Math.min(dispatchApplyWindowInsets.getSystemWindowInsetBottom(), rect.bottom);
}
return onApplyWindowInsets.replaceSystemWindowInsets(rect.left, rect.top, rect.right, rect.bottom);
}
});
}
protected void onDetachedFromWindow() {
removeCallbacks(this.mEndScrollRunnable);
if (!(this.mScroller == null || this.mScroller.isFinished())) {
this.mScroller.abortAnimation();
}
super.onDetachedFromWindow();
}
private void setScrollState(int i) {
if (this.mScrollState != i) {
this.mScrollState = i;
if (this.mPageTransformer != null) {
enableLayers(i != 0 ? true : DEBUG);
}
dispatchOnScrollStateChanged(i);
}
}
public void setAdapter(PagerAdapter pagerAdapter) {
if (this.mAdapter != null) {
this.mAdapter.setViewPagerObserver(null);
this.mAdapter.startUpdate((ViewGroup) this);
for (int i = 0; i < this.mItems.size(); i++) {
ItemInfo itemInfo = (ItemInfo) this.mItems.get(i);
this.mAdapter.destroyItem((ViewGroup) this, itemInfo.position, itemInfo.object);
}
this.mAdapter.finishUpdate((ViewGroup) this);
this.mItems.clear();
removeNonDecorViews();
this.mCurItem = 0;
scrollTo(SCROLL_STATE_IDLE, SCROLL_STATE_IDLE);
}
PagerAdapter pagerAdapter2 = this.mAdapter;
this.mAdapter = pagerAdapter;
this.mExpectedAdapterCount = 0;
if (this.mAdapter != null) {
if (this.mObserver == null) {
this.mObserver = new PagerObserver();
}
this.mAdapter.setViewPagerObserver(this.mObserver);
this.mPopulatePending = false;
boolean z = this.mFirstLayout;
this.mFirstLayout = true;
this.mExpectedAdapterCount = this.mAdapter.getCount();
if (this.mRestoredCurItem >= 0) {
this.mAdapter.restoreState(this.mRestoredAdapterState, this.mRestoredClassLoader);
setCurrentItemInternal(this.mRestoredCurItem, DEBUG, true);
this.mRestoredCurItem = -1;
this.mRestoredAdapterState = null;
this.mRestoredClassLoader = null;
} else if (z) {
requestLayout();
} else {
populate();
}
}
if (this.mAdapterChangeListener != null && pagerAdapter2 != pagerAdapter) {
this.mAdapterChangeListener.onAdapterChanged(pagerAdapter2, pagerAdapter);
}
}
private void removeNonDecorViews() {
int i = 0;
while (i < getChildCount()) {
if (!((LayoutParams) getChildAt(i).getLayoutParams()).isDecor) {
removeViewAt(i);
i--;
}
i++;
}
}
public PagerAdapter getAdapter() {
return this.mAdapter;
}
void setOnAdapterChangeListener(OnAdapterChangeListener onAdapterChangeListener) {
this.mAdapterChangeListener = onAdapterChangeListener;
}
private int getClientWidth() {
return (getMeasuredWidth() - getPaddingLeft()) - getPaddingRight();
}
public void setCurrentItem(int i) {
boolean z;
this.mPopulatePending = false;
if (this.mFirstLayout) {
z = false;
} else {
z = true;
}
setCurrentItemInternal(i, z, DEBUG);
}
public void setCurrentItem(int i, boolean z) {
this.mPopulatePending = false;
setCurrentItemInternal(i, z, DEBUG);
}
public int getCurrentItem() {
return this.mCurItem;
}
void setCurrentItemInternal(int i, boolean z, boolean z2) {
setCurrentItemInternal(i, z, z2, SCROLL_STATE_IDLE);
}
void setCurrentItemInternal(int i, boolean z, boolean z2, int i2) {
boolean z3 = DEBUG;
if (this.mAdapter == null || this.mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(DEBUG);
} else if (z2 || this.mCurItem != i || this.mItems.size() == 0) {
if (i < 0) {
i = 0;
} else if (i >= this.mAdapter.getCount()) {
i = this.mAdapter.getCount() - 1;
}
int i3 = this.mOffscreenPageLimit;
if (i > this.mCurItem + i3 || i < this.mCurItem - i3) {
for (int i4 = 0; i4 < this.mItems.size(); i4++) {
((ItemInfo) this.mItems.get(i4)).scrolling = true;
}
}
if (this.mCurItem != i) {
z3 = true;
}
if (this.mFirstLayout) {
this.mCurItem = i;
if (z3) {
dispatchOnPageSelected(i);
}
requestLayout();
return;
}
populate(i);
scrollToItem(i, z, i2, z3);
} else {
setScrollingCacheEnabled(DEBUG);
}
}
private void scrollToItem(int i, boolean z, int i2, boolean z2) {
int max;
ItemInfo infoForPosition = infoForPosition(i);
if (infoForPosition != null) {
max = (int) (Math.max(this.mFirstOffset, Math.min(infoForPosition.offset, this.mLastOffset)) * ((float) getClientWidth()));
} else {
max = 0;
}
if (z) {
smoothScrollTo(max, SCROLL_STATE_IDLE, i2);
if (z2) {
dispatchOnPageSelected(i);
return;
}
return;
}
if (z2) {
dispatchOnPageSelected(i);
}
completeScroll(DEBUG);
scrollTo(max, SCROLL_STATE_IDLE);
pageScrolled(max);
}
@Deprecated
public void setOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
this.mOnPageChangeListener = onPageChangeListener;
}
public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
if (this.mOnPageChangeListeners == null) {
this.mOnPageChangeListeners = new ArrayList();
}
this.mOnPageChangeListeners.add(onPageChangeListener);
}
public void removeOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
if (this.mOnPageChangeListeners != null) {
this.mOnPageChangeListeners.remove(onPageChangeListener);
}
}
public void clearOnPageChangeListeners() {
if (this.mOnPageChangeListeners != null) {
this.mOnPageChangeListeners.clear();
}
}
public void setPageTransformer(boolean z, PageTransformer pageTransformer) {
int i = SCROLL_STATE_DRAGGING;
if (VERSION.SDK_INT >= 11) {
int i2;
boolean z2 = pageTransformer != null;
if (this.mPageTransformer != null) {
i2 = 1;
} else {
i2 = 0;
}
i2 = z2 != r3 ? 1 : 0;
this.mPageTransformer = pageTransformer;
setChildrenDrawingOrderEnabledCompat(z2);
if (z2) {
if (z) {
i = SCROLL_STATE_SETTLING;
}
this.mDrawingOrder = i;
} else {
this.mDrawingOrder = 0;
}
if (i2 != 0) {
populate();
}
}
}
void setChildrenDrawingOrderEnabledCompat(boolean z) {
if (VERSION.SDK_INT >= 7) {
if (this.mSetChildrenDrawingOrderEnabled == null) {
try {
this.mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod("setChildrenDrawingOrderEnabled", new Class[]{Boolean.TYPE});
} catch (NoSuchMethodException e) {
}
}
try {
this.mSetChildrenDrawingOrderEnabled.invoke(this, new Object[]{Boolean.valueOf(z)});
} catch (Exception e2) {
}
}
}
protected int getChildDrawingOrder(int i, int i2) {
if (this.mDrawingOrder == 2) {
i2 = (i - 1) - i2;
}
return ((LayoutParams) ((View) this.mDrawingOrderedChildren.get(i2)).getLayoutParams()).childIndex;
}
OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener onPageChangeListener) {
OnPageChangeListener onPageChangeListener2 = this.mInternalPageChangeListener;
this.mInternalPageChangeListener = onPageChangeListener;
return onPageChangeListener2;
}
public int getOffscreenPageLimit() {
return this.mOffscreenPageLimit;
}
public void setOffscreenPageLimit(int i) {
if (i <= 0) {
new StringBuilder("Requested offscreen page limit ").append(i).append(" too small; defaulting to 1");
i = SCROLL_STATE_DRAGGING;
}
if (i != this.mOffscreenPageLimit) {
this.mOffscreenPageLimit = i;
populate();
}
}
public void setPageMargin(int i) {
int i2 = this.mPageMargin;
this.mPageMargin = i;
int width = getWidth();
recomputeScrollPosition(width, width, i, i2);
requestLayout();
}
public int getPageMargin() {
return this.mPageMargin;
}
public void setPageMarginDrawable(Drawable drawable) {
this.mMarginDrawable = drawable;
if (drawable != null) {
refreshDrawableState();
}
setWillNotDraw(drawable == null ? true : DEBUG);
invalidate();
}
public void setPageMarginDrawable(int i) {
setPageMarginDrawable(getContext().getResources().getDrawable(i));
}
protected boolean verifyDrawable(Drawable drawable) {
return (super.verifyDrawable(drawable) || drawable == this.mMarginDrawable) ? true : DEBUG;
}
protected void drawableStateChanged() {
super.drawableStateChanged();
Drawable drawable = this.mMarginDrawable;
if (drawable != null && drawable.isStateful()) {
drawable.setState(getDrawableState());
}
}
float distanceInfluenceForSnapDuration(float f) {
return (float) Math.sin((double) ((float) (((double) (f - 0.5f)) * 0.4712389167638204d)));
}
void smoothScrollTo(int i, int i2) {
smoothScrollTo(i, i2, SCROLL_STATE_IDLE);
}
void smoothScrollTo(int i, int i2, int i3) {
if (getChildCount() == 0) {
setScrollingCacheEnabled(DEBUG);
return;
}
int i4;
boolean z = (this.mScroller == null || this.mScroller.isFinished()) ? false : true;
if (z) {
int currX = this.mIsScrollStarted ? this.mScroller.getCurrX() : this.mScroller.getStartX();
this.mScroller.abortAnimation();
setScrollingCacheEnabled(DEBUG);
i4 = currX;
} else {
i4 = getScrollX();
}
int scrollY = getScrollY();
int i5 = i - i4;
int i6 = i2 - scrollY;
if (i5 == 0 && i6 == 0) {
completeScroll(DEBUG);
populate();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
setScrollState(SCROLL_STATE_SETTLING);
currX = getClientWidth();
int i7 = currX / 2;
float distanceInfluenceForSnapDuration = (((float) i7) * distanceInfluenceForSnapDuration(Math.min(1.0f, (((float) Math.abs(i5)) * 1.0f) / ((float) currX)))) + ((float) i7);
int abs = Math.abs(i3);
if (abs > 0) {
currX = Math.round(1000.0f * Math.abs(distanceInfluenceForSnapDuration / ((float) abs))) * 4;
} else {
currX = (int) (((((float) Math.abs(i5)) / ((((float) currX) * this.mAdapter.getPageWidth(this.mCurItem)) + ((float) this.mPageMargin))) + 1.0f) * 100.0f);
}
i7 = Math.min(currX, MAX_SETTLE_DURATION);
this.mIsScrollStarted = false;
this.mScroller.startScroll(i4, scrollY, i5, i6, i7);
ViewCompat.postInvalidateOnAnimation(this);
}
ItemInfo addNewItem(int i, int i2) {
ItemInfo itemInfo = new ItemInfo();
itemInfo.position = i;
itemInfo.object = this.mAdapter.instantiateItem((ViewGroup) this, i);
itemInfo.widthFactor = this.mAdapter.getPageWidth(i);
if (i2 < 0 || i2 >= this.mItems.size()) {
this.mItems.add(itemInfo);
} else {
this.mItems.add(i2, itemInfo);
}
return itemInfo;
}
void dataSetChanged() {
int count = this.mAdapter.getCount();
this.mExpectedAdapterCount = count;
boolean z = this.mItems.size() < (this.mOffscreenPageLimit * 2) + 1 && this.mItems.size() < count;
boolean z2 = false;
int i = this.mCurItem;
boolean z3 = z;
int i2 = 0;
while (i2 < this.mItems.size()) {
int i3;
boolean z4;
int max;
boolean z5;
ItemInfo itemInfo = (ItemInfo) this.mItems.get(i2);
int itemPosition = this.mAdapter.getItemPosition(itemInfo.object);
if (itemPosition != -1) {
if (itemPosition == -2) {
this.mItems.remove(i2);
i2--;
if (!z2) {
this.mAdapter.startUpdate((ViewGroup) this);
z2 = true;
}
this.mAdapter.destroyItem((ViewGroup) this, itemInfo.position, itemInfo.object);
if (this.mCurItem == itemInfo.position) {
i3 = i2;
z4 = z2;
max = Math.max(SCROLL_STATE_IDLE, Math.min(this.mCurItem, count - 1));
z5 = true;
} else {
i3 = i2;
z4 = z2;
max = i;
z5 = true;
}
} else if (itemInfo.position != itemPosition) {
if (itemInfo.position == this.mCurItem) {
i = itemPosition;
}
itemInfo.position = itemPosition;
i3 = i2;
z4 = z2;
max = i;
z5 = true;
}
z3 = z5;
i = max;
z2 = z4;
i2 = i3 + 1;
}
i3 = i2;
z4 = z2;
max = i;
z5 = z3;
z3 = z5;
i = max;
z2 = z4;
i2 = i3 + 1;
}
if (z2) {
this.mAdapter.finishUpdate((ViewGroup) this);
}
Collections.sort(this.mItems, COMPARATOR);
if (z3) {
max = getChildCount();
for (i2 = 0; i2 < max; i2++) {
LayoutParams layoutParams = (LayoutParams) getChildAt(i2).getLayoutParams();
if (!layoutParams.isDecor) {
layoutParams.widthFactor = 0.0f;
}
}
setCurrentItemInternal(i, DEBUG, true);
requestLayout();
}
}
void populate() {
populate(this.mCurItem);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void populate(int r18) {
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.view.ViewPager.populate(int):void");
/*
this = this;
r2 = 0;
r0 = r17;
r3 = r0.mCurItem;
r0 = r18;
if (r3 == r0) goto L_0x031d;
L_0x0009:
r0 = r17;
r2 = r0.mCurItem;
r0 = r17;
r2 = r0.infoForPosition(r2);
r0 = r18;
r1 = r17;
r1.mCurItem = r0;
r3 = r2;
L_0x001a:
r0 = r17;
r2 = r0.mAdapter;
if (r2 != 0) goto L_0x0024;
L_0x0020:
r17.sortChildDrawingOrder();
L_0x0023:
return;
L_0x0024:
r0 = r17;
r2 = r0.mPopulatePending;
if (r2 == 0) goto L_0x002e;
L_0x002a:
r17.sortChildDrawingOrder();
goto L_0x0023;
L_0x002e:
r2 = r17.getWindowToken();
if (r2 == 0) goto L_0x0023;
L_0x0034:
r0 = r17;
r2 = r0.mAdapter;
r0 = r17;
r2.startUpdate(r0);
r0 = r17;
r2 = r0.mOffscreenPageLimit;
r4 = 0;
r0 = r17;
r5 = r0.mCurItem;
r5 = r5 - r2;
r10 = java.lang.Math.max(r4, r5);
r0 = r17;
r4 = r0.mAdapter;
r11 = r4.getCount();
r4 = r11 + -1;
r0 = r17;
r5 = r0.mCurItem;
r2 = r2 + r5;
r12 = java.lang.Math.min(r4, r2);
r0 = r17;
r2 = r0.mExpectedAdapterCount;
if (r11 == r2) goto L_0x00cc;
L_0x0064:
r2 = r17.getResources(); Catch:{ NotFoundException -> 0x00c2 }
r3 = r17.getId(); Catch:{ NotFoundException -> 0x00c2 }
r2 = r2.getResourceName(r3); Catch:{ NotFoundException -> 0x00c2 }
L_0x0070:
r3 = new java.lang.IllegalStateException;
r4 = new java.lang.StringBuilder;
r5 = "The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: ";
r4.<init>(r5);
r0 = r17;
r5 = r0.mExpectedAdapterCount;
r4 = r4.append(r5);
r5 = ", found: ";
r4 = r4.append(r5);
r4 = r4.append(r11);
r5 = " Pager id: ";
r4 = r4.append(r5);
r2 = r4.append(r2);
r4 = " Pager class: ";
r2 = r2.append(r4);
r4 = r17.getClass();
r2 = r2.append(r4);
r4 = " Problematic adapter: ";
r2 = r2.append(r4);
r0 = r17;
r4 = r0.mAdapter;
r4 = r4.getClass();
r2 = r2.append(r4);
r2 = r2.toString();
r3.<init>(r2);
throw r3;
L_0x00c2:
r2 = move-exception;
r2 = r17.getId();
r2 = java.lang.Integer.toHexString(r2);
goto L_0x0070;
L_0x00cc:
r5 = 0;
r2 = 0;
r4 = r2;
L_0x00cf:
r0 = r17;
r2 = r0.mItems;
r2 = r2.size();
if (r4 >= r2) goto L_0x031a;
L_0x00d9:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r4);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
r6 = r2.position;
r0 = r17;
r7 = r0.mCurItem;
if (r6 < r7) goto L_0x015f;
L_0x00eb:
r6 = r2.position;
r0 = r17;
r7 = r0.mCurItem;
if (r6 != r7) goto L_0x031a;
L_0x00f3:
if (r2 != 0) goto L_0x0317;
L_0x00f5:
if (r11 <= 0) goto L_0x0317;
L_0x00f7:
r0 = r17;
r2 = r0.mCurItem;
r0 = r17;
r2 = r0.addNewItem(r2, r4);
r9 = r2;
L_0x0102:
if (r9 == 0) goto L_0x0279;
L_0x0104:
r8 = 0;
r7 = r4 + -1;
if (r7 < 0) goto L_0x0164;
L_0x0109:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r7);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
L_0x0113:
r13 = r17.getClientWidth();
if (r13 > 0) goto L_0x0166;
L_0x0119:
r5 = 0;
L_0x011a:
r0 = r17;
r6 = r0.mCurItem;
r6 = r6 + -1;
r15 = r6;
r6 = r8;
r8 = r15;
r16 = r7;
r7 = r4;
r4 = r16;
L_0x0128:
if (r8 < 0) goto L_0x01ac;
L_0x012a:
r14 = (r6 > r5 ? 1 : (r6 == r5 ? 0 : -1));
if (r14 < 0) goto L_0x0176;
L_0x012e:
if (r8 >= r10) goto L_0x0176;
L_0x0130:
if (r2 == 0) goto L_0x01ac;
L_0x0132:
r14 = r2.position;
if (r8 != r14) goto L_0x015c;
L_0x0136:
r14 = r2.scrolling;
if (r14 != 0) goto L_0x015c;
L_0x013a:
r0 = r17;
r14 = r0.mItems;
r14.remove(r4);
r0 = r17;
r14 = r0.mAdapter;
r2 = r2.object;
r0 = r17;
r14.destroyItem(r0, r8, r2);
r4 = r4 + -1;
r7 = r7 + -1;
if (r4 < 0) goto L_0x0174;
L_0x0152:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r4);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
L_0x015c:
r8 = r8 + -1;
goto L_0x0128;
L_0x015f:
r2 = r4 + 1;
r4 = r2;
goto L_0x00cf;
L_0x0164:
r2 = 0;
goto L_0x0113;
L_0x0166:
r5 = 1073741824; // 0x40000000 float:2.0 double:5.304989477E-315;
r6 = r9.widthFactor;
r5 = r5 - r6;
r6 = r17.getPaddingLeft();
r6 = (float) r6;
r14 = (float) r13;
r6 = r6 / r14;
r5 = r5 + r6;
goto L_0x011a;
L_0x0174:
r2 = 0;
goto L_0x015c;
L_0x0176:
if (r2 == 0) goto L_0x0190;
L_0x0178:
r14 = r2.position;
if (r8 != r14) goto L_0x0190;
L_0x017c:
r2 = r2.widthFactor;
r6 = r6 + r2;
r4 = r4 + -1;
if (r4 < 0) goto L_0x018e;
L_0x0183:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r4);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
goto L_0x015c;
L_0x018e:
r2 = 0;
goto L_0x015c;
L_0x0190:
r2 = r4 + 1;
r0 = r17;
r2 = r0.addNewItem(r8, r2);
r2 = r2.widthFactor;
r6 = r6 + r2;
r7 = r7 + 1;
if (r4 < 0) goto L_0x01aa;
L_0x019f:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r4);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
goto L_0x015c;
L_0x01aa:
r2 = 0;
goto L_0x015c;
L_0x01ac:
r5 = r9.widthFactor;
r8 = r7 + 1;
r2 = 1073741824; // 0x40000000 float:2.0 double:5.304989477E-315;
r2 = (r5 > r2 ? 1 : (r5 == r2 ? 0 : -1));
if (r2 >= 0) goto L_0x0274;
L_0x01b6:
r0 = r17;
r2 = r0.mItems;
r2 = r2.size();
if (r8 >= r2) goto L_0x021a;
L_0x01c0:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r8);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
r6 = r2;
L_0x01cb:
if (r13 > 0) goto L_0x021c;
L_0x01cd:
r2 = 0;
r4 = r2;
L_0x01cf:
r0 = r17;
r2 = r0.mCurItem;
r2 = r2 + 1;
r15 = r6;
r6 = r8;
r8 = r2;
r2 = r15;
L_0x01d9:
if (r8 >= r11) goto L_0x0274;
L_0x01db:
r10 = (r5 > r4 ? 1 : (r5 == r4 ? 0 : -1));
if (r10 < 0) goto L_0x022a;
L_0x01df:
if (r8 <= r12) goto L_0x022a;
L_0x01e1:
if (r2 == 0) goto L_0x0274;
L_0x01e3:
r10 = r2.position;
if (r8 != r10) goto L_0x0312;
L_0x01e7:
r10 = r2.scrolling;
if (r10 != 0) goto L_0x0312;
L_0x01eb:
r0 = r17;
r10 = r0.mItems;
r10.remove(r6);
r0 = r17;
r10 = r0.mAdapter;
r2 = r2.object;
r0 = r17;
r10.destroyItem(r0, r8, r2);
r0 = r17;
r2 = r0.mItems;
r2 = r2.size();
if (r6 >= r2) goto L_0x0228;
L_0x0207:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r6);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
L_0x0211:
r15 = r5;
r5 = r2;
r2 = r15;
L_0x0214:
r8 = r8 + 1;
r15 = r2;
r2 = r5;
r5 = r15;
goto L_0x01d9;
L_0x021a:
r6 = 0;
goto L_0x01cb;
L_0x021c:
r2 = r17.getPaddingRight();
r2 = (float) r2;
r4 = (float) r13;
r2 = r2 / r4;
r4 = 1073741824; // 0x40000000 float:2.0 double:5.304989477E-315;
r2 = r2 + r4;
r4 = r2;
goto L_0x01cf;
L_0x0228:
r2 = 0;
goto L_0x0211;
L_0x022a:
if (r2 == 0) goto L_0x024f;
L_0x022c:
r10 = r2.position;
if (r8 != r10) goto L_0x024f;
L_0x0230:
r2 = r2.widthFactor;
r5 = r5 + r2;
r6 = r6 + 1;
r0 = r17;
r2 = r0.mItems;
r2 = r2.size();
if (r6 >= r2) goto L_0x024d;
L_0x023f:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r6);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
L_0x0249:
r15 = r5;
r5 = r2;
r2 = r15;
goto L_0x0214;
L_0x024d:
r2 = 0;
goto L_0x0249;
L_0x024f:
r0 = r17;
r2 = r0.addNewItem(r8, r6);
r6 = r6 + 1;
r2 = r2.widthFactor;
r5 = r5 + r2;
r0 = r17;
r2 = r0.mItems;
r2 = r2.size();
if (r6 >= r2) goto L_0x0272;
L_0x0264:
r0 = r17;
r2 = r0.mItems;
r2 = r2.get(r6);
r2 = (android.support.v4.view.ViewPager.ItemInfo) r2;
L_0x026e:
r15 = r5;
r5 = r2;
r2 = r15;
goto L_0x0214;
L_0x0272:
r2 = 0;
goto L_0x026e;
L_0x0274:
r0 = r17;
r0.calculatePageOffsets(r9, r7, r3);
L_0x0279:
r0 = r17;
r3 = r0.mAdapter;
r0 = r17;
r4 = r0.mCurItem;
if (r9 == 0) goto L_0x02c8;
L_0x0283:
r2 = r9.object;
L_0x0285:
r0 = r17;
r3.setPrimaryItem(r0, r4, r2);
r0 = r17;
r2 = r0.mAdapter;
r0 = r17;
r2.finishUpdate(r0);
r4 = r17.getChildCount();
r2 = 0;
r3 = r2;
L_0x0299:
if (r3 >= r4) goto L_0x02ca;
L_0x029b:
r0 = r17;
r5 = r0.getChildAt(r3);
r2 = r5.getLayoutParams();
r2 = (android.support.v4.view.ViewPager.LayoutParams) r2;
r2.childIndex = r3;
r6 = r2.isDecor;
if (r6 != 0) goto L_0x02c4;
L_0x02ad:
r6 = r2.widthFactor;
r7 = 0;
r6 = (r6 > r7 ? 1 : (r6 == r7 ? 0 : -1));
if (r6 != 0) goto L_0x02c4;
L_0x02b4:
r0 = r17;
r5 = r0.infoForChild(r5);
if (r5 == 0) goto L_0x02c4;
L_0x02bc:
r6 = r5.widthFactor;
r2.widthFactor = r6;
r5 = r5.position;
r2.position = r5;
L_0x02c4:
r2 = r3 + 1;
r3 = r2;
goto L_0x0299;
L_0x02c8:
r2 = 0;
goto L_0x0285;
L_0x02ca:
r17.sortChildDrawingOrder();
r2 = r17.hasFocus();
if (r2 == 0) goto L_0x0023;
L_0x02d3:
r2 = r17.findFocus();
if (r2 == 0) goto L_0x0310;
L_0x02d9:
r0 = r17;
r2 = r0.infoForAnyChild(r2);
L_0x02df:
if (r2 == 0) goto L_0x02e9;
L_0x02e1:
r2 = r2.position;
r0 = r17;
r3 = r0.mCurItem;
if (r2 == r3) goto L_0x0023;
L_0x02e9:
r2 = 0;
L_0x02ea:
r3 = r17.getChildCount();
if (r2 >= r3) goto L_0x0023;
L_0x02f0:
r0 = r17;
r3 = r0.getChildAt(r2);
r0 = r17;
r4 = r0.infoForChild(r3);
if (r4 == 0) goto L_0x030d;
L_0x02fe:
r4 = r4.position;
r0 = r17;
r5 = r0.mCurItem;
if (r4 != r5) goto L_0x030d;
L_0x0306:
r4 = 2;
r3 = r3.requestFocus(r4);
if (r3 != 0) goto L_0x0023;
L_0x030d:
r2 = r2 + 1;
goto L_0x02ea;
L_0x0310:
r2 = 0;
goto L_0x02df;
L_0x0312:
r15 = r5;
r5 = r2;
r2 = r15;
goto L_0x0214;
L_0x0317:
r9 = r2;
goto L_0x0102;
L_0x031a:
r2 = r5;
goto L_0x00f3;
L_0x031d:
r3 = r2;
goto L_0x001a;
*/
}
private void sortChildDrawingOrder() {
if (this.mDrawingOrder != 0) {
if (this.mDrawingOrderedChildren == null) {
this.mDrawingOrderedChildren = new ArrayList();
} else {
this.mDrawingOrderedChildren.clear();
}
int childCount = getChildCount();
for (int i = SCROLL_STATE_IDLE; i < childCount; i++) {
this.mDrawingOrderedChildren.add(getChildAt(i));
}
Collections.sort(this.mDrawingOrderedChildren, sPositionComparator);
}
}
private void calculatePageOffsets(ItemInfo itemInfo, int i, ItemInfo itemInfo2) {
float f;
ItemInfo itemInfo3;
float f2;
int i2;
int i3;
int count = this.mAdapter.getCount();
int clientWidth = getClientWidth();
if (clientWidth > 0) {
f = ((float) this.mPageMargin) / ((float) clientWidth);
} else {
f = 0.0f;
}
if (itemInfo2 != null) {
clientWidth = itemInfo2.position;
float f3;
int i4;
int i5;
int i6;
float pageWidth;
if (clientWidth < itemInfo.position) {
f3 = (itemInfo2.offset + itemInfo2.widthFactor) + f;
i4 = 0;
i5 = clientWidth + 1;
while (i5 <= itemInfo.position && i4 < this.mItems.size()) {
itemInfo3 = (ItemInfo) this.mItems.get(i4);
while (i5 > itemInfo3.position && i4 < this.mItems.size() - 1) {
i4++;
itemInfo3 = (ItemInfo) this.mItems.get(i4);
}
i6 = i5;
f2 = f3;
i2 = i6;
while (i2 < itemInfo3.position) {
pageWidth = (this.mAdapter.getPageWidth(i2) + f) + f2;
i2++;
f2 = pageWidth;
}
itemInfo3.offset = f2;
f2 += itemInfo3.widthFactor + f;
clientWidth = i2 + 1;
f3 = f2;
i5 = clientWidth;
}
} else if (clientWidth > itemInfo.position) {
i4 = this.mItems.size() - 1;
f3 = itemInfo2.offset;
i5 = clientWidth - 1;
while (i5 >= itemInfo.position && i4 >= 0) {
itemInfo3 = (ItemInfo) this.mItems.get(i4);
while (i5 < itemInfo3.position && i4 > 0) {
i4--;
itemInfo3 = (ItemInfo) this.mItems.get(i4);
}
i6 = i5;
f2 = f3;
i2 = i6;
while (i2 > itemInfo3.position) {
pageWidth = f2 - (this.mAdapter.getPageWidth(i2) + f);
i2--;
f2 = pageWidth;
}
f2 -= itemInfo3.widthFactor + f;
itemInfo3.offset = f2;
clientWidth = i2 - 1;
f3 = f2;
i5 = clientWidth;
}
}
}
int size = this.mItems.size();
f2 = itemInfo.offset;
i2 = itemInfo.position - 1;
this.mFirstOffset = itemInfo.position == 0 ? itemInfo.offset : -3.4028235E38f;
this.mLastOffset = itemInfo.position == count + -1 ? (itemInfo.offset + itemInfo.widthFactor) - 1.0f : AutoScrollHelper.NO_MAX;
for (i3 = i - 1; i3 >= 0; i3--) {
itemInfo3 = (ItemInfo) this.mItems.get(i3);
while (i2 > itemInfo3.position) {
f2 -= this.mAdapter.getPageWidth(i2) + f;
i2--;
}
f2 -= itemInfo3.widthFactor + f;
itemInfo3.offset = f2;
if (itemInfo3.position == 0) {
this.mFirstOffset = f2;
}
i2--;
}
f2 = (itemInfo.offset + itemInfo.widthFactor) + f;
i2 = itemInfo.position + 1;
for (i3 = i + 1; i3 < size; i3++) {
itemInfo3 = (ItemInfo) this.mItems.get(i3);
while (i2 < itemInfo3.position) {
f2 += this.mAdapter.getPageWidth(i2) + f;
i2++;
}
if (itemInfo3.position == count - 1) {
this.mLastOffset = (itemInfo3.widthFactor + f2) - 1.0f;
}
itemInfo3.offset = f2;
f2 += itemInfo3.widthFactor + f;
i2++;
}
this.mNeedCalculatePageOffsets = false;
}
public Parcelable onSaveInstanceState() {
Parcelable savedState = new SavedState(super.onSaveInstanceState());
savedState.position = this.mCurItem;
if (this.mAdapter != null) {
savedState.adapterState = this.mAdapter.saveState();
}
return savedState;
}
public void onRestoreInstanceState(Parcelable parcelable) {
if (parcelable instanceof SavedState) {
SavedState savedState = (SavedState) parcelable;
super.onRestoreInstanceState(savedState.getSuperState());
if (this.mAdapter != null) {
this.mAdapter.restoreState(savedState.adapterState, savedState.loader);
setCurrentItemInternal(savedState.position, DEBUG, true);
return;
}
this.mRestoredCurItem = savedState.position;
this.mRestoredAdapterState = savedState.adapterState;
this.mRestoredClassLoader = savedState.loader;
return;
}
super.onRestoreInstanceState(parcelable);
}
public void addView(View view, int i, android.view.ViewGroup.LayoutParams layoutParams) {
android.view.ViewGroup.LayoutParams layoutParams2;
if (checkLayoutParams(layoutParams)) {
layoutParams2 = layoutParams;
} else {
layoutParams2 = generateLayoutParams(layoutParams);
}
LayoutParams layoutParams3 = (LayoutParams) layoutParams2;
layoutParams3.isDecor |= view instanceof Decor;
if (!this.mInLayout) {
super.addView(view, i, layoutParams2);
} else if (layoutParams3 == null || !layoutParams3.isDecor) {
layoutParams3.needsMeasure = true;
addViewInLayout(view, i, layoutParams2);
} else {
throw new IllegalStateException("Cannot add pager decor view during layout");
}
}
public void removeView(View view) {
if (this.mInLayout) {
removeViewInLayout(view);
} else {
super.removeView(view);
}
}
ItemInfo infoForChild(View view) {
for (int i = 0; i < this.mItems.size(); i++) {
ItemInfo itemInfo = (ItemInfo) this.mItems.get(i);
if (this.mAdapter.isViewFromObject(view, itemInfo.object)) {
return itemInfo;
}
}
return null;
}
ItemInfo infoForAnyChild(View view) {
while (true) {
ViewPager parent = view.getParent();
if (parent == this) {
return infoForChild(view);
}
if (parent == null || !(parent instanceof View)) {
break;
}
view = parent;
}
return null;
}
ItemInfo infoForPosition(int i) {
for (int i2 = 0; i2 < this.mItems.size(); i2++) {
ItemInfo itemInfo = (ItemInfo) this.mItems.get(i2);
if (itemInfo.position == i) {
return itemInfo;
}
}
return null;
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
this.mFirstLayout = true;
}
protected void onMeasure(int i, int i2) {
int i3;
int i4;
setMeasuredDimension(getDefaultSize(SCROLL_STATE_IDLE, i), getDefaultSize(SCROLL_STATE_IDLE, i2));
int measuredWidth = getMeasuredWidth();
this.mGutterSize = Math.min(measuredWidth / 10, this.mDefaultGutterSize);
int paddingLeft = (measuredWidth - getPaddingLeft()) - getPaddingRight();
int measuredHeight = (getMeasuredHeight() - getPaddingTop()) - getPaddingBottom();
int childCount = getChildCount();
for (int i5 = 0; i5 < childCount; i5++) {
LayoutParams layoutParams;
View childAt = getChildAt(i5);
if (childAt.getVisibility() != 8) {
layoutParams = (LayoutParams) childAt.getLayoutParams();
if (layoutParams != null && layoutParams.isDecor) {
Object obj;
Object obj2;
int i6 = layoutParams.gravity & 7;
int i7 = layoutParams.gravity & 112;
Object obj3 = ExploreByTouchHelper.INVALID_ID;
Object obj4 = ExploreByTouchHelper.INVALID_ID;
if (i7 == 48 || i7 == 80) {
int i8 = 1;
} else {
obj = null;
}
if (i6 == 3 || i6 == 5) {
i6 = 1;
} else {
obj2 = null;
}
if (obj != null) {
obj3 = 1073741824;
} else if (obj2 != null) {
obj4 = 1073741824;
}
if (layoutParams.width != -2) {
i7 = 1073741824;
i3 = layoutParams.width != -1 ? layoutParams.width : paddingLeft;
} else {
i7 = i3;
i3 = paddingLeft;
}
if (layoutParams.height != -2) {
i4 = 1073741824;
if (layoutParams.height != -1) {
measuredWidth = layoutParams.height;
childAt.measure(MeasureSpec.makeMeasureSpec(i3, i7), MeasureSpec.makeMeasureSpec(measuredWidth, i4));
if (obj != null) {
measuredHeight -= childAt.getMeasuredHeight();
} else if (obj2 != null) {
paddingLeft -= childAt.getMeasuredWidth();
}
}
}
measuredWidth = measuredHeight;
childAt.measure(MeasureSpec.makeMeasureSpec(i3, i7), MeasureSpec.makeMeasureSpec(measuredWidth, i4));
if (obj != null) {
measuredHeight -= childAt.getMeasuredHeight();
} else if (obj2 != null) {
paddingLeft -= childAt.getMeasuredWidth();
}
}
}
}
this.mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(paddingLeft, 1073741824);
this.mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(measuredHeight, 1073741824);
this.mInLayout = true;
populate();
this.mInLayout = false;
i3 = getChildCount();
for (i4 = 0; i4 < i3; i4++) {
View childAt2 = getChildAt(i4);
if (childAt2.getVisibility() != 8) {
layoutParams = (LayoutParams) childAt2.getLayoutParams();
if (layoutParams == null || !layoutParams.isDecor) {
childAt2.measure(MeasureSpec.makeMeasureSpec((int) (layoutParams.widthFactor * ((float) paddingLeft)), 1073741824), this.mChildHeightMeasureSpec);
}
}
}
}
protected void onSizeChanged(int i, int i2, int i3, int i4) {
super.onSizeChanged(i, i2, i3, i4);
if (i != i3) {
recomputeScrollPosition(i, i3, this.mPageMargin, this.mPageMargin);
}
}
private void recomputeScrollPosition(int i, int i2, int i3, int i4) {
if (i2 <= 0 || this.mItems.isEmpty()) {
ItemInfo infoForPosition = infoForPosition(this.mCurItem);
int min = (int) ((infoForPosition != null ? Math.min(infoForPosition.offset, this.mLastOffset) : AutoScrollHelper.RELATIVE_UNSPECIFIED) * ((float) ((i - getPaddingLeft()) - getPaddingRight())));
if (min != getScrollX()) {
completeScroll(DEBUG);
scrollTo(min, getScrollY());
}
} else if (this.mScroller.isFinished()) {
scrollTo((int) (((float) (((i - getPaddingLeft()) - getPaddingRight()) + i3)) * (((float) getScrollX()) / ((float) (((i2 - getPaddingLeft()) - getPaddingRight()) + i4)))), getScrollY());
} else {
this.mScroller.setFinalX(getCurrentItem() * getClientWidth());
}
}
protected void onLayout(boolean z, int i, int i2, int i3, int i4) {
LayoutParams layoutParams;
int max;
int childCount = getChildCount();
int i5 = i3 - i;
int i6 = i4 - i2;
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int scrollX = getScrollX();
int i7 = SCROLL_STATE_IDLE;
int i8 = 0;
while (i8 < childCount) {
int measuredWidth;
View childAt = getChildAt(i8);
if (childAt.getVisibility() != 8) {
layoutParams = (LayoutParams) childAt.getLayoutParams();
if (layoutParams.isDecor) {
int i9 = layoutParams.gravity & 112;
switch (layoutParams.gravity & 7) {
case SCROLL_STATE_DRAGGING:
max = Math.max((i5 - childAt.getMeasuredWidth()) / 2, paddingLeft);
break;
case XZBDevice.DOWNLOAD_LIST_FAILED:
max = paddingLeft;
paddingLeft = childAt.getMeasuredWidth() + paddingLeft;
break;
case XZBDevice.DOWNLOAD_LIST_UNCOMPLETED_AND_FAILED:
measuredWidth = (i5 - paddingRight) - childAt.getMeasuredWidth();
paddingRight += childAt.getMeasuredWidth();
max = measuredWidth;
break;
default:
max = paddingLeft;
break;
}
int i10;
switch (i9) {
case DEFAULT_GUTTER_SIZE:
measuredWidth = Math.max((i6 - childAt.getMeasuredHeight()) / 2, paddingTop);
i10 = paddingBottom;
paddingBottom = paddingTop;
paddingTop = i10;
break;
case R.styleable.AppCompatTheme_homeAsUpIndicator:
measuredWidth = childAt.getMeasuredHeight() + paddingTop;
i10 = paddingTop;
paddingTop = paddingBottom;
paddingBottom = measuredWidth;
measuredWidth = i10;
break;
case R.styleable.AppCompatTheme_panelMenuListTheme:
measuredWidth = (i6 - paddingBottom) - childAt.getMeasuredHeight();
i10 = paddingBottom + childAt.getMeasuredHeight();
paddingBottom = paddingTop;
paddingTop = i10;
break;
default:
measuredWidth = paddingTop;
i10 = paddingBottom;
paddingBottom = paddingTop;
paddingTop = i10;
break;
}
max += scrollX;
childAt.layout(max, measuredWidth, childAt.getMeasuredWidth() + max, childAt.getMeasuredHeight() + measuredWidth);
measuredWidth = i7 + 1;
i7 = paddingBottom;
paddingBottom = paddingTop;
paddingTop = paddingRight;
paddingRight = paddingLeft;
i8++;
paddingLeft = paddingRight;
paddingRight = paddingTop;
paddingTop = i7;
i7 = measuredWidth;
}
}
measuredWidth = i7;
i7 = paddingTop;
paddingTop = paddingRight;
paddingRight = paddingLeft;
i8++;
paddingLeft = paddingRight;
paddingRight = paddingTop;
paddingTop = i7;
i7 = measuredWidth;
}
max = (i5 - paddingLeft) - paddingRight;
for (paddingRight = 0; paddingRight < childCount; paddingRight++) {
View childAt2 = getChildAt(paddingRight);
if (childAt2.getVisibility() != 8) {
layoutParams = (LayoutParams) childAt2.getLayoutParams();
if (!layoutParams.isDecor) {
ItemInfo infoForChild = infoForChild(childAt2);
if (infoForChild != null) {
i5 = ((int) (infoForChild.offset * ((float) max))) + paddingLeft;
if (layoutParams.needsMeasure) {
layoutParams.needsMeasure = false;
childAt2.measure(MeasureSpec.makeMeasureSpec((int) (layoutParams.widthFactor * ((float) max)), 1073741824), MeasureSpec.makeMeasureSpec((i6 - paddingTop) - paddingBottom, 1073741824));
}
childAt2.layout(i5, paddingTop, childAt2.getMeasuredWidth() + i5, childAt2.getMeasuredHeight() + paddingTop);
}
}
}
}
this.mTopPageBounds = paddingTop;
this.mBottomPageBounds = i6 - paddingBottom;
this.mDecorChildCount = i7;
if (this.mFirstLayout) {
scrollToItem(this.mCurItem, DEBUG, SCROLL_STATE_IDLE, DEBUG);
}
this.mFirstLayout = false;
}
public void computeScroll() {
this.mIsScrollStarted = true;
if (this.mScroller.isFinished() || !this.mScroller.computeScrollOffset()) {
completeScroll(true);
return;
}
int scrollX = getScrollX();
int scrollY = getScrollY();
int currX = this.mScroller.getCurrX();
int currY = this.mScroller.getCurrY();
if (!(scrollX == currX && scrollY == currY)) {
scrollTo(currX, currY);
if (!pageScrolled(currX)) {
this.mScroller.abortAnimation();
scrollTo(SCROLL_STATE_IDLE, currY);
}
}
ViewCompat.postInvalidateOnAnimation(this);
}
private boolean pageScrolled(int i) {
if (this.mItems.size() != 0) {
ItemInfo infoForCurrentScrollPosition = infoForCurrentScrollPosition();
int clientWidth = getClientWidth();
int i2 = this.mPageMargin + clientWidth;
float f = ((float) this.mPageMargin) / ((float) clientWidth);
int i3 = infoForCurrentScrollPosition.position;
float f2 = ((((float) i) / ((float) clientWidth)) - infoForCurrentScrollPosition.offset) / (infoForCurrentScrollPosition.widthFactor + f);
clientWidth = (int) (((float) i2) * f2);
this.mCalledSuper = false;
onPageScrolled(i3, f2, clientWidth);
if (this.mCalledSuper) {
return true;
}
throw new IllegalStateException("onPageScrolled did not call superclass implementation");
} else if (this.mFirstLayout) {
return DEBUG;
} else {
this.mCalledSuper = false;
onPageScrolled(SCROLL_STATE_IDLE, AutoScrollHelper.RELATIVE_UNSPECIFIED, SCROLL_STATE_IDLE);
if (this.mCalledSuper) {
return DEBUG;
}
throw new IllegalStateException("onPageScrolled did not call superclass implementation");
}
}
protected void onPageScrolled(int i, float f, int i2) {
int paddingLeft;
int paddingRight;
int i3;
if (this.mDecorChildCount > 0) {
int scrollX = getScrollX();
paddingLeft = getPaddingLeft();
paddingRight = getPaddingRight();
int width = getWidth();
int childCount = getChildCount();
i3 = 0;
while (i3 < childCount) {
int i4;
View childAt = getChildAt(i3);
LayoutParams layoutParams = (LayoutParams) childAt.getLayoutParams();
if (layoutParams.isDecor) {
int max;
switch (layoutParams.gravity & 7) {
case SCROLL_STATE_DRAGGING:
max = Math.max((width - childAt.getMeasuredWidth()) / 2, paddingLeft);
i4 = paddingRight;
paddingRight = paddingLeft;
paddingLeft = i4;
break;
case XZBDevice.DOWNLOAD_LIST_FAILED:
max = childAt.getWidth() + paddingLeft;
i4 = paddingLeft;
paddingLeft = paddingRight;
paddingRight = max;
max = i4;
break;
case XZBDevice.DOWNLOAD_LIST_UNCOMPLETED_AND_FAILED:
max = (width - paddingRight) - childAt.getMeasuredWidth();
i4 = paddingRight + childAt.getMeasuredWidth();
paddingRight = paddingLeft;
paddingLeft = i4;
break;
default:
max = paddingLeft;
i4 = paddingRight;
paddingRight = paddingLeft;
paddingLeft = i4;
break;
}
max = (max + scrollX) - childAt.getLeft();
if (max != 0) {
childAt.offsetLeftAndRight(max);
}
} else {
i4 = paddingRight;
paddingRight = paddingLeft;
paddingLeft = i4;
}
i3++;
i4 = paddingLeft;
paddingLeft = paddingRight;
paddingRight = i4;
}
}
dispatchOnPageScrolled(i, f, i2);
if (this.mPageTransformer != null) {
paddingRight = getScrollX();
i3 = getChildCount();
for (paddingLeft = 0; paddingLeft < i3; paddingLeft++) {
View childAt2 = getChildAt(paddingLeft);
if (!((LayoutParams) childAt2.getLayoutParams()).isDecor) {
this.mPageTransformer.transformPage(childAt2, ((float) (childAt2.getLeft() - paddingRight)) / ((float) getClientWidth()));
}
}
}
this.mCalledSuper = true;
}
private void dispatchOnPageScrolled(int i, float f, int i2) {
if (this.mOnPageChangeListener != null) {
this.mOnPageChangeListener.onPageScrolled(i, f, i2);
}
if (this.mOnPageChangeListeners != null) {
int size = this.mOnPageChangeListeners.size();
for (int i3 = 0; i3 < size; i3++) {
OnPageChangeListener onPageChangeListener = (OnPageChangeListener) this.mOnPageChangeListeners.get(i3);
if (onPageChangeListener != null) {
onPageChangeListener.onPageScrolled(i, f, i2);
}
}
}
if (this.mInternalPageChangeListener != null) {
this.mInternalPageChangeListener.onPageScrolled(i, f, i2);
}
}
private void dispatchOnPageSelected(int i) {
if (this.mOnPageChangeListener != null) {
this.mOnPageChangeListener.onPageSelected(i);
}
if (this.mOnPageChangeListeners != null) {
int size = this.mOnPageChangeListeners.size();
for (int i2 = 0; i2 < size; i2++) {
OnPageChangeListener onPageChangeListener = (OnPageChangeListener) this.mOnPageChangeListeners.get(i2);
if (onPageChangeListener != null) {
onPageChangeListener.onPageSelected(i);
}
}
}
if (this.mInternalPageChangeListener != null) {
this.mInternalPageChangeListener.onPageSelected(i);
}
}
private void dispatchOnScrollStateChanged(int i) {
if (this.mOnPageChangeListener != null) {
this.mOnPageChangeListener.onPageScrollStateChanged(i);
}
if (this.mOnPageChangeListeners != null) {
int size = this.mOnPageChangeListeners.size();
for (int i2 = 0; i2 < size; i2++) {
OnPageChangeListener onPageChangeListener = (OnPageChangeListener) this.mOnPageChangeListeners.get(i2);
if (onPageChangeListener != null) {
onPageChangeListener.onPageScrollStateChanged(i);
}
}
}
if (this.mInternalPageChangeListener != null) {
this.mInternalPageChangeListener.onPageScrollStateChanged(i);
}
}
private void completeScroll(boolean z) {
boolean z2;
int i;
if (this.mScrollState == 2) {
int i2 = 1;
} else {
z2 = false;
}
if (z2) {
boolean z3;
setScrollingCacheEnabled(DEBUG);
if (this.mScroller.isFinished()) {
z3 = false;
} else {
i = 1;
}
if (z3) {
this.mScroller.abortAnimation();
i = getScrollX();
int scrollY = getScrollY();
int currX = this.mScroller.getCurrX();
int currY = this.mScroller.getCurrY();
if (!(i == currX && scrollY == currY)) {
scrollTo(currX, currY);
if (currX != i) {
pageScrolled(currX);
}
}
}
}
this.mPopulatePending = false;
boolean z4 = z2;
for (i = 0; i < this.mItems.size(); i++) {
ItemInfo itemInfo = (ItemInfo) this.mItems.get(i);
if (itemInfo.scrolling) {
itemInfo.scrolling = false;
scrollY = 1;
}
}
if (!z4) {
return;
}
if (z) {
ViewCompat.postOnAnimation(this, this.mEndScrollRunnable);
} else {
this.mEndScrollRunnable.run();
}
}
private boolean isGutterDrag(float f, float f2) {
return ((f >= ((float) this.mGutterSize) || f2 <= 0.0f) && (f <= ((float) (getWidth() - this.mGutterSize)) || f2 >= 0.0f)) ? DEBUG : true;
}
private void enableLayers(boolean z) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
ViewCompat.setLayerType(getChildAt(i), z ? SCROLL_STATE_SETTLING : 0, null);
}
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
int action = motionEvent.getAction() & 255;
if (action == 3 || action == 1) {
resetTouch();
return DEBUG;
}
if (action != 0) {
if (this.mIsBeingDragged) {
return true;
}
if (this.mIsUnableToDrag) {
return DEBUG;
}
}
switch (action) {
case SCROLL_STATE_IDLE:
float x = motionEvent.getX();
this.mInitialMotionX = x;
this.mLastMotionX = x;
x = motionEvent.getY();
this.mInitialMotionY = x;
this.mLastMotionY = x;
this.mActivePointerId = MotionEventCompat.getPointerId(motionEvent, SCROLL_STATE_IDLE);
this.mIsUnableToDrag = false;
this.mIsScrollStarted = true;
this.mScroller.computeScrollOffset();
if (this.mScrollState != 2 || Math.abs(this.mScroller.getFinalX() - this.mScroller.getCurrX()) <= this.mCloseEnough) {
completeScroll(DEBUG);
this.mIsBeingDragged = false;
} else {
this.mScroller.abortAnimation();
this.mPopulatePending = false;
populate();
this.mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
break;
case SCROLL_STATE_SETTLING:
action = this.mActivePointerId;
if (action != -1) {
action = MotionEventCompat.findPointerIndex(motionEvent, action);
float x2 = MotionEventCompat.getX(motionEvent, action);
float f = x2 - this.mLastMotionX;
float abs = Math.abs(f);
float y = MotionEventCompat.getY(motionEvent, action);
float abs2 = Math.abs(y - this.mInitialMotionY);
if (f == 0.0f || isGutterDrag(this.mLastMotionX, f) || !canScroll(this, DEBUG, (int) f, (int) x2, (int) y)) {
if (abs > ((float) this.mTouchSlop) && 0.5f * abs > abs2) {
this.mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
this.mLastMotionX = f > 0.0f ? this.mInitialMotionX + ((float) this.mTouchSlop) : this.mInitialMotionX - ((float) this.mTouchSlop);
this.mLastMotionY = y;
setScrollingCacheEnabled(true);
} else if (abs2 > ((float) this.mTouchSlop)) {
this.mIsUnableToDrag = true;
}
if (this.mIsBeingDragged && performDrag(x2)) {
ViewCompat.postInvalidateOnAnimation(this);
}
} else {
this.mLastMotionX = x2;
this.mLastMotionY = y;
this.mIsUnableToDrag = true;
return DEBUG;
}
}
case R.styleable.Toolbar_contentInsetEnd:
onSecondaryPointerUp(motionEvent);
break;
}
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
}
this.mVelocityTracker.addMovement(motionEvent);
return this.mIsBeingDragged;
}
public boolean onTouchEvent(MotionEvent motionEvent) {
boolean z = DEBUG;
if (this.mFakeDragging) {
return true;
}
if (motionEvent.getAction() == 0 && motionEvent.getEdgeFlags() != 0) {
return false;
}
if (this.mAdapter == null || this.mAdapter.getCount() == 0) {
return false;
}
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
}
this.mVelocityTracker.addMovement(motionEvent);
float x;
int xVelocity;
switch (motionEvent.getAction() & 255) {
case SCROLL_STATE_IDLE:
this.mScroller.abortAnimation();
this.mPopulatePending = false;
populate();
x = motionEvent.getX();
this.mInitialMotionX = x;
this.mLastMotionX = x;
x = motionEvent.getY();
this.mInitialMotionY = x;
this.mLastMotionY = x;
this.mActivePointerId = MotionEventCompat.getPointerId(motionEvent, SCROLL_STATE_IDLE);
break;
case SCROLL_STATE_DRAGGING:
if (this.mIsBeingDragged) {
VelocityTracker velocityTracker = this.mVelocityTracker;
velocityTracker.computeCurrentVelocity(IHost.HOST_NOFITY_REFRESH_LIST, (float) this.mMaximumVelocity);
xVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, this.mActivePointerId);
this.mPopulatePending = true;
int clientWidth = getClientWidth();
int scrollX = getScrollX();
ItemInfo infoForCurrentScrollPosition = infoForCurrentScrollPosition();
setCurrentItemInternal(determineTargetPage(infoForCurrentScrollPosition.position, ((((float) scrollX) / ((float) clientWidth)) - infoForCurrentScrollPosition.offset) / (infoForCurrentScrollPosition.widthFactor + (((float) this.mPageMargin) / ((float) clientWidth))), xVelocity, (int) (MotionEventCompat.getX(motionEvent, MotionEventCompat.findPointerIndex(motionEvent, this.mActivePointerId)) - this.mInitialMotionX)), true, true, xVelocity);
z = resetTouch();
}
break;
case SCROLL_STATE_SETTLING:
if (!this.mIsBeingDragged) {
xVelocity = MotionEventCompat.findPointerIndex(motionEvent, this.mActivePointerId);
if (xVelocity == -1) {
z = resetTouch();
} else {
float x2 = MotionEventCompat.getX(motionEvent, xVelocity);
float abs = Math.abs(x2 - this.mLastMotionX);
float y = MotionEventCompat.getY(motionEvent, xVelocity);
x = Math.abs(y - this.mLastMotionY);
if (abs > ((float) this.mTouchSlop) && abs > x) {
this.mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
if (x2 - this.mInitialMotionX > 0.0f) {
x = this.mInitialMotionX + ((float) this.mTouchSlop);
} else {
x = this.mInitialMotionX - ((float) this.mTouchSlop);
}
this.mLastMotionX = x;
this.mLastMotionY = y;
setScrollState(SCROLL_STATE_DRAGGING);
setScrollingCacheEnabled(true);
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
}
}
if (this.mIsBeingDragged) {
z = performDrag(MotionEventCompat.getX(motionEvent, MotionEventCompat.findPointerIndex(motionEvent, this.mActivePointerId))) | 0;
}
break;
case XZBDevice.DOWNLOAD_LIST_FAILED:
if (this.mIsBeingDragged) {
scrollToItem(this.mCurItem, true, SCROLL_STATE_IDLE, DEBUG);
z = resetTouch();
}
break;
case XZBDevice.DOWNLOAD_LIST_UNCOMPLETED_AND_FAILED:
xVelocity = MotionEventCompat.getActionIndex(motionEvent);
this.mLastMotionX = MotionEventCompat.getX(motionEvent, xVelocity);
this.mActivePointerId = MotionEventCompat.getPointerId(motionEvent, xVelocity);
break;
case R.styleable.Toolbar_contentInsetEnd:
onSecondaryPointerUp(motionEvent);
this.mLastMotionX = MotionEventCompat.getX(motionEvent, MotionEventCompat.findPointerIndex(motionEvent, this.mActivePointerId));
break;
}
if (z) {
ViewCompat.postInvalidateOnAnimation(this);
}
return true;
}
private boolean resetTouch() {
this.mActivePointerId = -1;
endDrag();
return this.mLeftEdge.onRelease() | this.mRightEdge.onRelease();
}
private void requestParentDisallowInterceptTouchEvent(boolean z) {
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(z);
}
}
private boolean performDrag(float f) {
float f2;
Object obj = SCROLL_STATE_DRAGGING;
boolean z = DEBUG;
float f3 = this.mLastMotionX - f;
this.mLastMotionX = f;
float scrollX = ((float) getScrollX()) + f3;
int clientWidth = getClientWidth();
float f4 = ((float) clientWidth) * this.mFirstOffset;
float f5 = ((float) clientWidth) * this.mLastOffset;
ItemInfo itemInfo = (ItemInfo) this.mItems.get(SCROLL_STATE_IDLE);
ItemInfo itemInfo2 = (ItemInfo) this.mItems.get(this.mItems.size() - 1);
if (itemInfo.position != 0) {
f4 = itemInfo.offset * ((float) clientWidth);
boolean z2 = false;
} else {
int i = 1;
}
if (itemInfo2.position != this.mAdapter.getCount() - 1) {
f2 = itemInfo2.offset * ((float) clientWidth);
boolean z3 = false;
} else {
f2 = f5;
}
if (scrollX < f4) {
if (z2) {
z = this.mLeftEdge.onPull(Math.abs(f4 - scrollX) / ((float) clientWidth));
}
} else if (scrollX > f2) {
if (z3) {
z = this.mRightEdge.onPull(Math.abs(scrollX - f2) / ((float) clientWidth));
}
f4 = f2;
} else {
f4 = scrollX;
}
this.mLastMotionX += f4 - ((float) ((int) f4));
scrollTo((int) f4, getScrollY());
pageScrolled((int) f4);
return z;
}
private ItemInfo infoForCurrentScrollPosition() {
float f;
int clientWidth = getClientWidth();
float scrollX = clientWidth > 0 ? ((float) getScrollX()) / ((float) clientWidth) : 0.0f;
if (clientWidth > 0) {
f = ((float) this.mPageMargin) / ((float) clientWidth);
} else {
f = 0.0f;
}
float f2 = 0.0f;
float f3 = 0.0f;
int i = -1;
int i2 = 0;
int i3 = 1;
ItemInfo itemInfo = null;
while (i2 < this.mItems.size()) {
int i4;
ItemInfo itemInfo2;
ItemInfo itemInfo3 = (ItemInfo) this.mItems.get(i2);
Object obj;
ItemInfo itemInfo4;
if (obj != null || itemInfo3.position == i + 1) {
itemInfo4 = itemInfo3;
i4 = i2;
itemInfo2 = itemInfo4;
} else {
itemInfo3 = this.mTempItem;
itemInfo3.offset = (f2 + f3) + f;
itemInfo3.position = i + 1;
itemInfo3.widthFactor = this.mAdapter.getPageWidth(itemInfo3.position);
itemInfo4 = itemInfo3;
i4 = i2 - 1;
itemInfo2 = itemInfo4;
}
f2 = itemInfo2.offset;
f3 = (itemInfo2.widthFactor + f2) + f;
if (obj == null && scrollX < f2) {
return itemInfo;
}
if (scrollX >= f3 && i4 != this.mItems.size() - 1) {
f3 = f2;
i = itemInfo2.position;
obj = null;
f2 = itemInfo2.widthFactor;
itemInfo = itemInfo2;
i2 = i4 + 1;
}
return itemInfo2;
}
return itemInfo;
}
private int determineTargetPage(int i, float f, int i2, int i3) {
if (Math.abs(i3) <= this.mFlingDistance || Math.abs(i2) <= this.mMinimumVelocity) {
i = (int) ((i >= this.mCurItem ? 0.4f : 0.6f) + (((float) i) + f));
} else if (i2 <= 0) {
i++;
}
if (this.mItems.size() <= 0) {
return i;
}
return Math.max(((ItemInfo) this.mItems.get(SCROLL_STATE_IDLE)).position, Math.min(i, ((ItemInfo) this.mItems.get(this.mItems.size() - 1)).position));
}
public void draw(Canvas canvas) {
super.draw(canvas);
int i = SCROLL_STATE_IDLE;
int overScrollMode = ViewCompat.getOverScrollMode(this);
if (overScrollMode == 0 || (overScrollMode == 1 && this.mAdapter != null && this.mAdapter.getCount() > 1)) {
int width;
if (!this.mLeftEdge.isFinished()) {
overScrollMode = canvas.save();
i = (getHeight() - getPaddingTop()) - getPaddingBottom();
width = getWidth();
canvas.rotate(270.0f);
canvas.translate((float) ((-i) + getPaddingTop()), this.mFirstOffset * ((float) width));
this.mLeftEdge.setSize(i, width);
i = this.mLeftEdge.draw(canvas) | 0;
canvas.restoreToCount(overScrollMode);
}
if (!this.mRightEdge.isFinished()) {
overScrollMode = canvas.save();
width = getWidth();
int height = (getHeight() - getPaddingTop()) - getPaddingBottom();
canvas.rotate(90.0f);
canvas.translate((float) (-getPaddingTop()), (-(this.mLastOffset + 1.0f)) * ((float) width));
this.mRightEdge.setSize(height, width);
i |= this.mRightEdge.draw(canvas);
canvas.restoreToCount(overScrollMode);
}
} else {
this.mLeftEdge.finish();
this.mRightEdge.finish();
}
if (i != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (this.mPageMargin > 0 && this.mMarginDrawable != null && this.mItems.size() > 0 && this.mAdapter != null) {
int scrollX = getScrollX();
int width = getWidth();
float f = ((float) this.mPageMargin) / ((float) width);
ItemInfo itemInfo = (ItemInfo) this.mItems.get(SCROLL_STATE_IDLE);
float f2 = itemInfo.offset;
int size = this.mItems.size();
int i = itemInfo.position;
int i2 = ((ItemInfo) this.mItems.get(size - 1)).position;
int i3 = 0;
int i4 = i;
while (i4 < i2) {
float f3;
while (i4 > itemInfo.position && i3 < size) {
i3++;
itemInfo = (ItemInfo) this.mItems.get(i3);
}
if (i4 == itemInfo.position) {
f3 = (itemInfo.offset + itemInfo.widthFactor) * ((float) width);
f2 = (itemInfo.offset + itemInfo.widthFactor) + f;
} else {
float pageWidth = this.mAdapter.getPageWidth(i4);
f3 = (f2 + pageWidth) * ((float) width);
f2 += pageWidth + f;
}
if (((float) this.mPageMargin) + f3 > ((float) scrollX)) {
this.mMarginDrawable.setBounds(Math.round(f3), this.mTopPageBounds, Math.round(((float) this.mPageMargin) + f3), this.mBottomPageBounds);
this.mMarginDrawable.draw(canvas);
}
if (f3 <= ((float) (scrollX + width))) {
i4++;
} else {
return;
}
}
}
}
public boolean beginFakeDrag() {
if (this.mIsBeingDragged) {
return DEBUG;
}
this.mFakeDragging = true;
setScrollState(SCROLL_STATE_DRAGGING);
this.mLastMotionX = 0.0f;
this.mInitialMotionX = 0.0f;
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
} else {
this.mVelocityTracker.clear();
}
long uptimeMillis = SystemClock.uptimeMillis();
MotionEvent obtain = MotionEvent.obtain(uptimeMillis, uptimeMillis, SCROLL_STATE_IDLE, AutoScrollHelper.RELATIVE_UNSPECIFIED, 0.0f, 0);
this.mVelocityTracker.addMovement(obtain);
obtain.recycle();
this.mFakeDragBeginTime = uptimeMillis;
return true;
}
public void endFakeDrag() {
if (this.mFakeDragging) {
if (this.mAdapter != null) {
VelocityTracker velocityTracker = this.mVelocityTracker;
velocityTracker.computeCurrentVelocity(IHost.HOST_NOFITY_REFRESH_LIST, (float) this.mMaximumVelocity);
int xVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, this.mActivePointerId);
this.mPopulatePending = true;
int clientWidth = getClientWidth();
int scrollX = getScrollX();
ItemInfo infoForCurrentScrollPosition = infoForCurrentScrollPosition();
setCurrentItemInternal(determineTargetPage(infoForCurrentScrollPosition.position, ((((float) scrollX) / ((float) clientWidth)) - infoForCurrentScrollPosition.offset) / infoForCurrentScrollPosition.widthFactor, xVelocity, (int) (this.mLastMotionX - this.mInitialMotionX)), true, true, xVelocity);
}
endDrag();
this.mFakeDragging = false;
return;
}
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
public void fakeDragBy(float f) {
if (!this.mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
} else if (this.mAdapter != null) {
float f2;
float f3;
this.mLastMotionX += f;
float scrollX = ((float) getScrollX()) - f;
int clientWidth = getClientWidth();
float f4 = ((float) clientWidth) * this.mFirstOffset;
float f5 = ((float) clientWidth) * this.mLastOffset;
ItemInfo itemInfo = (ItemInfo) this.mItems.get(SCROLL_STATE_IDLE);
ItemInfo itemInfo2 = (ItemInfo) this.mItems.get(this.mItems.size() - 1);
if (itemInfo.position != 0) {
f2 = itemInfo.offset * ((float) clientWidth);
} else {
f2 = f4;
}
if (itemInfo2.position != this.mAdapter.getCount() - 1) {
f3 = itemInfo2.offset * ((float) clientWidth);
} else {
f3 = f5;
}
if (scrollX >= f2) {
if (scrollX > f3) {
f2 = f3;
} else {
f2 = scrollX;
}
}
this.mLastMotionX += f2 - ((float) ((int) f2));
scrollTo((int) f2, getScrollY());
pageScrolled((int) f2);
MotionEvent obtain = MotionEvent.obtain(this.mFakeDragBeginTime, SystemClock.uptimeMillis(), SCROLL_STATE_SETTLING, this.mLastMotionX, AutoScrollHelper.RELATIVE_UNSPECIFIED, SCROLL_STATE_IDLE);
this.mVelocityTracker.addMovement(obtain);
obtain.recycle();
}
}
public boolean isFakeDragging() {
return this.mFakeDragging;
}
private void onSecondaryPointerUp(MotionEvent motionEvent) {
int actionIndex = MotionEventCompat.getActionIndex(motionEvent);
if (MotionEventCompat.getPointerId(motionEvent, actionIndex) == this.mActivePointerId) {
actionIndex = actionIndex == 0 ? SCROLL_STATE_DRAGGING : SCROLL_STATE_IDLE;
this.mLastMotionX = MotionEventCompat.getX(motionEvent, actionIndex);
this.mActivePointerId = MotionEventCompat.getPointerId(motionEvent, actionIndex);
if (this.mVelocityTracker != null) {
this.mVelocityTracker.clear();
}
}
}
private void endDrag() {
this.mIsBeingDragged = false;
this.mIsUnableToDrag = false;
if (this.mVelocityTracker != null) {
this.mVelocityTracker.recycle();
this.mVelocityTracker = null;
}
}
private void setScrollingCacheEnabled(boolean z) {
if (this.mScrollingCacheEnabled != z) {
this.mScrollingCacheEnabled = z;
}
}
public boolean canScrollHorizontally(int i) {
if (this.mAdapter == null) {
return DEBUG;
}
int clientWidth = getClientWidth();
int scrollX = getScrollX();
return i < 0 ? scrollX > ((int) (((float) clientWidth) * this.mFirstOffset)) ? true : DEBUG : (i <= 0 || scrollX >= ((int) (((float) clientWidth) * this.mLastOffset))) ? DEBUG : true;
}
protected boolean canScroll(View view, boolean z, int i, int i2, int i3) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
int scrollX = view.getScrollX();
int scrollY = view.getScrollY();
for (int childCount = viewGroup.getChildCount() - 1; childCount >= 0; childCount--) {
View childAt = viewGroup.getChildAt(childCount);
if (i2 + scrollX >= childAt.getLeft() && i2 + scrollX < childAt.getRight() && i3 + scrollY >= childAt.getTop() && i3 + scrollY < childAt.getBottom()) {
if (canScroll(childAt, true, i, (i2 + scrollX) - childAt.getLeft(), (i3 + scrollY) - childAt.getTop())) {
return true;
}
}
}
}
return (z && ViewCompat.canScrollHorizontally(view, -i)) ? true : DEBUG;
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
return (super.dispatchKeyEvent(keyEvent) || executeKeyEvent(keyEvent)) ? true : DEBUG;
}
public boolean executeKeyEvent(KeyEvent keyEvent) {
if (keyEvent.getAction() != 0) {
return DEBUG;
}
switch (keyEvent.getKeyCode()) {
case R.styleable.Toolbar_navigationContentDescription:
return arrowScroll(R.styleable.Toolbar_maxButtonHeight);
case R.styleable.Toolbar_logoDescription:
return arrowScroll(R.styleable.AppCompatTheme_textAppearanceSearchResultSubtitle);
case R.styleable.AppCompatTheme_popupWindowStyle:
if (VERSION.SDK_INT < 11) {
return DEBUG;
}
if (KeyEventCompat.hasNoModifiers(keyEvent)) {
return arrowScroll(SCROLL_STATE_SETTLING);
}
return KeyEventCompat.hasModifiers(keyEvent, SCROLL_STATE_DRAGGING) ? arrowScroll(SCROLL_STATE_DRAGGING) : DEBUG;
default:
return DEBUG;
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public boolean arrowScroll(int r10) {
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.view.ViewPager.arrowScroll(int):boolean");
/*
this = this;
r1 = 0;
r8 = 66;
r7 = 17;
r4 = 1;
r3 = 0;
r2 = r9.findFocus();
if (r2 != r9) goto L_0x003e;
L_0x000d:
r0 = r1;
L_0x000e:
r1 = android.view.FocusFinder.getInstance();
r1 = r1.findNextFocus(r9, r0, r10);
if (r1 == 0) goto L_0x00b3;
L_0x0018:
if (r1 == r0) goto L_0x00b3;
L_0x001a:
if (r10 != r7) goto L_0x0098;
L_0x001c:
r2 = r9.mTempRect;
r2 = r9.getChildRectInPagerCoordinates(r2, r1);
r2 = r2.left;
r3 = r9.mTempRect;
r3 = r9.getChildRectInPagerCoordinates(r3, r0);
r3 = r3.left;
if (r0 == 0) goto L_0x0093;
L_0x002e:
if (r2 < r3) goto L_0x0093;
L_0x0030:
r0 = r9.pageLeft();
L_0x0034:
if (r0 == 0) goto L_0x003d;
L_0x0036:
r1 = android.view.SoundEffectConstants.getContantForFocusDirection(r10);
r9.playSoundEffect(r1);
L_0x003d:
return r0;
L_0x003e:
if (r2 == 0) goto L_0x00cb;
L_0x0040:
r0 = r2.getParent();
L_0x0044:
r5 = r0 instanceof android.view.ViewGroup;
if (r5 == 0) goto L_0x00ce;
L_0x0048:
if (r0 != r9) goto L_0x007c;
L_0x004a:
r0 = r4;
L_0x004b:
if (r0 != 0) goto L_0x00cb;
L_0x004d:
r5 = new java.lang.StringBuilder;
r5.<init>();
r0 = r2.getClass();
r0 = r0.getSimpleName();
r5.append(r0);
r0 = r2.getParent();
L_0x0061:
r2 = r0 instanceof android.view.ViewGroup;
if (r2 == 0) goto L_0x0081;
L_0x0065:
r2 = " => ";
r2 = r5.append(r2);
r6 = r0.getClass();
r6 = r6.getSimpleName();
r2.append(r6);
r0 = r0.getParent();
goto L_0x0061;
L_0x007c:
r0 = r0.getParent();
goto L_0x0044;
L_0x0081:
r0 = new java.lang.StringBuilder;
r2 = "arrowScroll tried to find focus based on non-child current focused view ";
r0.<init>(r2);
r2 = r5.toString();
r0.append(r2);
r0 = r1;
goto L_0x000e;
L_0x0093:
r0 = r1.requestFocus();
goto L_0x0034;
L_0x0098:
if (r10 != r8) goto L_0x00c8;
L_0x009a:
r2 = r9.mTempRect;
r2 = r9.getChildRectInPagerCoordinates(r2, r1);
r2 = r2.left;
r3 = r9.mTempRect;
r3 = r9.getChildRectInPagerCoordinates(r3, r0);
r3 = r3.left;
if (r0 == 0) goto L_0x00ae;
L_0x00ac:
if (r2 <= r3) goto L_0x00c2;
L_0x00ae:
r0 = r1.requestFocus();
goto L_0x0034;
L_0x00b3:
if (r10 == r7) goto L_0x00b7;
L_0x00b5:
if (r10 != r4) goto L_0x00bd;
L_0x00b7:
r0 = r9.pageLeft();
goto L_0x0034;
L_0x00bd:
if (r10 == r8) goto L_0x00c2;
L_0x00bf:
r0 = 2;
if (r10 != r0) goto L_0x00c8;
L_0x00c2:
r0 = r9.pageRight();
goto L_0x0034;
L_0x00c8:
r0 = r3;
goto L_0x0034;
L_0x00cb:
r0 = r2;
goto L_0x000e;
L_0x00ce:
r0 = r3;
goto L_0x004b;
*/
}
private Rect getChildRectInPagerCoordinates(Rect rect, View view) {
Rect rect2;
if (rect == null) {
rect2 = new Rect();
} else {
rect2 = rect;
}
if (view == null) {
rect2.set(SCROLL_STATE_IDLE, SCROLL_STATE_IDLE, SCROLL_STATE_IDLE, SCROLL_STATE_IDLE);
return rect2;
}
rect2.left = view.getLeft();
rect2.right = view.getRight();
rect2.top = view.getTop();
rect2.bottom = view.getBottom();
ViewParent parent = view.getParent();
while ((r0 instanceof ViewGroup) && r0 != this) {
ViewGroup viewGroup = r0;
rect2.left += viewGroup.getLeft();
rect2.right += viewGroup.getRight();
rect2.top += viewGroup.getTop();
rect2.bottom += viewGroup.getBottom();
parent = viewGroup.getParent();
}
return rect2;
}
boolean pageLeft() {
if (this.mCurItem <= 0) {
return DEBUG;
}
setCurrentItem(this.mCurItem - 1, true);
return true;
}
boolean pageRight() {
if (this.mAdapter == null || this.mCurItem >= this.mAdapter.getCount() - 1) {
return DEBUG;
}
setCurrentItem(this.mCurItem + 1, true);
return true;
}
public void addFocusables(ArrayList<View> arrayList, int i, int i2) {
int size = arrayList.size();
int descendantFocusability = getDescendantFocusability();
if (descendantFocusability != 393216) {
for (int i3 = SCROLL_STATE_IDLE; i3 < getChildCount(); i3++) {
View childAt = getChildAt(i3);
if (childAt.getVisibility() == 0) {
ItemInfo infoForChild = infoForChild(childAt);
if (infoForChild != null && infoForChild.position == this.mCurItem) {
childAt.addFocusables(arrayList, i, i2);
}
}
}
}
if ((descendantFocusability == 262144 && size != arrayList.size()) || !isFocusable()) {
return;
}
if (((i2 & 1) != 1 || !isInTouchMode() || isFocusableInTouchMode()) && arrayList != null) {
arrayList.add(this);
}
}
public void addTouchables(ArrayList<View> arrayList) {
for (int i = SCROLL_STATE_IDLE; i < getChildCount(); i++) {
View childAt = getChildAt(i);
if (childAt.getVisibility() == 0) {
ItemInfo infoForChild = infoForChild(childAt);
if (infoForChild != null && infoForChild.position == this.mCurItem) {
childAt.addTouchables(arrayList);
}
}
}
}
protected boolean onRequestFocusInDescendants(int i, Rect rect) {
int i2;
int i3 = INVALID_POINTER;
int childCount = getChildCount();
if ((i & 2) != 0) {
i3 = 1;
i2 = 0;
} else {
i2 = childCount - 1;
childCount = -1;
}
while (i2 != childCount) {
View childAt = getChildAt(i2);
if (childAt.getVisibility() == 0) {
ItemInfo infoForChild = infoForChild(childAt);
if (infoForChild != null && infoForChild.position == this.mCurItem && childAt.requestFocus(i, rect)) {
return true;
}
}
i2 += i3;
}
return false;
}
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
if (accessibilityEvent.getEventType() == 4096) {
return super.dispatchPopulateAccessibilityEvent(accessibilityEvent);
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childAt = getChildAt(i);
if (childAt.getVisibility() == 0) {
ItemInfo infoForChild = infoForChild(childAt);
if (infoForChild != null && infoForChild.position == this.mCurItem && childAt.dispatchPopulateAccessibilityEvent(accessibilityEvent)) {
return true;
}
}
}
return DEBUG;
}
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams layoutParams) {
return generateDefaultLayoutParams();
}
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams layoutParams) {
return ((layoutParams instanceof LayoutParams) && super.checkLayoutParams(layoutParams)) ? true : DEBUG;
}
public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attributeSet) {
return new LayoutParams(getContext(), attributeSet);
}
}
|
/*
* Copyright 2008-2013 Exigen Insurance Solutions, Inc. All Rights Reserved.
*
*/
package com.exigeninsurance.x4j.analytic.xlsx.transform.pdf.header.rule;
import org.apache.poi.xssf.usermodel.XSSFSheet;
public class OddFooterRule extends HeaderFooterApplicabilityRule {
@Override
public boolean isApplicable(int pageNumber, XSSFSheet sheet) {
String firstHeader = sheet.getCTWorksheet().getHeaderFooter().getFirstFooter();
String evenHeader = sheet.getCTWorksheet().getHeaderFooter().getEvenFooter();
if (pageNumber == 1 && isHeaderFooterValid(firstHeader)) {
return false;
}
return !((pageNumber % 2 == 0) && isHeaderFooterValid(evenHeader));
}
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor;
import com.google.common.collect.ImmutableList;
import com.yahoo.tensor.evaluation.MapEvaluationContext;
import com.yahoo.tensor.evaluation.Name;
import com.yahoo.tensor.evaluation.VariableTensor;
import com.yahoo.tensor.functions.ConstantTensor;
import com.yahoo.tensor.functions.Join;
import com.yahoo.tensor.functions.Reduce;
import com.yahoo.tensor.functions.TensorFunction;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.DoubleBinaryOperator;
import java.util.stream.Collectors;
import static com.yahoo.tensor.TensorType.Dimension.Type;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests tensor functionality
*
* @author bratseth
*/
public class TensorTestCase {
@Test
public void testStringForm() {
assertEquals("tensor():{5.7}", Tensor.from("{5.7}").toString());
assertTrue(Tensor.from("tensor():{5.7}") instanceof IndexedTensor);
assertEquals("tensor(d1{},d2{}):{{d1:l1,d2:l1}:5.0,{d1:l1,d2:l2}:6.0}", Tensor.from("{ {d1:l1,d2:l1}: 5, {d2:l2, d1:l1}:6.0} ").toString());
assertEquals("tensor(d1{},d2{}):{{d1:l1,d2:l1}:-5.3,{d1:l1,d2:l2}:0.0}", Tensor.from("{ {d1:l1,d2:l1}:-5.3, {d2:l2, d1:l1}:0}").toString());
assertEquals("Labels are quoted when necessary",
"tensor(d1{}):{{d1:\"'''\"}:6.0,{d1:'[[\":\"]]'}:5.0}",
Tensor.from("{ {d1:'[[\":\"]]'}: 5, {d1:\"'''\"}:6.0 }").toString());
}
@Test
public void testValueTypes() {
assertEquals(Tensor.from("tensor<double>(x[1]):{{x:0}:5}").getClass(), IndexedDoubleTensor.class);
assertEquals(Tensor.Builder.of(TensorType.fromSpec("tensor<double>(x[1])")).cell(5.0, 0).build().getClass(),
IndexedDoubleTensor.class);
assertEquals(Tensor.from("tensor<float>(x[1]):{{x:0}:5}").getClass(), IndexedFloatTensor.class);
assertEquals(Tensor.Builder.of(TensorType.fromSpec("tensor<float>(x[1])")).cell(5.0, 0).build().getClass(),
IndexedFloatTensor.class);
}
@Test
public void testParseError() {
try {
Tensor.from("--");
fail("Expected parse error");
}
catch (IllegalArgumentException expected) {
assertEquals("Excepted a number or a string starting by {, [ or tensor(...):, got '--'",
expected.getCause().getMessage());
}
}
@Test
public void testDimensions() {
Set<String> dimensions1 = Tensor.from("{} ").type().dimensionNames();
assertEquals(0, dimensions1.size());
Set<String> dimensions2 = Tensor.from("{ {d1:l1, d2:l2}:5, {d1:l2, d2:l2}:6.0} ").type().dimensionNames();
assertEquals(2, dimensions2.size());
assertTrue(dimensions2.contains("d1"));
assertTrue(dimensions2.contains("d2"));
Set<String> dimensions3 = Tensor.from("{ {d1:l1, d2:l1, d3:l1}:5, {d1:l1, d2:l2, d3:l1}:6.0} ").type().dimensionNames();
assertEquals(3, dimensions3.size());
assertTrue(dimensions3.contains("d1"));
assertTrue(dimensions3.contains("d2"));
assertTrue(dimensions3.contains("d3"));
}
@Test
public void testExpressions() {
Tensor y = Tensor.from("{{y:1}:3}");
Tensor x = Tensor.from("{{x:0}:5,{x:1}:7}");
Tensor xy = Tensor.from("{{x:0,y:1}:11, {x:1,y:1}:13}");
double nest1 = y.multiply(x.multiply(xy).sum("x")).sum("y").asDouble();
double nest2 = x.multiply(xy).sum("x").multiply(y).sum("y").asDouble();
double flat = y.multiply(x).multiply(xy).sum(ImmutableList.of("x","y")).asDouble();
assertEquals(nest1, flat, 0.000000001);
assertEquals(nest2, flat, 0.000000001);
}
@Test
public void testCombineInDimensionIndexed() {
Tensor input = Tensor.from("tensor(input[2]):{{input:0}:3, {input:1}:7}");
Tensor result = input.concat(11, "input");
assertEquals("tensor(input[3]):[3.0, 7.0, 11.0]", result.toString());
}
/** All functions are more throughly tested in searchlib EvaluationTestCase */
@Test
public void testTensorComputation() {
Tensor tensor1 = Tensor.from("{ {x:1}:3, {x:2}:7 }");
Tensor tensor2 = Tensor.from("{ {y:1}:5 }");
assertEquals(Tensor.from("{ {x:1,y:1}:15, {x:2,y:1}:35 }"), tensor1.multiply(tensor2));
assertEquals(Tensor.from("{ {x:1,y:1}:12, {x:2,y:1}:28 }"), tensor1.join(tensor2, (a, b) -> a * b - a ));
assertEquals(Tensor.from("{ {x:1,y:1}:0, {x:2,y:1}:1 }"), tensor1.larger(tensor2));
assertEquals(Tensor.from("{ {y:1}:50.0 }"), tensor1.matmul(tensor2, "x"));
assertEquals(Tensor.from("{ {z:1}:3, {z:2}:7 }"), tensor1.rename("x", "z"));
assertEquals(Tensor.from("{ {y:1,x:1}:8, {x:1,y:2}:12 }"), tensor1.add(tensor2).rename(ImmutableList.of("x", "y"),
ImmutableList.of("y", "x")));
assertEquals(Tensor.from("{ {x:0,y:0}:0, {x:0,y:1}:0, {x:1,y:0}:0, {x:1,y:1}:1, {x:2,y:0}:0, {x:2,y:1}:2, }"),
Tensor.generate(new TensorType.Builder().indexed("x", 3).indexed("y", 2).build(),
(List<Long> indexes) -> (double)indexes.get(0)*indexes.get(1)));
assertEquals(Tensor.from("{ {x:0,y:0,z:0}:0, {x:0,y:1,z:0}:1, {x:1,y:0,z:0}:1, {x:1,y:1,z:0}:2, {x:2,y:0,z:0}:2, {x:2,y:1,z:0}:3, "+
" {x:0,y:0,z:1}:1, {x:0,y:1,z:1}:2, {x:1,y:0,z:1}:2, {x:1,y:1,z:1}:3, {x:2,y:0,z:1}:3, {x:2,y:1,z:1}:4 }"),
Tensor.range(new TensorType.Builder().indexed("x", 3).indexed("y", 2).indexed("z", 2).build()));
assertEquals(Tensor.from("{ {x:0,y:0,z:0}:1, {x:0,y:1,z:0}:0, {x:1,y:0,z:0}:0, {x:1,y:1,z:0}:0, {x:2,y:0,z:0}:0, {x:2,y:1,z:0}:0, "+
" {x:0,y:0,z:1}:0, {x:0,y:1,z:1}:0, {x:1,y:0,z:1}:0, {x:1,y:1,z:1}:1, {x:2,y:0,z:1}:0, {x:2,y:1,z:1}:00 } "),
Tensor.diag(new TensorType.Builder().indexed("x", 3).indexed("y", 2).indexed("z", 2).build()));
assertEquals(Tensor.from("{ {x:1}:0, {x:3}:1, {x:9}:0 }"), Tensor.from("{ {x:1}:1, {x:3}:5, {x:9}:3 }").argmax("x"));
}
/** Test the same computation made in various ways which are implemented with special-case optimizations */
@Test
public void testOptimizedComputation() {
assertEquals("Mapped vector", 42, (int)dotProduct(vector(Type.mapped), vectors(Type.mapped, 2)));
assertEquals("Indexed unbound vector", 42, (int)dotProduct(vector(3, Type.indexedUnbound), vectors(5, Type.indexedUnbound, 2)));
assertEquals("Indexed unbound vector", 42, (int)dotProduct(vector(5, Type.indexedUnbound), vectors(3, Type.indexedUnbound, 2)));
assertEquals("Indexed bound vector", 42, (int)dotProduct(vector(3, Type.indexedBound), vectors(5, Type.indexedBound, 2)));
assertEquals("Indexed bound vector", 42, (int)dotProduct(vector(5, Type.indexedBound), vectors(3, Type.indexedBound, 2)));
assertEquals("Mapped matrix", 42, (int)dotProduct(vector(Type.mapped), matrix(Type.mapped, 2)));
assertEquals("Indexed unbound matrix", 42, (int)dotProduct(vector(3, Type.indexedUnbound), matrix(5, Type.indexedUnbound, 2)));
assertEquals("Indexed unbound matrix", 42, (int)dotProduct(vector(5, Type.indexedUnbound), matrix(3, Type.indexedUnbound, 2)));
assertEquals("Indexed bound matrix", 42, (int)dotProduct(vector(3, Type.indexedBound), matrix(5, Type.indexedBound, 2)));
assertEquals("Indexed bound matrix", 42, (int)dotProduct(vector(5, Type.indexedBound), matrix(3, Type.indexedBound, 2)));
assertEquals("Mixed vector", 42, (int)dotProduct(vector(Type.mapped), vectors(Type.indexedUnbound, 2)));
assertEquals("Mixed vector", 42, (int)dotProduct(vector(Type.mapped), vectors(Type.indexedUnbound, 2)));
assertEquals("Mixed matrix", 42, (int)dotProduct(vector(Type.mapped), matrix(Type.indexedUnbound, 2)));
assertEquals("Mixed matrix", 42, (int)dotProduct(vector(Type.mapped), matrix(Type.indexedUnbound, 2)));
assertEquals("Mixed vector", 42, (int)dotProduct(vector(Type.indexedUnbound), vectors(Type.mapped, 2)));
assertEquals("Mixed vector", 42, (int)dotProduct(vector(Type.indexedUnbound), vectors(Type.mapped, 2)));
assertEquals("Mixed matrix", 42, (int)dotProduct(vector(Type.indexedUnbound), matrix(Type.mapped, 2)));
assertEquals("Mixed matrix", 42, (int)dotProduct(vector(Type.indexedUnbound), matrix(Type.mapped, 2)));
// Test the unoptimized path by joining in another dimension
Tensor unitJ = Tensor.Builder.of(new TensorType.Builder().mapped("j").build()).cell().label("j", 0).value(1).build();
Tensor unitK = Tensor.Builder.of(new TensorType.Builder().mapped("k").build()).cell().label("k", 0).value(1).build();
Tensor vectorInJSpace = vector(Type.mapped).multiply(unitJ);
Tensor matrixInKSpace = matrix(Type.mapped, 2).get(0).multiply(unitK);
assertEquals("Generic computation implementation", 42, (int)dotProduct(vectorInJSpace, Collections.singletonList(matrixInKSpace)));
}
@Test
public void testTensorModify() {
assertTensorModify((left, right) -> right,
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1, {x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:0}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:0}"));
assertTensorModify((left, right) -> left + right,
Tensor.from("tensor(x[1],y[2])", "{{x:0,y:0}:1, {x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:3}"),
Tensor.from("tensor(x[1],y[2])", "{{x:0,y:0}:1,{x:0,y:1}:5}"));
assertTensorModify((left, right) -> left * right,
Tensor.from("tensor(x[1],y[2])", "{{x:0,y:0}:1, {x:0,y:1}:2}"),
Tensor.from("tensor(x[1],y[3])", "{}"),
Tensor.from("tensor(x[1],y[2])", "{{x:0,y:0}:0,{x:0,y:1}:0}"));
assertTensorModify((left, right) -> left * right,
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1, {x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:3}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:6}"));
}
@Test
public void testTensorMerge() {
assertTensorMerge(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:2}:3}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2,{x:0,y:2}:3}"));
assertTensorMerge(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:3}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:3}"));
assertTensorMerge(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:3,{x:0,y:2}:4}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:3,{x:0,y:2}:4}"));
assertTensorMerge(
Tensor.from("tensor(x{},y{})", "{}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:5}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:5}"));
assertTensorMerge(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"));
assertTensorMerge(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:2}:3}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:0,{x:0,y:1}:0,{x:0,y:2}:3}")); // notice difference with sparse case - y is dense dimension here with default value 0.0
assertTensorMerge(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:1}:3}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:0,{x:0,y:1}:3,{x:0,y:2}:0}"));
assertTensorMerge(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:1}:3,{x:0,y:2}:4}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:0,{x:0,y:1}:3,{x:0,y:2}:4}"));
assertTensorMerge(
Tensor.from("tensor(x{},y[3])", "{}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:5}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:5}"));
assertTensorMerge(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y[3])", "{}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:0,y:1}:2}"));
}
@Test
public void testTensorRemove() {
assertTensorRemove(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:2,{x:0,y:1}:3}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:1}:1}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:2}"));
assertTensorRemove(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:2}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1,{x:0,y:1}:1}"),
Tensor.from("tensor(x{},y{})", "{}"));
assertTensorRemove(
Tensor.from("tensor(x{},y{})", "{}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:1}"),
Tensor.from("tensor(x{},y{})", "{}"));
assertTensorRemove(
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:2,{x:0,y:1}:3}"),
Tensor.from("tensor(x{},y{})", "{}"),
Tensor.from("tensor(x{},y{})", "{{x:0,y:0}:2,{x:0,y:1}:3}"));
assertTensorRemove(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:2, {x:0,y:1}:3}"),
Tensor.from("tensor(x{})", "{{x:0}:1}"), // notice update is without dense dimension
Tensor.from("tensor(x{},y[3])", "{}"));
assertTensorRemove(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:1,{x:1,y:0}:2}"),
Tensor.from("tensor(x{})", "{{x:0}:1}"),
Tensor.from("tensor(x{},y[3])", "{{x:1,y:0}:2,{x:1,y:1}:0,{x:1,y:2}:0}"));
assertTensorRemove(
Tensor.from("tensor(x{},y[3])", "{}"),
Tensor.from("tensor(x{})", "{{x:0}:1}"),
Tensor.from("tensor(x{},y[3])", "{}"));
assertTensorRemove(
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:2,{x:0,y:1}:3}"),
Tensor.from("tensor(x{})", "{}"),
Tensor.from("tensor(x{},y[3])", "{{x:0,y:0}:2,{x:0,y:1}:3}"));
}
@Test
public void testLargest() {
assertLargest("{d1:l1,d2:l2}:6.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:5.0,{d1:l1,d2:l2}:6.0}");
assertLargest("{d1:l1,d2:l1}:6.0, {d1:l1,d2:l2}:6.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:6.0,{d1:l1,d2:l2}:6.0}");
assertLargest("{d1:l1,d2:l1}:6.0, {d1:l1,d2:l2}:6.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:6.0,{d1:l1,d2:l3}:5.0,{d1:l1,d2:l2}:6.0}");
assertLargest("{x:1,y:1}:4.0",
"tensor(x[2],y[2]):[[1,2],[3,4]]");
assertLargest("{x:0,y:0}:4.0, {x:1,y:1}:4.0",
"tensor(x[2],y[2]):[[4,2],[3,4]]");
}
@Test
public void testSmallest() {
assertSmallest("{d1:l1,d2:l1}:5.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:5.0,{d1:l1,d2:l2}:6.0}");
assertSmallest("{d1:l1,d2:l1}:6.0, {d1:l1,d2:l2}:6.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:6.0,{d1:l1,d2:l2}:6.0}");
assertSmallest("{d1:l1,d2:l1}:5.0, {d1:l1,d2:l2}:5.0",
"tensor(d1{},d2{}):{{d1:l1,d2:l1}:5.0,{d1:l1,d2:l3}:6.0,{d1:l1,d2:l2}:5.0}");
assertSmallest("{x:0,y:0}:1.0",
"tensor(x[2],y[2]):[[1,2],[3,4]]");
assertSmallest("{x:0,y:1}:2.0",
"tensor(x[2],y[2]):[[4,2],[3,4]]");
}
private void assertLargest(String expectedCells, String tensorString) {
Tensor tensor = Tensor.from(tensorString);
assertEquals(expectedCells, asString(tensor.largest(), tensor.type()));
}
private void assertSmallest(String expectedCells, String tensorString) {
Tensor tensor = Tensor.from(tensorString);
assertEquals(expectedCells, asString(tensor.smallest(), tensor.type()));
}
private String asString(List<Tensor.Cell> cells, TensorType type) {
return cells.stream().map(cell -> cell.toString(type)).collect(Collectors.joining(", "));
}
private void assertTensorModify(DoubleBinaryOperator op, Tensor init, Tensor update, Tensor expected) {
assertEquals(expected, init.modify(op, update.cells()));
}
private void assertTensorMerge(Tensor init, Tensor update, Tensor expected) {
DoubleBinaryOperator op = (left, right) -> right;
assertEquals(expected, init.merge(op, update.cells()));
}
private void assertTensorRemove(Tensor init, Tensor update, Tensor expected) {
assertEquals(expected, init.remove(update.cells().keySet()));
}
private double dotProduct(Tensor tensor, List<Tensor> tensors) {
double sum = 0;
TensorFunction<Name> dotProductFunction = new Reduce<>(new Join<>(new ConstantTensor<>(tensor),
new VariableTensor<>("argument"), (a, b) -> a * b),
Reduce.Aggregator.sum).toPrimitive();
MapEvaluationContext<Name> context = new MapEvaluationContext<>();
for (Tensor tensorElement : tensors) { // tensors.size() = 1 for larger tensor
context.put("argument", tensorElement);
// System.out.println("Dot product of " + tensor + " and " + tensorElement + ": " + dotProductFunction.evaluate(context).asDouble());
sum += dotProductFunction.evaluate(context).asDouble();
}
return sum;
}
private Tensor vector(TensorType.Dimension.Type dimensionType) {
return vectors(dimensionType, 1).get(0);
}
private Tensor vector(int vectorSize, TensorType.Dimension.Type dimensionType) {
return vectors(vectorSize, dimensionType, 1).get(0);
}
/** Create a list of vectors having a single dimension x */
private List<Tensor> vectors(TensorType.Dimension.Type dimensionType, int vectorCount) {
return vectors(3, dimensionType, vectorCount);
}
private List<Tensor> vectors(int vectorSize, TensorType.Dimension.Type dimensionType, int vectorCount) {
List<Tensor> tensors = new ArrayList<>();
TensorType type = vectorType(new TensorType.Builder(), "x", dimensionType, vectorSize);
for (int i = 0; i < vectorCount; i++) {
Tensor.Builder builder = Tensor.Builder.of(type);
for (int j = 0; j < vectorSize; j++) {
builder.cell().label("x", String.valueOf(j)).value((i+1)*(j+1));
}
tensors.add(builder.build());
}
return tensors;
}
/**
* Create a matrix of vectors (in dimension i) where each vector has the dimension x.
* This matrix contains the same vectors as returned by createVectors, in a single list element for convenience.
*/
private List<Tensor> matrix(TensorType.Dimension.Type dimensionType, int vectorCount) {
return matrix(3, dimensionType, vectorCount);
}
private List<Tensor> matrix(int vectorSize, TensorType.Dimension.Type dimensionType, int vectorCount) {
TensorType.Builder typeBuilder = new TensorType.Builder();
typeBuilder.dimension("i", dimensionType == Type.indexedBound ? Type.indexedUnbound : dimensionType);
vectorType(typeBuilder, "x", dimensionType, vectorSize);
Tensor.Builder builder = Tensor.Builder.of(typeBuilder.build());
for (int i = 0; i < vectorCount; i++) {
for (int j = 0; j < vectorSize; j++) {
builder.cell()
.label("i", String.valueOf(i))
.label("x", String.valueOf(j))
.value((i+1)*(j+1));
}
}
return Collections.singletonList(builder.build());
}
private TensorType vectorType(TensorType.Builder builder, String name, TensorType.Dimension.Type type, int size) {
switch (type) {
case mapped: builder.mapped(name); break;
case indexedUnbound: builder.indexed(name); break;
case indexedBound: builder.indexed(name, size); break;
default: throw new IllegalArgumentException("Dimension type " + type + " not supported");
}
return builder.build();
}
}
|
package com.eure.demo.domain.metrics.techcontribution;
import com.eure.demo.domain.metrics.*;
/**
* CodeReview指标
* @author xueliang.sxl, alisa.hsh, xiangning.lxn
*/
public class CodeReviewMetric extends SubMetric {
public CodeReviewMetric(){
this.subMetricType = SubMetricType.CodeReview;
}
public CodeReviewMetric(MainMetric parent) {
this.parent = parent;
parent.addSubMetric(this);
this.subMetricType = SubMetricType.CodeReview;
}
@Override
public double getWeight() {
return metricOwner.getWeight().getUnanimousWeight();
}
}
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.threadsafety;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.util.Arrays;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ImmutableChecker}Test */
@RunWith(JUnit4.class)
public class ImmutableCheckerTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ImmutableChecker.class, getClass());
@Test
public void basicFields() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test {",
" final int a = 42;",
" final String b = null;",
" final java.lang.String c = null;",
" final com.google.common.collect.ImmutableList<String> d = null;",
" final ImmutableList<Integer> e = null;",
" final Deprecated dep = null;",
" final Class<?> clazz = Class.class;",
"}")
.doTest();
}
@Test
public void interfacesMutableByDefault() {
compilationHelper
.addSourceLines("I.java", "interface I {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:"
+ " 'I' is not annotated with @com.google.errorprone.annotations.Immutable",
" private final I i = new I() {};",
"}")
.doTest();
}
@Test
public void annotationsAreImmutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable @interface Test {}")
.doTest();
}
@Test
public void customAnnotationsMightBeMutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable @interface Test {}")
.addSourceLines(
"MyTest.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.lang.annotation.Annotation;",
"@Immutable final class MyTest implements Test {",
" // BUG: Diagnostic contains: non-final",
" public Object[] xs = {};",
" public Class<? extends Annotation> annotationType() {",
" return null;",
" }",
"}")
.doTest();
}
@Ignore("b/25630189") // don't check annotations for immutability yet
@Test
public void customImplementionsOfImplicitlyImmutableAnnotationsMustBeImmutable() {
compilationHelper
.addSourceLines("Anno.java", "@interface Anno {}")
.addSourceLines(
"MyAnno.java",
"import java.lang.annotation.Annotation;",
"final class MyAnno implements Anno {",
" // BUG: Diagnostic contains:",
" public Object[] xs = {};",
" public Class<? extends Annotation> annotationType() {",
" return null;",
" }",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" private final Anno anno = new MyAnno();",
"}")
.doTest();
}
@Test
public void customAnnotationsSubtype() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable @interface Test {}")
.addSourceLines(
"MyTest.java",
"import java.lang.annotation.Annotation;",
"// BUG: Diagnostic contains:",
"// extends @Immutable type Test, but is not annotated as immutable",
"final class MyTest implements Test {",
" public Object[] xs = {};",
" public Class<? extends Annotation> annotationType() {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void annotationsDefaultToImmutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.lang.model.element.ElementKind;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" private final Override override = null;",
"}")
.doTest();
}
@Test
public void enumsDefaultToImmutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import javax.lang.model.element.ElementKind;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" private final ElementKind ek = null;",
"}")
.doTest();
}
@Test
public void enumsMayBeImmutable() {
compilationHelper
.addSourceLines(
"Kind.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable enum Kind { A, B, C; }")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" private final Kind k = null;",
"}")
.doTest();
}
@Test
public void mutableArray() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final int[] xs = {42};",
"}")
.doTest();
}
@Test
public void annotatedImmutableInterfaces() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface Test {}")
.doTest();
}
@Test
public void immutableInterfaceField() {
compilationHelper
.addSourceLines(
"MyInterface.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface MyInterface {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final MyInterface i = null;",
"}")
.doTest();
}
@Test
public void deeplyImmutableArguments() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test {",
" final ImmutableList<ImmutableList<ImmutableList<String>>> l = null;",
"}")
.doTest();
}
@Test
public void mutableNonFinalField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: non-final",
" int a = 42;",
"}")
.doTest();
}
@Test
public void ignoreStaticFields() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" static int a = 42;",
"}")
.doTest();
}
@Test
public void mutableField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.Map;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final Map<String, String> a = null;",
"}")
.doTest();
}
@Test
public void deeplyMutableTypeArguments() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.Map;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: instantiated with mutable type for 'E'",
" final ImmutableList<ImmutableList<ImmutableList<Map<String, String>>>> l = null;",
"}")
.doTest();
}
@Test
public void rawImpliesImmutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final ImmutableList l = null;",
"}")
.doTest();
}
@Test
public void extendsImmutable() {
compilationHelper
.addSourceLines(
"Super.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable public class Super {",
" public final int x = 42;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test extends Super {",
"}")
.doTest();
}
@Test
public void extendsMutable() {
compilationHelper
.addSourceLines("Super.java", "public class Super {", " public int x = 42;", "}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: 'Super' has non-final field 'x'",
"@Immutable class Test extends Super {",
"}")
.doTest();
}
@Test
public void extendsImmutableAnnotated_substBounds() {
compilationHelper
.addSourceLines(
"SuperMost.java",
"import com.google.errorprone.annotations.Immutable;",
"public class SuperMost<B> {",
" public final B x = null;",
"}")
.addSourceLines(
"Super.java",
"import java.util.List;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf={\"A\"}) public class Super<A, B> extends SuperMost<A> {",
" public final int x = 42;",
"}")
.doTest();
}
@Test
public void extendsImmutableAnnotated_mutableBounds() {
compilationHelper
.addSourceLines(
"SuperMost.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf={\"A\"})",
"public class SuperMost<A> {",
" public final A x = null;",
"}")
.addSourceLines(
"SubClass.java",
"import java.util.List;",
"import com.google.errorprone.annotations.Immutable;",
" // BUG: Diagnostic contains: instantiated with mutable type for 'A'",
"@Immutable public class SubClass extends SuperMost<List<String>> {}")
.doTest();
}
@Test
public void typeParameterWithImmutableBound() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable(containerOf=\"T\") class Test<T extends ImmutableList<String>> {",
" final T t = null;",
"}")
.doTest();
}
@Test
public void immutableTypeArgumentInstantiation() {
compilationHelper
.addSourceLines(
"Holder.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class Holder<T> {",
" public final T t = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final Holder<String> h = null;",
"}")
.doTest();
}
@Test
public void mutableTypeArgumentInstantiation() {
compilationHelper
.addSourceLines(
"Holder.java",
"import com.google.errorprone.annotations.Immutable;",
"public class Holder<T> {",
" public final T t = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final Holder<Object> h = null;",
"}")
.doTest();
}
@Test
public void instantiationWithMutableType() {
compilationHelper
.addSourceLines(
"Holder.java",
"import com.google.errorprone.annotations.Immutable;",
"public class Holder<T> {",
" public final T t = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: not annotated",
" final Holder<Object> h = null;",
"}")
.doTest();
}
@Test
public void transitiveSuperSubstitutionImmutable() {
compilationHelper
.addSourceLines(
"SuperMostType.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"N\") public class SuperMostType<N> {",
" public final N f = null;",
"}")
.addSourceLines(
"MiddleClass.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"M\") public class MiddleClass<M> extends SuperMostType<M> {",
" // Empty",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test extends MiddleClass<String> {",
" final MiddleClass<String> f = null;",
"}")
.doTest();
}
@Ignore("http://b/72495910")
@Test
public void containerOf_extendsImmutable() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class X<V> {",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
" // BUG: Diagnostic contains: 'V' is a mutable type variable",
"@Immutable(containerOf=\"V\") class Test<V> extends X<V> {",
" private final V t = null;",
"}")
.addSourceLines(
"MutableLeak.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class MutableLeak {",
" private static class Mutable {",
" int mutableInt;",
" }",
" private final X<Mutable> bad = new Test<Mutable>();",
"}")
.doTest();
}
@Test
public void containerOf_mutableInstantiation() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"V\") class X<V> {",
" private final V t = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test<T> {",
" // BUG: Diagnostic contains:",
" // 'X' was instantiated with mutable type for 'V'",
" // 'T' is a mutable type variable",
" private final X<T> t = null;",
"}")
.doTest();
}
@Test
public void missingContainerOf() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test<T> {",
" // BUG: Diagnostic contains: 'T' is a mutable type variable",
" private final T t = null;",
"}")
.doTest();
}
@Test
public void transitiveSuperSubstitutionMutable() {
compilationHelper
.addSourceLines(
"SuperMostType.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"N\") public class SuperMostType<N> {",
" public final N f = null;",
"}")
.addSourceLines(
"MiddleClass.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"M\") public class MiddleClass<M> extends SuperMostType<M> {",
" // Empty",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"// BUG: Diagnostic contains: instantiated with mutable type for 'M'",
"@Immutable class Test extends MiddleClass<List> {",
"}")
.doTest();
}
@Test
public void immutableInstantiation() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final ImmutableList<T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" final X<String> x = null;",
"}")
.doTest();
}
@Test
public void mutableInstantiation() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"public class X<T> { final ImmutableList<T> xs = null; }")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
"// BUG: Diagnostic contains:",
" final X<Object> x = null;",
"}")
.doTest();
}
@Test
public void immutableInstantiation_superBound() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"public class X<T> { final ImmutableList<? super T> xs = null; }")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final X<String> x = null;",
"}")
.doTest();
}
@Test
public void mutableInstantiation_superBound() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"public class X<T> { final ImmutableList<? super T> xs = null; }")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: is not annotated",
" final X<String> x = null;",
"}")
.doTest();
}
@Test
public void immutableInstantiation_extendsBound() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final ImmutableList<? extends T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" final X<String> x = null;",
"}")
.doTest();
}
@Test
public void mutableInstantiation_wildcard() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" // BUG: Diagnostic contains: mutable type for 'E', 'Object' is mutable",
" final ImmutableList<?> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" final X<String> x = null;",
"}")
.doTest();
}
@Test
public void mutableInstantiation_extendsBound() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final ImmutableList<? extends T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: instantiated with mutable type",
" final X<Object> x = null;",
"}")
.doTest();
}
@Test
public void containerOf_noSuchType() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: could not find type(s) referenced by containerOf: Z",
"@Immutable(containerOf=\"Z\") public class X<T> {",
" final int xs = 1;",
"}")
.doTest();
}
@Test
public void immutableInstantiation_inferredImmutableType() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final T xs = null;",
"}")
.addSourceLines(
"Y.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class Y<T> {",
" final X<? extends T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final Y<String> x = null;",
"}")
.doTest();
}
@Test
public void mutableInstantiation_inferredImmutableType() {
compilationHelper
.addSourceLines("X.java", "public class X<T> {", " final T xs = null;", "}")
.addSourceLines("Y.java", "public class Y<T> {", " final X<? extends T> xs = null;", "}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:",
" final Y<Object> x = null;",
"}")
.doTest();
}
@Test
public void mutableWildInstantiation() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final ImmutableList<T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: instantiated",
" final X<?> x = null;",
"}")
.doTest();
}
@Test
public void mutableRawType() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public class X<T> {",
" final ImmutableList<T> xs = null;",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: raw",
" final X x = null;",
"}")
.doTest();
}
@Test
public void testImmutableListImplementation() {
compilationHelper
.addSourceLines(
"com/google/common/collect/ImmutableList.java",
"package com.google.common.collect;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class ImmutableList<E> {",
" public Object[] veryMutable = null;",
"}")
.doTest();
}
@Test
public void positiveAnonymous() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Super {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {{",
" new Super() {",
" // BUG: Diagnostic contains: non-final",
" int x = 0;",
" {",
" x++;",
" }",
" };",
"}}")
.doTest();
}
@Test
public void positiveAnonymousInterface() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface Super {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {{",
" new Super() {",
" // BUG: Diagnostic contains: non-final",
" int x = 0;",
" {",
" x++;",
" }",
" };",
"}}")
.doTest();
}
@Test
public void negativeParametricAnonymous() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") class Super<T> {",
" private final T t = null;",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {",
" static <T> Super<T> get() {",
" return new Super<T>() {};",
" }",
"}")
.doTest();
}
@Test
public void interface_containerOf_immutable() {
compilationHelper
.addSourceLines(
"MyList.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public interface MyList<T> {",
" T get(int i);",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"public class Test {",
" private final MyList<Integer> l = null;",
"}")
.doTest();
}
@Test
public void interface_containerOf_mutable() {
compilationHelper
.addSourceLines(
"MyList.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public interface MyList<T> {",
" T get(int i);",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable public class Test<X> {",
" // BUG: Diagnostic contains: mutable type for 'T'",
" private final MyList<X> l = null;",
"}")
.doTest();
}
@Test
public void implementsInterface_containerOf() {
compilationHelper
.addSourceLines(
"MyList.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") public interface MyList<T> {",
" T get(int i);",
"}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: 'X' is a mutable type",
"@Immutable public class Test<X> implements MyList<X> {",
" public X get(int i) { return null; }",
"}")
.doTest();
}
// sub-type tests
@Test
public void positive() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Super {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Test extends Super {",
" // BUG: Diagnostic contains:"
+ " Class extends @Immutable type threadsafety.Super, but is not immutable: 'Test'"
+ " has non-final field 'x'",
" public int x = 0;",
"}")
.doTest();
}
@Test
public void positiveContainerOf() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf={\"T\"}) class Super<T> {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Test extends Super<Integer> {",
" // BUG: Diagnostic contains: non-final",
" public int x = 0;",
"}")
.doTest();
}
@Test
public void positiveImplicitContainerOf() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf={\"T\"}) class Super<T> {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Test<U> extends Super<U> {",
" // BUG: Diagnostic contains: mutable type for 'U'",
" public final Test<Object> x = null;",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Super {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test extends Super {",
"}")
.doTest();
}
// Report errors in compilation order, and detect transitive errors even if immediate
// supertype is unannotated.
@Test
public void transitive() {
compilationHelper
.addSourceLines(
"threadsafety/I.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface I {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"// BUG: Diagnostic contains: extends @Immutable",
"class Test implements J {",
" public int x = 0;",
"}")
.addSourceLines(
"threadsafety/J.java", //
"package threadsafety;",
"// BUG: Diagnostic contains: extends @Immutable",
"interface J extends I {",
"}")
.doTest();
}
// the type arguments are checked everywhere the super type is used
@Test
public void negativeAnonymousMutableBound() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") class Super<T> {",
" private final T t = null;",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {{",
" new Super<Object>() {};",
"}}")
.doTest();
}
@Test
public void immutableAnonymousTypeScope() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"X\") class Super<X> {",
" private final X t = null;",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") class Test<T> {{",
" new Super<T>() {};",
"}}")
.doTest();
}
@Test
public void immutableClassSuperTypeScope() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"Y\") class Super<Y> {",
" @Immutable(containerOf=\"X\") class Inner1<X> {",
" private final X x = null;",
" private final Y y = null;",
" }",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"U\") class Test<U> extends Super<U> {",
" @Immutable class Inner2 extends Inner1<U> {}",
"}")
.doTest();
}
@Test
public void immutableClassTypeScope() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"X\") class Super<X> {",
" private final X t = null;",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") class Test<T> {",
" @Immutable class Inner extends Super<T> {}",
"}")
.doTest();
}
@Test
public void negativeAnonymousBound() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\") class Super<T> {",
" private final T t = null;",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {{",
" new Super<String>() {};",
"}}")
.doTest();
}
@Test
public void negativeAnonymous() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Super {",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"class Test {{",
" new Super() {};",
"}}")
.doTest();
}
@Test
public void positiveEnumConstant() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface Super {",
" int f();",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable enum Test implements Super {",
" INSTANCE {",
" // BUG: Diagnostic contains: non-final",
" public int x = 0;",
" public int f() {",
" return x++;",
" }",
" }",
"}")
.doTest();
}
@Test
public void negativeEnumConstant() {
compilationHelper
.addSourceLines(
"threadsafety/Super.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface Super {",
" void f();",
"}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable enum Test implements Super {",
" INSTANCE {",
" public void f() {",
" }",
" }",
"}")
.doTest();
}
// any final null reference constant is immutable, but do we actually care?
//
// javac makes it annoying to figure this out - since null isn't a compile-time constant,
// none of that machinery can be used. Instead, we need to look at the actual AST node
// for the member declaration to see that it's initialized to null.
@Ignore
@Test
public void immutableNull() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final int[] xs = null;",
"}")
.doTest();
}
@Test
public void suppressOnField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" @SuppressWarnings(\"Immutable\")",
" final int[] xs = {1};",
"}")
.doTest();
}
@Test
public void suppressOnOneField() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" @SuppressWarnings(\"Immutable\")",
" final int[] xs = {1};",
" // BUG: Diagnostic contains: arrays are mutable",
" final int[] ys = {1};",
"}")
.doTest();
}
@Test
public void twoFieldsInSource() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: arrays are mutable",
" final int[] xs = {1};",
" // BUG: Diagnostic contains: arrays are mutable",
" final int[] ys = {1};",
"}")
.doTest();
}
@Test
public void protosNotOnClasspath() {
compilationHelper
.addSourceLines(
"com/google/errorprone/annotations/Immutable.java",
"package com.google.errorprone.annotations;",
"import static java.lang.annotation.ElementType.TYPE;",
"import static java.lang.annotation.RetentionPolicy.RUNTIME;",
"import java.lang.annotation.Retention;",
"import java.lang.annotation.Target;",
"@Target(TYPE)",
"@Retention(RUNTIME)",
"public @interface Immutable {",
" String[] containerOf() default {};",
"}")
.addSourceLines("Foo.java", "class Foo {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains:"
+ " 'Foo' is not annotated with @com.google.errorprone.annotations.Immutable",
" final Foo f = null;",
"}")
.setArgs(Arrays.asList("-cp", "NOSUCH"))
.doTest();
}
@Ignore("b/25630186") // don't check enums for immutability yet
@Test
public void mutableEnum() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"enum Test {",
" ;",
" // BUG: Diagnostic contains: @Immutable class has mutable field",
" private final Object o = null;",
"}")
.doTest();
}
@Ignore("b/25630186") // don't check enums for immutability yet
@Test
public void mutableEnumMember() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"enum Test {",
" ONE {",
" // BUG: Diagnostic contains: @Immutable class has mutable field",
" private final Object o = null;",
" }",
"}")
.doTest();
}
@Ignore("b/25630189") // don't check annotations for immutability yet
@Test
public void mutableExtendsAnnotation() {
compilationHelper
.addSourceLines(
"Anno.java", //
"@interface Anno {}")
.addSourceLines(
"Test.java",
"abstract class Test implements Anno {",
" // BUG: Diagnostic contains: @Immutable class has mutable field",
" final Object o = null;",
"}")
.doTest();
}
@Test
public void mutableEnclosing() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"public class Test {",
" int x = 0;",
" // BUG: Diagnostic contains: 'Inner' has mutable enclosing instance 'Test'",
" @Immutable public class Inner {",
" public int count() {",
" return x++;",
" }",
" }",
"}")
.doTest();
}
/** A sample superclass with a mutable field. */
public static class SuperFieldSuppressionTest {
@LazyInit public int x = 0;
public int count() {
return x++;
}
}
@Test
public void superFieldSuppression() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import " + SuperFieldSuppressionTest.class.getCanonicalName() + ";",
"@Immutable public class Test extends SuperFieldSuppressionTest {}")
.doTest();
}
@Test
public void rawClass() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final Class clazz = Test.class;",
"}")
.doTest();
}
/** Test class annotated with @Immutable. */
@Immutable(containerOf = {"T"})
public static class ClassPathTest<T> {}
@Test
public void incompleteClassPath() {
compilationHelper
.addSourceLines(
"Test.java",
"import " + ClassPathTest.class.getCanonicalName() + ";",
"class Test extends ClassPathTest<String> {",
" // BUG: Diagnostic contains: 'Test' has non-final field 'x'",
" int x;",
"}")
.withClasspath(ImmutableCheckerTest.ClassPathTest.class, ImmutableCheckerTest.class)
.doTest();
}
@Test
public void knownImmutableFlag() {
CompilationTestHelper.newInstance(ImmutableChecker.class, getClass())
.setArgs(ImmutableList.of("-XepOpt:Immutable:KnownImmutable=threadsafety.SomeImmutable"))
.addSourceLines(
"threadsafety/SomeImmutable.java", "package threadsafety;", "class SomeImmutable {}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" public final SomeImmutable s = new SomeImmutable();",
"}")
.doTest();
}
@Test
public void knownUnsafeFlag() {
CompilationTestHelper.newInstance(ImmutableChecker.class, getClass())
.setArgs(ImmutableList.of("-XepOpt:Immutable:KnownMutable=threadsafety.SomeUnsafe"))
.addSourceLines(
"threadsafety/SomeUnsafe.java", "package threadsafety;", "class SomeUnsafe {}")
.addSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: 'SomeUnsafe' is mutable",
" public final SomeUnsafe s = new SomeUnsafe();",
"}")
.doTest();
}
@Test
public void lazyInit() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.errorprone.annotations.concurrent.LazyInit;",
"@Immutable class Test {",
" @LazyInit int a = 42;",
"}")
.doTest();
}
@Test
public void lazyInitMutable() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.errorprone.annotations.concurrent.LazyInit;",
"import java.util.List;",
"@Immutable class Test {",
" // BUG: Diagnostic contains: 'List' is mutable",
" @LazyInit List<Integer> a = null;",
"}")
.doTest();
}
@Test
public void immutableTypeParameter() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test<@ImmutableTypeParameter T> {",
" final T t = null;",
"}")
.doTest();
}
@Test
public void immutableTypeParameterInstantiation() {
compilationHelper
.addSourceLines(
"MyImmutableType.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class MyImmutableType {}")
.addSourceLines(
"MyMutableType.java",
"import com.google.errorprone.annotations.Immutable;",
"class MyMutableType {}")
.addSourceLines(
"A.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class A<@ImmutableTypeParameter T> {}")
.addSourceLines(
"Test.java",
"class Test {",
" A<String> f() {",
" return new A<>();",
" }",
" A<Object> g() {",
" // BUG: Diagnostic contains: instantiation of 'T' is mutable, 'Object' is mutable",
" return new A<>();",
" }",
" <T extends MyImmutableType> A<T> h() {",
" return new A<>();",
" }",
" <T extends MyMutableType> A<T> i() {",
" // BUG: Diagnostic contains: "
+ "instantiation of 'T' is mutable, 'T' is a mutable type variable",
" return new A<>();",
" }",
"}")
.doTest();
}
@Test
public void immutableTypeParameterUsage() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"class T {",
" static <@ImmutableTypeParameter T> void f() {}",
"}")
.doTest();
}
@Test
public void immutableTypeParameterUsage_interface() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"@Immutable interface T<@ImmutableTypeParameter T> {",
"}")
.doTest();
}
@Test
public void immutableTypeParameterMutableClass() {
compilationHelper
.addSourceLines(
"Test.java", //
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
" // BUG: Diagnostic contains: only supported on immutable classes",
"class A<@ImmutableTypeParameter T> {}")
.doTest();
}
@Test
public void immutableTypeParameter_notAllTypeVarsInstantiated() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.function.Function;",
"class Test {",
" public final <A> void f1(A transform) {}",
" public <B, @ImmutableTypeParameter C> C f2(Function<B, C> fn) {",
" return null;",
" }",
" public final <D, E> void f3(Function<D, E> fn) {",
" // BUG: Diagnostic contains: instantiation of 'C' is mutable",
" // 'E' is a mutable type variable",
" f1(f2(fn));",
" }",
"}")
.doTest();
}
// javac does not instantiate type variables when they are not used, so we cannot check whether
// their instantiations are immutable.
@Ignore
@Test
public void immutableTypeParameter_notAllTypeVarsInstantiated_shouldFail() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.function.Function;",
"class Test {",
" public final <A> void f1(A transform) {}",
" public <@ImmutableTypeParameter B, C> C f2(Function<B, C> fn) {",
" return null;",
" }",
" public final <D, E> void f3(Function<D, E> fn) {",
" // BUG: Diagnostic contains: instantiation of 'B' is mutable",
" // 'D' is a mutable type variable",
" f1(f2(fn));",
" }",
"}")
.doTest();
}
@Test
public void containerOf_extendsThreadSafe() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class X<V> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: 'X' is not a container of 'V'",
"@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Y> {",
" private final Y t = null;",
"}")
.doTest();
}
@Test
public void containerOf_extendsThreadSafeContainerOf() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf = {\"V\"}) class X<V> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Y> {",
" private final Y t = null;",
"}")
.doTest();
}
@Test
public void containerOf_extendsThreadSafe_nonContainer() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf = {\"V\"}) class X<U, V> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf = {\"Y\"}) class Test<Y> extends X<Object, Y> {",
" private final Y t = null;",
"}")
.doTest();
}
@Test
public void containerOf_extendsThreadSafe_interface() {
compilationHelper
.addSourceLines(
"X.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface X<V> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: 'X' is not a container of 'V'",
"@Immutable(containerOf = {\"Y\"}) class Test<Y> implements X<Y> {",
" private final Y t = null;",
"}")
.doTest();
}
@Test
public void containerOf_field() {
compilationHelper
.addSourceLines(
"X.java", //
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface X<Y> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"V\") class Test<V> {",
" private final X<V> t = null;",
"}")
.doTest();
}
@Test
public void annotatedClassType() {
compilationHelper
.addSourceLines(
"Test.java",
"import static java.lang.annotation.ElementType.TYPE_USE;",
"import java.lang.annotation.Target;",
"@Target(TYPE_USE) @interface A {}",
"class Test {",
" Object o = new @A Object();",
"}")
.doTest();
}
@Ignore("b/77333859")
@Test
public void immutableInterfaceImplementationCapturesMutableState() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface I {",
" int f();",
"}",
"class Test {",
" int x;",
" I one = new I() {",
" public int f() {",
" return x++;",
" }",
" };",
" I two = () -> x++;",
"}")
.doTest();
}
@Test
public void immutableUpperBound() {
compilationHelper
.addSourceLines(
"MyImmutableType.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class MyImmutableType {}")
.addSourceLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test<T extends MyImmutableType, U extends T> {",
" final T t = null;",
" final U u = null;",
" final ImmutableList<? extends U> v = null;",
"}")
.doTest();
}
@Test
public void immutableRecursiveUpperBound() {
compilationHelper
.addSourceLines(
"Recursive.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable",
"abstract class Recursive<T extends Recursive<T>> {",
" final T x = null;",
"}")
.doTest();
}
@Test
public void immutableRecursiveUpperBound_notImmutable() {
compilationHelper
.addSourceLines(
"Recursive.java",
"import com.google.errorprone.annotations.Immutable;",
"import java.util.List;",
"@Immutable",
"abstract class Recursive<T extends Recursive<T>> {",
" final T x = null;",
" // BUG: Diagnostic contains: 'Recursive' has field 'y' of type 'java.util.List<T>'",
" final List<T> y = null;",
"}")
.doTest();
}
@Test
public void immutableUpperBoundAndContainerOfInconsistency() {
compilationHelper
.addSourceLines(
"ImmutableInterface.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable interface ImmutableInterface {}")
.addSourceLines(
"MutableImpl.java",
"import com.google.errorprone.annotations.Immutable;",
"@SuppressWarnings(\"Immutable\") class MutableImpl implements ImmutableInterface {",
" int mutableField;",
"}")
.addSourceLines(
"WithContainerOf.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable(containerOf=\"T\")",
"class WithContainerOf<T extends ImmutableInterface> { final T x = null; }")
.addSourceLines(
"WithoutContainerOf.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable",
"class WithoutContainerOf<T extends ImmutableInterface> { final T x = null; }")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class Test {",
" final WithContainerOf<ImmutableInterface> a = null;",
" final WithoutContainerOf<ImmutableInterface> b = null;",
" // BUG: Diagnostic contains: field 'c' of type 'WithContainerOf<MutableImpl>'",
" final WithContainerOf<MutableImpl> c = null;",
" final WithoutContainerOf<MutableImpl> d = null;",
"}")
.doTest();
}
// regression test for b/77781008
@Test
public void immutableTypeParameter_twoInstantiations() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"import com.google.common.collect.ImmutableList;",
"@Immutable class Test<@ImmutableTypeParameter T> {",
" <@ImmutableTypeParameter T> T f(T t) { return t; }",
" <@ImmutableTypeParameter T> void g(T a, T b) {}",
" @Immutable interface I {}",
" void test(I i) {",
" g(f(i), f(i));",
" }",
"}")
.doTest();
}
// regression test for b/148734874
@Test
public void immutableTypeParameter_instantiations_negative() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"abstract class T {",
" interface S<T> {}",
" interface L<T> {}",
" interface A {}",
" @Immutable interface B extends A {}",
" @Immutable interface C extends B {}",
" abstract <X, Y, Z> void h(S<X> firstType, S<Y> secondType, S<Z> thirdType);",
" abstract <@ImmutableTypeParameter E extends A> S<E> f(Class<E> entityClass);",
" abstract <T> S<L<T>> g(S<T> element);",
" void test() {",
" // BUG: Diagnostic contains: the declaration of type 'T.A' is not annotated",
" h(f(A.class), g(f(B.class)), g(f(C.class)));",
" }",
"}")
.doTest();
}
// regression test for b/181262633
@Test
public void immutableTypeParameter_rawSuper() {
compilationHelper
.addSourceLines(
"A.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"@Immutable class S<@ImmutableTypeParameter X> {}")
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.ImmutableTypeParameter;",
"import com.google.errorprone.annotations.Immutable;",
"// BUG: Diagnostic contains: 'S' required instantiation of 'X' with type parameters,"
+ " but was raw",
"@Immutable class T<@ImmutableTypeParameter X> extends S {}")
.doTest();
}
}
|
/*
* Copyright 2000-2020 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.server;
import java.io.Serializable;
/**
* Constants used by the server side framework.
* <p>
* Not available on the client side, for that use
* {@link com.vaadin.flow.shared.ApplicationConstants}.
*
* @since 1.0
*/
public final class Constants implements Serializable {
// Keep the version number in sync with flow-push/pom.xml
public static final String REQUIRED_ATMOSPHERE_RUNTIME_VERSION = "2.4.30.slf4jvaadin1";
/**
* The prefix used for System property parameters.
*/
public static final String VAADIN_PREFIX = "vaadin.";
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_PRODUCTION_MODE}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_PRODUCTION_MODE = InitParameters.SERVLET_PARAMETER_PRODUCTION_MODE;
// Token file keys used for defining folder paths for dev server
public static final String NPM_TOKEN = "npmFolder";
public static final String FRONTEND_TOKEN = "frontendFolder";
public static final String GENERATED_TOKEN = "generatedFolder";
public static final String CONNECT_JAVA_SOURCE_FOLDER_TOKEN = "connect.javaSourceFolder";
public static final String CONNECT_APPLICATION_PROPERTIES_TOKEN = "connect.applicationProperties";
public static final String CONNECT_OPEN_API_FILE_TOKEN = "connect.openApiFile";
public static final String PROJECT_FRONTEND_GENERATED_DIR_TOKEN = "project.frontend.generated";
public static final String EXTERNAL_STATS_FILE_TOKEN = "externalStatsFile";
public static final String EXTERNAL_STATS_URL_TOKEN = "externalStatsUrl";
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_USE_V14_BOOTSTRAP}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_USE_V14_BOOTSTRAP = InitParameters.SERVLET_PARAMETER_USE_V14_BOOTSTRAP;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_INITIAL_UIDL}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_INITIAL_UIDL = InitParameters.SERVLET_PARAMETER_INITIAL_UIDL;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_ENABLE_DEV_SERVER}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_ENABLE_DEV_SERVER = InitParameters.SERVLET_PARAMETER_ENABLE_DEV_SERVER;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_REUSE_DEV_SERVER}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_REUSE_DEV_SERVER = InitParameters.SERVLET_PARAMETER_REUSE_DEV_SERVER;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_REQUEST_TIMING}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_REQUEST_TIMING = InitParameters.SERVLET_PARAMETER_REQUEST_TIMING;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION = InitParameters.SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_HEARTBEAT_INTERVAL}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_HEARTBEAT_INTERVAL = InitParameters.SERVLET_PARAMETER_HEARTBEAT_INTERVAL;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_WEB_COMPONENT_DISCONNECT}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_WEB_COMPONENT_DISCONNECT = InitParameters.SERVLET_PARAMETER_WEB_COMPONENT_DISCONNECT;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_CLOSE_IDLE_SESSIONS}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_CLOSE_IDLE_SESSIONS = InitParameters.SERVLET_PARAMETER_CLOSE_IDLE_SESSIONS;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_PUSH_MODE}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_PUSH_MODE = InitParameters.SERVLET_PARAMETER_PUSH_MODE;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_PUSH_URL}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_PUSH_URL = InitParameters.SERVLET_PARAMETER_PUSH_URL;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_SYNC_ID_CHECK}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_SYNC_ID_CHECK = InitParameters.SERVLET_PARAMETER_SYNC_ID_CHECK;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_SEND_URLS_AS_PARAMETERS}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_SEND_URLS_AS_PARAMETERS = InitParameters.SERVLET_PARAMETER_SEND_URLS_AS_PARAMETERS;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING = InitParameters.SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_MAX_MESSAGE_SUSPEND_TIMEOUT}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_MAX_MESSAGE_SUSPEND_TIMEOUT = InitParameters.SERVLET_PARAMETER_MAX_MESSAGE_SUSPEND_TIMEOUT;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_JSBUNDLE}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_JSBUNDLE = InitParameters.SERVLET_PARAMETER_JSBUNDLE;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_POLYFILLS}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_POLYFILLS = InitParameters.SERVLET_PARAMETER_POLYFILLS;
public static final String POLYFILLS_DEFAULT_VALUE = "";
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_BROTLI} instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_BROTLI = InitParameters.SERVLET_PARAMETER_BROTLI;
/**
* @deprecated Use {@link InitParameters#I18N_PROVIDER} instead.
*/
@Deprecated
public static final String I18N_PROVIDER = InitParameters.I18N_PROVIDER;
/**
* @deprecated Use
* {@link InitParameters#DISABLE_AUTOMATIC_SERVLET_REGISTRATION}
* instead.
*/
@Deprecated
public static final String DISABLE_AUTOMATIC_SERVLET_REGISTRATION = InitParameters.DISABLE_AUTOMATIC_SERVLET_REGISTRATION;
/**
* @deprecated Use {@link InitParameters#COMPILED_WEB_COMPONENTS_PATH}
* instead.
*/
@Deprecated
public static final String COMPILED_WEB_COMPONENTS_PATH = InitParameters.COMPILED_WEB_COMPONENTS_PATH;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_STATISTICS_JSON}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_STATISTICS_JSON = InitParameters.SERVLET_PARAMETER_STATISTICS_JSON;
/**
* Default path for the WebPack profile statistics json file. It can be
* modified by setting the system property "statistics.file.path".
*/
public static final String STATISTICS_JSON_DEFAULT = Constants.VAADIN_CONFIGURATION
+ "stats.json";
/**
* Name of the <code>npm</code> main file.
*/
public static final String PACKAGE_JSON = "package.json";
/**
* Target folder constant.
*/
public static final String TARGET = "target";
/**
* Location for the frontend resources in jar files for compatibility mode
* (also obsolete but supported for NPM mode).
*/
public static final String COMPATIBILITY_RESOURCES_FRONTEND_DEFAULT = "META-INF/resources/frontend";
/**
* Location for the frontend resources in jar files.
*/
public static final String RESOURCES_FRONTEND_DEFAULT = "META-INF/frontend";
/**
* The name of the application theme root folder.
*/
public static final String APPLICATION_THEME_ROOT = "themes";
/**
* Location for the resources in jar files.
*/
public static final String RESOURCES_JAR_DEFAULT = "META-INF/resources/";
/**
* Location for the theme resources in jar files.
*/
public static final String RESOURCES_THEME_JAR_DEFAULT = RESOURCES_JAR_DEFAULT
+ APPLICATION_THEME_ROOT + "/";
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_WEBPACK_TIMEOUT}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_WEBPACK_TIMEOUT = InitParameters.SERVLET_PARAMETER_DEVMODE_WEBPACK_TIMEOUT;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_WEBPACK_SUCCESS_PATTERN}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_WEBPACK_SUCCESS_PATTERN = InitParameters.SERVLET_PARAMETER_DEVMODE_WEBPACK_SUCCESS_PATTERN;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_WEBPACK_ERROR_PATTERN}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_WEBPACK_ERROR_PATTERN = InitParameters.SERVLET_PARAMETER_DEVMODE_WEBPACK_ERROR_PATTERN;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_WEBPACK_OPTIONS}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_WEBPACK_OPTIONS = InitParameters.SERVLET_PARAMETER_DEVMODE_WEBPACK_OPTIONS;
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE = InitParameters.SERVLET_PARAMETER_DEVMODE_OPTIMIZE_BUNDLE;
/**
* @deprecated Use {@link InitParameters#SERVLET_PARAMETER_ENABLE_PNPM}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_ENABLE_PNPM = InitParameters.SERVLET_PARAMETER_ENABLE_PNPM;
/**
* Constant for whether pnpm is default or not. Mojos need the value as
* string and constant, so need to use string instead of boolean.
*/
public static final String ENABLE_PNPM_DEFAULT_STRING = "true";
/**
* @deprecated Use {@link InitParameters#REQUIRE_HOME_NODE_EXECUTABLE}
* instead.
*/
@Deprecated
public static final String REQUIRE_HOME_NODE_EXECUTABLE = InitParameters.REQUIRE_HOME_NODE_EXECUTABLE;
/**
* Internal parameter which prevent validation for annotations which are
* allowed on an AppShell class in non V14 bootstrap mode.
*/
public static final String ALLOW_APPSHELL_ANNOTATIONS = "allow.appshell.annotations";
/**
* The path used in the vaadin servlet for handling static resources.
*/
public static final String META_INF = "META-INF/";
/**
* The path used in the vaadin servlet for handling static resources.
*/
public static final String VAADIN_MAPPING = "VAADIN/";
/**
* The static build resources folder.
*/
public static final String VAADIN_BUILD = "build/";
/**
* The static configuration resources folder.
*/
public static final String VAADIN_CONFIGURATION = "config/";
/**
* The static resources root folder.
*/
public static final String VAADIN_WEBAPP = "webapp/";
/**
* The path to meta-inf/VAADIN/ where static resources are put on the
* servlet.
*/
public static final String VAADIN_SERVLET_RESOURCES = META_INF
+ VAADIN_MAPPING;
/**
* The path to webapp/ public resources root.
*/
public static final String VAADIN_WEBAPP_RESOURCES = VAADIN_SERVLET_RESOURCES
+ VAADIN_WEBAPP;
/**
* The prefix used for all internal static files, relative to context root.
*/
public static final String VAADIN_BUILD_FILES_PATH = VAADIN_MAPPING
+ VAADIN_BUILD;
/**
* Default path for local frontend resources packaged for jar add-ons.
*/
public static final String LOCAL_FRONTEND_RESOURCES_PATH = "src/main/resources/META-INF/resources/frontend";
/**
* Property boolean for marking stats.json to be fetched from external
* location.
*/
public static final String EXTERNAL_STATS_FILE = "external.stats.file";
/**
* Property String for external stats.json location url.
*/
public static final String EXTERNAL_STATS_URL = "external.stats.url";
/**
* Default location to look for the external stats.json.
*/
public static final String DEFAULT_EXTERNAL_STATS_URL = "/vaadin-static/VAADIN/config/stats.json";
/**
* A request parameter that can be given in browser to force the Vaadin
* application to create a new UI and session instance, thus overriding
* {@code @PreserveOnRefresh} annotation.
*/
public static final String URL_PARAMETER_RESTART_APPLICATION = "restartApplication";
/**
* A request parameter that can be given in browser to force the Vaadin
* application to close an existing UI and session. Unlike
* {@link #URL_PARAMETER_RESTART_APPLICATION}, this will not create a new
* session.
*/
public static final String URL_PARAMETER_CLOSE_APPLICATION = "closeApplication";
/**
* UsageEntry name for UsageStatistics BootstrapHandler.
*/
public static final String STATISTIC_FLOW_BOOTSTRAPHANDLER = "flow/BootstrapHandler";
/**
* UsageEntry name for UsageStatistics Routing Server.
*/
public static final String STATISTIC_ROUTING_SERVER = "routing/server";
/**
* UsageEntry name for UsageStatistics Routing Client.
*/
public static final String STATISTIC_ROUTING_CLIENT = "routing/client";
/**
* UsageEntry name for UsageStatistics Hybrid.
*/
public static final String STATISTIC_ROUTING_HYBRID = "routing/hybrid";
/**
* The name of platform versions file.
*/
public static final String VAADIN_VERSIONS_JSON = "vaadin_versions.json";
/**
* @deprecated Use
* {@link InitParameters#SERVLET_PARAMETER_DEVMODE_ENABLE_LIVE_RELOAD}
* instead.
*/
@Deprecated
public static final String SERVLET_PARAMETER_DEVMODE_ENABLE_LIVE_RELOAD = InitParameters.SERVLET_PARAMETER_DEVMODE_ENABLE_LIVE_RELOAD;
/**
* Default live reload port as defined in Spring Boot Dev Tools.
*/
// Non-default port currently not supported (#7970)
public static final int SPRING_BOOT_DEFAULT_LIVE_RELOAD_PORT = 35729;
private Constants() {
// prevent instantiation constants class only
}
}
|
/**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.dao.usertype;
import org.hibernate.HibernateException;
import org.jadira.usertype.spi.shared.AbstractStringColumnMapper;
/**
*/
public class NullSafeStringColumnMapper extends AbstractStringColumnMapper<String> {
private static final long serialVersionUID = 1L;
public static final char NOT_NULL_PREFIX = '_';
@Override
public String fromNonNullValue(String s) {
if (s.charAt(0) != NOT_NULL_PREFIX) {
throw new HibernateException(
"Persistent storage of "
+ this.getClass().getName()
+ " corrupted, database contained string ["
+ s
+ "] which should be prefixed by: "
+ NOT_NULL_PREFIX);
}
return s.substring(1);
}
@Override
public String toNonNullValue(String value) {
return NOT_NULL_PREFIX + value;
}
}
|
/*
* Copyright 2020, Verizon Media.
* Licensed under the terms of the Apache 2.0 license.
* Please see LICENSE file in the project root for terms.
*/
package com.yahoo.oak;
import java.nio.ByteBuffer;
/**
* This interface allows high performance access to the underlying data of Oak.
* To achieve that, it sacrifices safety, so it should be used only if you know what you are doing.
* Misuse of this interface might result in corrupted data, a crash or a deadlock.
* <p>
* Specifically, the developer should be concerned by two issues:
* 1. Concurrency: using this interface inside the context of serialize, compute, compare and transform is thread safe.
* In other contexts (e.g., get output), the developer should ensure that there is no concurrent access to this
* data. Failing to ensure that might result in corrupted data.
* 2. Data boundaries: when using this interface, Oak will not alert the developer regarding any out of boundary access.
* Thus, the developer should use getOffset() and getLength() to obtain the data boundaries and carefully access
* the data. Writing data out of these boundaries might result in corrupted data, a crash or a deadlock.
* <p>
* To use this interface, the developer should cast Oak's buffer (OakScopedReadBuffer or OakScopedWriteBuffer) to this
* interface, similarly to how Java's internal DirectBuffer is used. For example:
* <pre>
* {@code
* int foo(OakScopedReadBuffer b) {
* OakUnsafeDirectBuffer ub = (OakUnsafeDirectBuffer) b;
* ByteBuffer bb = ub.getByteBuffer();
* return bb.getInt(ub.getOffset());
* }
* }
* </pre>
*/
public interface OakUnsafeDirectBuffer {
/**
* Allows access to the underlying ByteBuffer of Oak.
* This buffer might contain data that is unrelated to the context in which this object was introduced.
* For example, it might contain internal Oak data and other user data.
* Thus, the developer should use getOffset() and getLength() to validate the data boundaries.
* Note 1: depending on the context (casting from OakScopedReadBuffer or OakScopedWriteBuffer), the buffer mode
* might be ready only.
* Note 2: the buffer internal state (e.g., byte order, position, limit and so on) should not be modified as this
* object might be shared and used elsewhere.
*
* @return the underlying ByteBuffer.
*/
ByteBuffer getByteBuffer();
/**
* @return the data offset inside the underlying ByteBuffer.
*/
int getOffset();
/**
* @return the data length.
*/
int getLength();
/**
* Allows access to the memory address of the underlying off-heap ByteBuffer of Oak.
* The address will point to the beginning of the user data, but avoiding overflow is the developer responsibility.
* Thus, the developer should use getLength() and access data only in this boundary.
* This is equivalent to ((DirectBuffer) b.getByteBuffer()).address() + b.getOffset()
*
* @return the exact memory address of the underlying buffer in the position of the data.
*/
long getAddress();
}
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.demo.model;
public class Medication {
private String name;
private String dose;
public Medication() {
}
public Medication( String name ) {
this.name = name;
}
public Medication( String name, String dose ) {
this.name = name;
this.dose = dose;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getDose() {
return dose;
}
public void setDose( String dose ) {
this.dose = dose;
}
@Override
public String toString() {
return "Medication{" + "name=" + name + ", dose=" + dose + '}';
}
}
|
package com.mypurecloud.sdk.v2.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* ConversationEventTopicJourneyActionMap
*/
public class ConversationEventTopicJourneyActionMap implements Serializable {
private String id = null;
private Integer version = null;
/**
**/
public ConversationEventTopicJourneyActionMap id(String id) {
this.id = id;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
**/
public ConversationEventTopicJourneyActionMap version(Integer version) {
this.version = version;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("version")
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConversationEventTopicJourneyActionMap conversationEventTopicJourneyActionMap = (ConversationEventTopicJourneyActionMap) o;
return Objects.equals(this.id, conversationEventTopicJourneyActionMap.id) &&
Objects.equals(this.version, conversationEventTopicJourneyActionMap.version);
}
@Override
public int hashCode() {
return Objects.hash(id, version);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ConversationEventTopicJourneyActionMap {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" version: ").append(toIndentedString(version)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.morningtech.eth.server.dao.impl;
import com.morningtech.eth.server.dao.SysWalletAccountMapperDao;
import com.morningtech.eth.server.entity.SysWalletAccount;
import org.springframework.stereotype.Service;
@Service
public class SysWalletAccountMapper extends BaseMapper<SysWalletAccount> implements SysWalletAccountMapperDao {
}
|
package com.github.fashionbrot.value.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
@Slf4j
public class JsonUtil {
private static final String CHARSET="UTF-8";
public static <T> T parseObject(String json,Class<T> clazz){
if (StringUtils.isEmpty(json)){
return null;
}
T t = null;
try {
t= JSONObject.parseObject(json.getBytes(CHARSET), clazz);
}catch (Exception e){
log.error("parseObject error json:{} clazz:{}",json,clazz,e);
}
return t;
}
public static JSONObject parseObject(String json){
if (StringUtils.isEmpty(json)){
return null;
}
try {
return JSONObject.parseObject(json);
}catch (Exception e){
log.error("parseObject error json:{}",json,e);
}
return null;
}
}
|
package ticket.domain;
public enum Status {
NEW,
OPEN,
IN_PROGRESS,
RESOLVED,
CLOSED,
ARCHIVED;
}
|
package com.puppies.store.apis;
import java.io.InputStream;
import apimodels.ModelApiResponse;
import apimodels.Pet;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Http;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Inject;
import java.io.File;
import openapitools.OpenAPIUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import javax.validation.constraints.*;
import play.Configuration;
import openapitools.OpenAPIUtils.ApiAction;
public class PetApiController extends Controller {
private final PetApiControllerImpInterface imp;
private final ObjectMapper mapper;
private final Configuration configuration;
@Inject
private PetApiController(Configuration configuration, PetApiControllerImpInterface imp) {
this.imp = imp;
mapper = new ObjectMapper();
this.configuration = configuration;
}
@ApiAction
public Result addPet() throws Exception {
JsonNode nodepet = request().body().asJson();
Pet pet;
if (nodepet != null) {
pet = mapper.readValue(nodepet.toString(), Pet.class);
if (configuration.getBoolean("useInputBeanValidation")) {
OpenAPIUtils.validate(pet);
}
} else {
throw new IllegalArgumentException("'Pet' parameter is required");
}
imp.addPet(pet);
return ok();
}
@ApiAction
public Result deletePet(Long petId) throws Exception {
String valueapiKey = request().getHeader("api_key");
String apiKey;
if (valueapiKey != null) {
apiKey = valueapiKey;
} else {
apiKey = null;
}
imp.deletePet(petId, apiKey);
return ok();
}
@ApiAction
public Result findPetsByStatus() throws Exception {
String[] statusArray = request().queryString().get("status");
if (statusArray == null) {
throw new IllegalArgumentException("'status' parameter is required");
}
List<String> statusList = OpenAPIUtils.parametersToList("csv", statusArray);
List<String> status = new ArrayList<String>();
for (String curParam : statusList) {
if (!curParam.isEmpty()) {
//noinspection UseBulkOperation
status.add(curParam);
}
}
List<Pet> obj = imp.findPetsByStatus(status);
if (configuration.getBoolean("useOutputBeanValidation")) {
for (Pet curItem : obj) {
OpenAPIUtils.validate(curItem);
}
}
JsonNode result = mapper.valueToTree(obj);
return ok(result);
}
@ApiAction
public Result findPetsByTags() throws Exception {
String[] tagsArray = request().queryString().get("tags");
if (tagsArray == null) {
throw new IllegalArgumentException("'tags' parameter is required");
}
List<String> tagsList = OpenAPIUtils.parametersToList("csv", tagsArray);
List<String> tags = new ArrayList<String>();
for (String curParam : tagsList) {
if (!curParam.isEmpty()) {
//noinspection UseBulkOperation
tags.add(curParam);
}
}
List<Pet> obj = imp.findPetsByTags(tags);
if (configuration.getBoolean("useOutputBeanValidation")) {
for (Pet curItem : obj) {
OpenAPIUtils.validate(curItem);
}
}
JsonNode result = mapper.valueToTree(obj);
return ok(result);
}
@ApiAction
public Result getPetById(Long petId) throws Exception {
Pet obj = imp.getPetById(petId);
if (configuration.getBoolean("useOutputBeanValidation")) {
OpenAPIUtils.validate(obj);
}
JsonNode result = mapper.valueToTree(obj);
return ok(result);
}
@ApiAction
public Result updatePet() throws Exception {
JsonNode nodepet = request().body().asJson();
Pet pet;
if (nodepet != null) {
pet = mapper.readValue(nodepet.toString(), Pet.class);
if (configuration.getBoolean("useInputBeanValidation")) {
OpenAPIUtils.validate(pet);
}
} else {
throw new IllegalArgumentException("'Pet' parameter is required");
}
imp.updatePet(pet);
return ok();
}
@ApiAction
public Result updatePetWithForm(Long petId) throws Exception {
String valuename = (request().body().asMultipartFormData().asFormUrlEncoded().get("name"))[0];
String name;
if (valuename != null) {
name = valuename;
} else {
name = "null";
}
String valuestatus = (request().body().asMultipartFormData().asFormUrlEncoded().get("status"))[0];
String status;
if (valuestatus != null) {
status = valuestatus;
} else {
status = "null";
}
imp.updatePetWithForm(petId, name, status);
return ok();
}
@ApiAction
public Result uploadFile(Long petId) throws Exception {
String valueadditionalMetadata = (request().body().asMultipartFormData().asFormUrlEncoded().get("additionalMetadata"))[0];
String additionalMetadata;
if (valueadditionalMetadata != null) {
additionalMetadata = valueadditionalMetadata;
} else {
additionalMetadata = "null";
}
Http.MultipartFormData.FilePart file = request().body().asMultipartFormData().getFile("file");
ModelApiResponse obj = imp.uploadFile(petId, additionalMetadata, file);
if (configuration.getBoolean("useOutputBeanValidation")) {
OpenAPIUtils.validate(obj);
}
JsonNode result = mapper.valueToTree(obj);
return ok(result);
}
}
|
/*
* Copyright 2014 http://Bither.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.bither.util;
import net.bither.bitherj.PrimerjSettings;
import net.bither.bitherj.PrimerjSettings.MarketType;
import net.bither.model.Market;
import net.bither.model.Ticker;
import net.bither.preference.AppSharedPreference;
import java.util.ArrayList;
import java.util.List;
public class MarketUtil {
private static ArrayList<Market> markets = new ArrayList<Market>();
public static ArrayList<Market> getMarkets() {
synchronized (markets) {
if (markets.size() == 0) {
for (MarketType marketType : MarketType.values()) {
markets.add(new Market(marketType));
}
}
return markets;
}
}
public static Market getMarket(MarketType marketType) {
if (markets.size() == 0) {
getMarkets();
}
synchronized (markets) {
if (markets.size() > 0) {
for (Market market : markets) {
if (market.getMarketType() == marketType) {
return market;
}
}
}
return null;
}
}
public static Market getDefaultMarket() {
PrimerjSettings.MarketType marketType = AppSharedPreference.getInstance()
.getDefaultMarket();
Market market = getMarket(marketType);
return market;
}
public static Ticker getTickerOfDefaultMarket() {
Market market = getDefaultMarket();
if (market != null) {
return market.getTicker();
}
return null;
}
public static void setTickerList(List<Ticker> tickerList) {
if (tickerList != null && tickerList.size() > 0) {
synchronized (markets) {
for (Ticker ticker : tickerList) {
Market market = getMarket(ticker.getMarketType());
if (market != null) {
market.setTicker(ticker);
}
}
}
}
}
}
|
/*
* Cache.java
*
* Copyright (c) 2012 Mike Strobel
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0.
* A copy of the license can be found in the License.html file at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*/
package com.strobel.collections;
import com.strobel.annotations.Nullable;
import com.strobel.core.VerifyArgument;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author strobelm
*/
public abstract class Cache<K, V> {
protected Cache() {
}
/**
* Gets a value indicating whether a cached value exists for the given key.
*/
public boolean contains(final K key) {
return get(key) != null;
}
/**
* Gets a value indicating whether the cached value matches the given value
* for a specified key.
*/
public boolean contains(final K key, final V value) {
final V cachedValue = get(key);
return cachedValue != null && cachedValue.equals(value);
}
/**
* Returns a thread-specific satellite cache chained to this cache. If the target
* cache is already a satellite cache, it will simply return itself. Note that the
* returned cache is completely unsynchronized and is not safe for concurrent access.
*
* @return A thread-specific satellite cache.
*/
public abstract Cache<K, V> getSatelliteCache();
/**
* <p>
* Replaces the value associated with a given key if the current value matches the
* expected value.
* </p>
* <p>
* Note that the replaced value <b>will not be propagated</b> to child caches that
* already have a value for the same key. As such, this method is of limited usefulness
* and should only be called on isolated Level 1 caches.
* </p>
*
* @param key
* The key for which to change the associated value.
* @param expectedValue
* The expected value to be replaced.
* @param updatedValue
* The new value.
*
* @return {@code true} if the expected value was replaced; otherwise, {@code false}.
*/
public abstract boolean replace(final K key, @Nullable final V expectedValue, final V updatedValue);
/**
* Gets the value associated with the given key.
*
* @param key
* The key associated with the desired value.
*
* @return The value corresponding the given key, or {@code null} if no value was found.
*/
public abstract V get(final K key);
/**
* Places a value in the cache only if no value exists with the same key.
*
* @param key
* The key associated with the given value.
* @param value
* The value to insert into the cache.
*
* @return The cached value associated with the given key, which will be the provided
* value if no existing value was found.
*/
public abstract V cache(final K key, final V value);
/**
* Creates a concurrency-safe Level 1 cache that may be used in isolation or as
* the root cache in a multi-level cache design.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createTopLevelCache() {
return new TopLevelCache<>();
}
/**
* Creates an unsynchronized, concurrency-unsafe Level 1 cache that can only be
* used safely by a single thread.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createSatelliteCache() {
return new SatelliteCache<>();
}
/**
* Creates an unsynchronized, concurrency-unsafe Level 2 cache that can only be
* used safely by a single thread. On a cache miss, the parent cache will be
* checked. On an insert, the value will propagate up to the parent cache.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createSatelliteCache(final Cache<K, V> parent) {
return new SatelliteCache<>(VerifyArgument.notNull(parent, "parent"));
}
/**
* Creates an unsynchronized, concurrency-unsafe Level 1 cache that can only be
* used safely by a single thread. Keys are compared by reference identity.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createSatelliteIdentityCache() {
return new SatelliteCache<>();
}
/**
* Creates an unsynchronized, concurrency-unsafe Level 2 cache that can only be
* used safely by a single thread. On a cache miss, the parent cache will be
* checked. On an insert, the value will propagate up to the parent cache.
* Keys are compared by reference identity.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createSatelliteIdentityCache(final Cache<K, V> parent) {
return new SatelliteCache<>(VerifyArgument.notNull(parent, "parent"));
}
/**
* Creates a Level 1 cache that internally maintains a separate satellite cache
* for each thread that accesses it.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createThreadLocalCache() {
return new ThreadLocalCache<>();
}
/**
* Creates a Level 1 cache that internally maintains a separate satellite cache
* for each thread that accesses it. Keys are compared by reference identity.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createThreadLocalIdentityCache() {
return new ThreadLocalCache<>();
}
/**
* Creates a Level 2 cache that internally maintains a separate satellite cache
* for each thread that accesses it. On a cache miss, the parent cache will be
* checked. On an insert, the value will propagate up to the parent cache.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createThreadLocalCache(final Cache<K, V> parent) {
return new ThreadLocalCache<>(VerifyArgument.notNull(parent, "parent"));
}
/**
* Creates a Level 2 cache that internally maintains a separate satellite cache
* for each thread that accesses it. On a cache miss, the parent cache will be
* checked. On an insert, the value will propagate up to the parent cache.
* Keys are compared by reference identity.
*
* @param <K>
* The type of keys used to identify values in the cache.
* @param <V>
* The type of values stored in the cache.
*
* @return The newly created cache.
*/
public static <K, V> Cache<K, V> createThreadLocalIdentityCache(final Cache<K, V> parent) {
return new ThreadLocalIdentityCache<>(VerifyArgument.notNull(parent, "parent"));
}
}
final class TopLevelCache<K, V> extends Cache<K, V> {
private final ConcurrentHashMap<K, V> _cache = new ConcurrentHashMap<>();
@Override
public V cache(final K key, final V value) {
final V cachedValue = _cache.putIfAbsent(key, value);
return cachedValue != null ? cachedValue : value;
}
@Override
public Cache<K, V> getSatelliteCache() {
return createSatelliteCache(this);
}
@Override
public boolean replace(final K key, final V expectedValue, final V updatedValue) {
if (expectedValue == null) {
return _cache.putIfAbsent(key, updatedValue) == null;
}
return _cache.replace(key, expectedValue, updatedValue);
}
@Override
public V get(final K key) {
return _cache.get(key);
}
}
final class SatelliteCache<K, V> extends Cache<K, V> {
private final Cache<K, V> _parent;
private final HashMap<K, V> _cache = new HashMap<>();
public SatelliteCache() {
_parent = null;
}
@Override
public Cache<K, V> getSatelliteCache() {
return this;
}
@Override
public boolean replace(final K key, final V expectedValue, final V updatedValue) {
if (_parent != null && !_parent.replace(key, expectedValue, updatedValue)) {
return false;
}
_cache.put(key, updatedValue);
return true;
}
public SatelliteCache(final Cache<K, V> parent) {
_parent = parent;
}
@Override
public V cache(final K key, final V value) {
V cachedValue = _cache.get(key);
if (cachedValue != null) {
return cachedValue;
}
if (_parent != null) {
cachedValue = _parent.cache(key, value);
}
else {
cachedValue = value;
}
_cache.put(key, cachedValue);
return cachedValue;
}
@Override
public V get(final K key) {
V cachedValue = _cache.get(key);
if (cachedValue != null) {
return cachedValue;
}
if (_parent != null) {
cachedValue = _parent.get(key);
if (cachedValue != null) {
_cache.put(key, cachedValue);
}
}
return cachedValue;
}
}
final class ThreadLocalCache<K, V> extends Cache<K, V> {
private final Cache<K, V> _parent;
@SuppressWarnings("ThreadLocalNotStaticFinal")
private final ThreadLocal<SatelliteCache<K, V>> _threadCaches = new ThreadLocal<SatelliteCache<K, V>>() {
@Override
protected SatelliteCache<K, V> initialValue() {
return new SatelliteCache<>(_parent);
}
};
public ThreadLocalCache() {
_parent = null;
}
@Override
public Cache<K, V> getSatelliteCache() {
return _threadCaches.get();
}
@Override
public boolean replace(final K key, final V expectedValue, final V updatedValue) {
return _threadCaches.get().replace(key, expectedValue, updatedValue);
}
public ThreadLocalCache(final Cache<K, V> parent) {
_parent = parent;
}
@Override
public V cache(final K key, final V value) {
return _threadCaches.get().cache(key, value);
}
@Override
public V get(final K key) {
return _threadCaches.get().get(key);
}
}
final class ThreadLocalIdentityCache<K, V> extends Cache<K, V> {
private final Cache<K, V> _parent;
@SuppressWarnings("ThreadLocalNotStaticFinal")
private final ThreadLocal<SatelliteCache<K, V>> _threadCaches = new ThreadLocal<SatelliteCache<K, V>>() {
@Override
protected SatelliteCache<K, V> initialValue() {
return new SatelliteCache<>(_parent);
}
};
public ThreadLocalIdentityCache() {
_parent = null;
}
@Override
public Cache<K, V> getSatelliteCache() {
return _threadCaches.get();
}
@Override
public boolean replace(final K key, final V expectedValue, final V updatedValue) {
return _threadCaches.get().replace(key, expectedValue, updatedValue);
}
public ThreadLocalIdentityCache(final Cache<K, V> parent) {
_parent = parent;
}
@Override
public V cache(final K key, final V value) {
return _threadCaches.get().cache(key, value);
}
@Override
public V get(final K key) {
return _threadCaches.get().get(key);
}
}
|
/*
* Copyright 2020 赖柄沣 bingfengdev@aliyun.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pers.lbf.yeju.consumer.auth.pojo;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* @author 赖柄沣 bingfengdev@aliyun.com
* @version 1.0
* @Description TODO
* @date 2020/12/20 22:27
*/
public class AuthenticationToken extends UsernamePasswordAuthenticationToken {
public AuthenticationToken(Object principal, Object credentials) {
super(principal, credentials);
}
public AuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
super(principal, credentials, authorities);
}
@Override
public Object getDetails() {
return super.getDetails();
}
@Override
public void setDetails(Object details) {
super.setDetails(details);
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
super.setAuthenticated(isAuthenticated);
}
}
|
package uk.co.quidos.dal.common.sequence;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import uk.co.quidos.common.component.threadpool.ThreadPool;
import uk.co.quidos.dal.common.sequence.dao.DalSequenceDO;
import uk.co.quidos.dal.common.sequence.dao.IdSequenceDao;
/**
* <strong>Title : SequenceGenerator<br></strong>
* <strong>Description : </strong>
* SequenceGenerator, 数据库序列生成器<br>
* <strong>Create on : 2011-10-31<br></strong>
* <p>
* <strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong>
* <p>
* @author peng.shi peng.shi@ecointellects.com<br>
* @version <strong>Ecointel v1.0.0</strong><br>
* <br>
* <strong>修改历史:</strong><br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public class SequenceGenerator {
private static Map<String, SequenceGenerator> generators = new HashMap<String, SequenceGenerator>();
@Autowired
private static IdSequenceDao dalSequenceDao;
private static ThreadPool threadPool = new ThreadPool(20, "SequenceGenerator");
private String moduleId;
private long updateBatchSize = 1;
private long batchCount = 0;
private static final long DEFAULT_STEP_VALUE = 1L;
private static final long DEFAULT_INIT_VALUE = 0L;
private long value;
private SequenceGenerator(String moduleId, long updateBatchSize) {
if (moduleId == null || moduleId.equals("")) {
throw new IllegalArgumentException("ModuleID can not be null.");
}
if (updateBatchSize < 1) {
throw new IllegalArgumentException("updateBatchSize can not less than 1.");
}
this.moduleId = moduleId;
this.updateBatchSize = updateBatchSize;
this.value = DEFAULT_INIT_VALUE;
DalSequenceDO dalSequenceDO = dalSequenceDao.load(moduleId);
if (dalSequenceDO != null) {
value = dalSequenceDO.getSequenceValue();
} else {
dalSequenceDO = new DalSequenceDO();
dalSequenceDO.setSequenceKey(moduleId);
dalSequenceDO.setSequenceValue(value);
dalSequenceDao.insert(dalSequenceDO);
}
}
public static SequenceGenerator getInstance(String moduleId, long batchSize) {
if (!generators.containsKey(moduleId)) {
synchronized (generators) {
if (!generators.containsKey(moduleId)) {
SequenceGenerator generator = new SequenceGenerator(moduleId, batchSize);
generators.put(moduleId, generator);
if (!threadPool.running()) {
threadPool.start();
}
}
}
}
return generators.get(moduleId);
}
public synchronized long nextId() {
if (batchCount == 0) {
addSequence(updateBatchSize);
batchCount = updateBatchSize;
batchCount--;
value = value + DEFAULT_STEP_VALUE;
return value;
} else {
batchCount--;
value = value + DEFAULT_STEP_VALUE;
return value;
}
}
private void addSequence(long stepValue) {
final DalSequenceDO seqDo = new DalSequenceDO();
seqDo.setSequenceKey(moduleId);
seqDo.setSequenceValue(value + stepValue);
try {
threadPool.execute(new Runnable() {
public void run() {
try {
/**
* 在另起一个线程里执行,目的是为了防止数据库事务嵌套,影响数据库操作。
*/
dalSequenceDao.update(seqDo);
} catch (Throwable e) {
e.printStackTrace();
} finally {
synchronized (seqDo) {
seqDo.notify();
}
}
}
});
synchronized (seqDo) {
seqDo.wait();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.util.nio;
import org.apache.ignite.*;
import org.apache.ignite.internal.util.lang.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.plugin.extensions.communication.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.*;
/**
* Grid client for NIO server.
*/
public class GridTcpNioCommunicationClient extends GridAbstractCommunicationClient {
/** Session. */
private final GridNioSession ses;
/** Logger. */
private final IgniteLogger log;
/**
* @param ses Session.
* @param log Logger.
*/
public GridTcpNioCommunicationClient(GridNioSession ses, IgniteLogger log) {
super(null);
assert ses != null;
assert log != null;
this.ses = ses;
this.log = log;
}
/**
* @return Gets underlying session.
*/
public GridNioSession session() {
return ses;
}
/** {@inheritDoc} */
@Override public void doHandshake(IgniteInClosure2X<InputStream, OutputStream> handshakeC) throws IgniteCheckedException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean close() {
boolean res = super.close();
if (res)
ses.close();
return res;
}
/** {@inheritDoc} */
@Override public void forceClose() {
super.forceClose();
ses.close();
}
/** {@inheritDoc} */
@Override public void sendMessage(byte[] data, int len) throws IgniteCheckedException {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public void sendMessage(ByteBuffer data) throws IgniteCheckedException {
if (closed())
throw new IgniteCheckedException("Client was closed: " + this);
GridNioFuture<?> fut = ses.send(data);
if (fut.isDone())
fut.get();
}
/** {@inheritDoc} */
@Override public boolean sendMessage(@Nullable UUID nodeId, Message msg, IgniteInClosure<IgniteException> closure)
throws IgniteCheckedException {
// Node ID is never provided in asynchronous send mode.
assert nodeId == null;
if (closure != null)
ses.addMeta(ACK_CLOSURE.ordinal(), closure);
GridNioFuture<?> fut = ses.send(msg);
if (fut.isDone()) {
try {
fut.get();
}
catch (IgniteCheckedException e) {
if (closure != null)
ses.removeMeta(ACK_CLOSURE.ordinal());
if (log.isDebugEnabled())
log.debug("Failed to send message [client=" + this + ", err=" + e + ']');
if (e.getCause() instanceof IOException)
return true;
else
throw new IgniteCheckedException("Failed to send message [client=" + this + ']', e);
}
}
if (closure != null)
ses.removeMeta(ACK_CLOSURE.ordinal());
return false;
}
/** {@inheritDoc} */
@Override public boolean async() {
return true;
}
/** {@inheritDoc} */
@Override public long getIdleTime() {
long now = U.currentTimeMillis();
// Session can be used for receiving and sending.
return Math.min(Math.min(now - ses.lastReceiveTime(), now - ses.lastSendScheduleTime()),
now - ses.lastSendTime());
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridTcpNioCommunicationClient.class, this, super.toString());
}
}
|
/*
* 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.beam.runners.dataflow.worker;
import com.google.api.services.dataflow.model.CounterUpdate;
import com.google.api.services.dataflow.model.SideInputInfo;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.beam.runners.core.InMemoryStateInternals;
import org.apache.beam.runners.core.InMemoryTimerInternals;
import org.apache.beam.runners.core.SideInputReader;
import org.apache.beam.runners.core.StateInternals;
import org.apache.beam.runners.core.TimerInternals;
import org.apache.beam.runners.core.TimerInternals.TimerData;
import org.apache.beam.runners.core.metrics.CounterCell;
import org.apache.beam.runners.core.metrics.ExecutionStateSampler;
import org.apache.beam.runners.core.metrics.MetricUpdates;
import org.apache.beam.runners.core.metrics.MetricsContainerImpl;
import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.runners.dataflow.worker.counters.CounterFactory;
import org.apache.beam.runners.dataflow.worker.counters.NameContext;
import org.apache.beam.runners.dataflow.worker.profiler.ScopedProfiler;
import org.apache.beam.runners.dataflow.worker.profiler.ScopedProfiler.ProfileScope;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.metrics.MetricName;
import org.apache.beam.sdk.metrics.MetricsContainer;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.util.WeightedValue;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.vendor.guava.v20_0.com.google.common.annotations.VisibleForTesting;
import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.Cache;
import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.CacheBuilder;
import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.FluentIterable;
import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.Iterables;
import org.joda.time.Instant;
/** {@link DataflowExecutionContext} for use in batch mode. */
public class BatchModeExecutionContext
extends DataflowExecutionContext<BatchModeExecutionContext.StepContext> {
protected final Cache<?, WeightedValue<?>> dataCache;
protected final Cache<?, ?> logicalReferenceCache;
protected final PipelineOptions options;
protected final ReaderFactory readerFactory;
private Object key;
private final MetricsContainerRegistry<MetricsContainerImpl> containerRegistry;
// TODO: Move throttle time Metric to a dedicated namespace.
protected static final String DATASTORE_THROTTLE_TIME_NAMESPACE =
"org.apache.beam.sdk.io.gcp.datastore.DatastoreV1$DatastoreWriterFn";
private BatchModeExecutionContext(
CounterFactory counterFactory,
Cache<?, WeightedValue<?>> dataCache,
Cache<?, ?> logicalReferenceCache,
ReaderFactory readerFactory,
PipelineOptions options,
DataflowExecutionStateTracker executionStateTracker,
DataflowExecutionStateRegistry executionStateRegistry) {
super(
counterFactory,
createMetricsContainerRegistry(),
executionStateTracker,
executionStateRegistry,
Long.MAX_VALUE);
this.logicalReferenceCache = logicalReferenceCache;
this.readerFactory = readerFactory;
this.options = options;
this.dataCache = dataCache;
this.containerRegistry =
(MetricsContainerRegistry<MetricsContainerImpl>) getMetricsContainerRegistry();
}
private static MetricsContainerRegistry<MetricsContainerImpl> createMetricsContainerRegistry() {
return new MetricsContainerRegistry<MetricsContainerImpl>() {
@Override
protected MetricsContainerImpl createContainer(String stepName) {
return new MetricsContainerImpl(stepName);
}
};
}
public static BatchModeExecutionContext forTesting(
PipelineOptions options, CounterFactory counterFactory, String stageName) {
BatchModeExecutionStateRegistry stateRegistry = new BatchModeExecutionStateRegistry();
return new BatchModeExecutionContext(
counterFactory,
CacheBuilder.newBuilder()
.maximumWeight(1_000_000) // weights are in bytes
.weigher(Weighers.fixedWeightKeys(8))
.softValues()
.recordStats()
.<Object, WeightedValue<?>>build(),
CacheBuilder.newBuilder().weakValues().build(),
ReaderRegistry.defaultRegistry(),
options,
new DataflowExecutionStateTracker(
ExecutionStateSampler.newForTest(),
stateRegistry.getState(
NameContext.forStage(stageName),
"other",
null,
ScopedProfiler.INSTANCE.emptyScope()),
counterFactory,
options,
"test-work-item-id"),
stateRegistry);
}
public static BatchModeExecutionContext forTesting(PipelineOptions options, String stageName) {
CounterFactory counterFactory = new CounterFactory();
return forTesting(options, counterFactory, stageName);
}
/**
* A version of {@link DataflowOperationContext.DataflowExecutionState} supporting per-bundle MSEC
* counters.
*/
@VisibleForTesting
static class BatchModeExecutionState extends DataflowOperationContext.DataflowExecutionState {
// Must be volatile so that totalMillisInState modifications are atomic. This field is only
// written by the sampler thread in takeSample, and read in a separate thread within
// extractUpdate.
private volatile long totalMillisInState = 0;
// This thread is only read and written within extractUpdate, which will be called from either
// the progress reporting thread or the execution thread when producing the final update.
// The value is not used as part of producing the final update, so the fact this is used in
// multiple threads does not lead to incorrect results.
private long lastReportedMillis = 0;
public BatchModeExecutionState(
NameContext nameContext,
String stateName,
@Nullable String requestingStepName,
@Nullable Integer inputIndex,
@Nullable MetricsContainer metricsContainer,
ProfileScope profileScope) {
super(nameContext, stateName, requestingStepName, inputIndex, metricsContainer, profileScope);
}
/**
* Take sample is only called by the ExecutionStateSampler thread and it is the only place that
* writes to totalMillisInState. Thus, we don't need to synchronize these writes, but we just
* need to make sure that the value seen by readers (which are in the reporting thread) is
* consistent. This is ensured since totalMillisInState is volatile, and thus is atomic.
*/
@SuppressWarnings("NonAtomicVolatileUpdate") // Single writer.
@Override
public void takeSample(long millisSinceLastSample) {
totalMillisInState += millisSinceLastSample;
}
/**
* Extract updates in the from of a {@link CounterUpdate}.
*
* <p>Non-final updates are extracted by the progress reporting thread (single reader, different
* from the sampler thread calling takeSample).
*
* <p>Final updates are extracted by the execution thread, and will be reported after all
* processing has completed and the writer thread has been shutdown.
*/
@Nullable
@Override
public CounterUpdate extractUpdate(boolean isFinalUpdate) {
long millisToReport = totalMillisInState;
if (millisToReport == lastReportedMillis && !isFinalUpdate) {
return null;
}
lastReportedMillis = millisToReport;
return createUpdate(true, totalMillisInState);
}
}
/**
* {@link DataflowExecutionStateRegistry} that creates {@link BatchModeExecutionState} instances.
*/
@VisibleForTesting
public static class BatchModeExecutionStateRegistry extends DataflowExecutionStateRegistry {
@Override
protected DataflowOperationContext.DataflowExecutionState createState(
NameContext nameContext,
String stateName,
@Nullable String requestingStepName,
@Nullable Integer inputIndex,
MetricsContainer container,
ProfileScope profileScope) {
return new BatchModeExecutionState(
nameContext, stateName, requestingStepName, inputIndex, container, profileScope);
}
}
public static BatchModeExecutionContext create(
CounterFactory counterFactory,
Cache<?, WeightedValue<?>> dataCache,
Cache<?, ?> logicalReferenceCache,
ReaderFactory readerFactory,
DataflowPipelineOptions options,
String stageName,
String workItemId) {
BatchModeExecutionStateRegistry executionStateRegistry = new BatchModeExecutionStateRegistry();
return new BatchModeExecutionContext(
counterFactory,
dataCache,
logicalReferenceCache,
readerFactory,
options,
new DataflowExecutionStateTracker(
ExecutionStateSampler.instance(),
executionStateRegistry.getState(
NameContext.forStage(stageName),
"other",
null,
ScopedProfiler.INSTANCE.emptyScope()),
counterFactory,
options,
workItemId),
executionStateRegistry);
}
/** Create a new {@link StepContext}. */
@Override
protected StepContext createStepContext(DataflowOperationContext operationContext) {
return new StepContext(operationContext);
}
/** Sets the key of the work currently being processed. */
public void setKey(Object key) {
if (!Objects.equals(key, this.key)) {
switchStateKey(key);
}
this.key = key;
}
/** @param newKey the key being switched to */
protected void switchStateKey(Object newKey) {
for (StepContext stepContext : getAllStepContexts()) {
stepContext.setKey(newKey);
}
}
/**
* Returns the key of the work currently being processed.
*
* <p>If there is not a currently defined key, returns null.
*/
@Nullable
public Object getKey() {
return key;
}
@Override
protected SideInputReader getSideInputReader(
Iterable<? extends SideInputInfo> sideInputInfos, DataflowOperationContext operationContext)
throws Exception {
return new LazilyInitializedSideInputReader(
sideInputInfos,
() -> {
try {
return IsmSideInputReader.of(
sideInputInfos,
options,
BatchModeExecutionContext.this,
readerFactory,
operationContext);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Override
protected SideInputReader getSideInputReaderForViews(
Iterable<? extends PCollectionView<?>> sideInputViews) {
throw new UnsupportedOperationException(
"Cannot call getSideInputReaderForViews for batch DataflowWorker: "
+ "the MapTask specification should have had SideInputInfo descriptors "
+ "for each side input, and a SideInputReader provided via getSideInputReader");
}
// TODO: Expose a keyed sub-cache which allows one to store all cached values in their
// own namespace.
public <K, V> Cache<K, V> getDataCache() {
@SuppressWarnings({"unchecked", "rawtypes"})
Cache<K, V> rval = (Cache) dataCache;
return rval;
}
public <K, V> Cache<K, V> getLogicalReferenceCache() {
@SuppressWarnings({"rawtypes", "unchecked"})
Cache<K, V> rval = (Cache) logicalReferenceCache;
return rval;
}
/** {@link DataflowStepContext} used in batch mode. */
public class StepContext extends DataflowExecutionContext.DataflowStepContext {
// State internals only for use by the system, lazily instantiated
@Nullable private InMemoryStateInternals<Object> systemStateInternals;
// State internals scoped to the user, lazily instantiated
@Nullable private InMemoryStateInternals<Object> userStateInternals;
// Timer internals scoped to the user, lazily instantiated
@Nullable private InMemoryTimerInternals userTimerInternals;
private InMemoryStateInternals<Object> getUserStateInternals() {
if (userStateInternals == null) {
userStateInternals = InMemoryStateInternals.forKey(getKey());
}
return userStateInternals;
}
private InMemoryTimerInternals getUserTimerInternals() {
if (userTimerInternals == null) {
userTimerInternals = new InMemoryTimerInternals();
}
return userTimerInternals;
}
private StepContext(DataflowOperationContext operationContext) {
super(operationContext.nameContext());
systemStateInternals = null;
userStateInternals = null;
userTimerInternals = null;
}
public void setKey(Object newKey) {
// When the key changes, wipe out existing state and timers for later
// lazy instantiation.
// In batch mode, a specific key is always processed contiguously
// because the state is either used after a GroupByKeyOnly where
// each key only occurs once, or after some ParDo's that preserved
// the key.
systemStateInternals = null;
userStateInternals = null;
userTimerInternals = null;
}
@Override
public StateInternals stateInternals() {
if (systemStateInternals == null) {
systemStateInternals = InMemoryStateInternals.forKey(getKey());
}
return systemStateInternals;
}
@Override
public TimerInternals timerInternals() {
throw new UnsupportedOperationException(
"System timerInternals() are not supported in Batch mode."
+ " Perhaps you meant stepContext.namespacedToUser().timerInternals()");
}
@Override
@Nullable
public <W extends BoundedWindow> TimerData getNextFiredTimer(Coder<W> windowCoder) {
// There are no actual timer firings, since in batch all state is cleaned up trivially
// and all user processing time timers are "expired" by the time they fire.
// Event time timers are handled in the UserStepContext
return null;
}
@Override
public <W extends BoundedWindow> void setStateCleanupTimer(
String timerId, W window, Coder<W> windowCoder, Instant cleanupTime) {
// noop, as the state will be discarded when the step is complete
}
@Override
public DataflowStepContext namespacedToUser() {
return new UserStepContext(this);
}
}
/**
* A specialized {@link StepContext} that uses provided {@link StateInternals} and {@link
* TimerInternals} for user state and timers.
*/
private static class UserStepContext extends DataflowStepContext {
private final BatchModeExecutionContext.StepContext wrapped;
public UserStepContext(BatchModeExecutionContext.StepContext wrapped) {
super(wrapped.getNameContext());
this.wrapped = wrapped;
}
@Override
public StateInternals stateInternals() {
return wrapped.getUserStateInternals();
}
@Override
public TimerInternals timerInternals() {
return wrapped.getUserTimerInternals();
}
@Nullable
@Override
public <W extends BoundedWindow> TimerData getNextFiredTimer(Coder<W> windowCoder) {
// Only event time timers fire, as processing time timers are reserved until after the
// bundle is complete, so they are all delivered droppably late
//
// Note also that timers hold the _output_ watermark, but the input watermark is
// advanced to infinity when timers begin to process
try {
wrapped.getUserTimerInternals().advanceInputWatermark(BoundedWindow.TIMESTAMP_MAX_VALUE);
} catch (Exception e) {
throw new IllegalStateException("Exception thrown advancing watermark", e);
}
return wrapped.getUserTimerInternals().removeNextEventTimer();
}
@Override
public <W extends BoundedWindow> void setStateCleanupTimer(
String timerId, W window, Coder<W> windowCoder, Instant cleanupTime) {
throw new UnsupportedOperationException(
String.format(
"setStateCleanupTimer should not be called on %s, only on a system %s",
getClass().getSimpleName(),
BatchModeExecutionContext.StepContext.class.getSimpleName()));
}
@Override
public DataflowStepContext namespacedToUser() {
return this;
}
}
/**
* Returns {@link CounterUpdate} protos representing the latest cumulative values of all
* user-defined metrics reported within this execution context.
*/
public Iterable<CounterUpdate> extractMetricUpdates(boolean isFinalUpdate) {
return containerRegistry
.getContainers()
.transformAndConcat(
container -> {
MetricUpdates updates;
if (isFinalUpdate) {
// getCumulative returns cumulative values for all metrics.
updates = container.getCumulative();
} else {
// getUpdates returns cumulative values only for metrics which have changes
// since the last time updates were committed.
updates = container.getUpdates();
}
return Iterables.concat(
FluentIterable.from(updates.counterUpdates())
.transform(
update ->
MetricsToCounterUpdateConverter.fromCounter(
update.getKey(), true, update.getUpdate())),
FluentIterable.from(updates.distributionUpdates())
.transform(
update ->
MetricsToCounterUpdateConverter.fromDistribution(
update.getKey(), true, update.getUpdate())));
});
}
public void commitMetricUpdates() {
for (MetricsContainerImpl container : containerRegistry.getContainers()) {
container.commitUpdates();
}
}
public Iterable<CounterUpdate> extractMsecCounters(boolean isFinalUpdate) {
return executionStateRegistry.extractUpdates(isFinalUpdate);
}
public Long extractThrottleTime() {
Long totalThrottleTime = 0L;
for (MetricsContainerImpl container : containerRegistry.getContainers()) {
// TODO: Update Datastore to use generic throttling-msecs metric.
CounterCell throttleTime =
container.tryGetCounter(
MetricName.named(
BatchModeExecutionContext.DATASTORE_THROTTLE_TIME_NAMESPACE,
"cumulativeThrottlingSeconds"));
if (throttleTime != null) {
totalThrottleTime += throttleTime.getCumulative();
}
CounterCell throttlingMsecs =
container.tryGetCounter(DataflowSystemMetrics.THROTTLING_MSECS_METRIC_NAME);
if (throttlingMsecs != null) {
totalThrottleTime += TimeUnit.MILLISECONDS.toSeconds(throttlingMsecs.getCumulative());
}
}
return totalThrottleTime;
}
}
|
package org.mlflow.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import org.mlflow.Flavor;
import org.mlflow.utils.FileUtils;
import org.mlflow.utils.SerializationUtils;
/**
* Represents an MLflow model. This class includes utility functions for parsing a serialized MLflow
* model configuration (`MLModel`) as a {@link Model} object.
*/
public class Model {
public static class Signature {
@JsonProperty("inputs")
private String inputsSchemaJson;
@JsonProperty("outputs")
private String outputSchemaJson;
}
@JsonProperty("artifact_path")
private String artifactPath;
@JsonProperty("run_id")
private String runId;
@JsonProperty("utc_time_created")
private String utcTimeCreated;
@JsonProperty("flavors")
private Map<String, Object> flavors;
@JsonProperty("signature")
Signature signature;
@JsonProperty("input_example")
private Map<String, Object> input_example;
private String rootPath;
/**
* Loads the configuration of an MLflow model and parses it as a {@link Model} object.
*
* @param modelRootPath The path to the root directory of the MLflow model
*/
public static Model fromRootPath(String modelRootPath) throws IOException {
String configPath = FileUtils.join(modelRootPath, "MLmodel");
return fromConfigPath(configPath);
}
/**
* Loads the configuration of an MLflow model and parses it as a {@link Model} object.
*
* @param configPath The path to the `MLModel` configuration file
*/
public static Model fromConfigPath(String configPath) throws IOException {
File configFile = new File(configPath);
Model model = SerializationUtils.parseYamlFromFile(configFile, Model.class);
// Set the root path to the directory containing the configuration file.
// This will be used to create an absolute path to the serialized model
model.setRootPath(configFile.getParentFile().getAbsolutePath());
return model;
}
/** @return The MLflow model's artifact path */
public Optional<String> getArtifactPath() {
return Optional.ofNullable(this.artifactPath);
}
/** @return The MLflow model's time of creation */
public Optional<String> getUtcTimeCreated() {
return Optional.ofNullable(this.utcTimeCreated);
}
/** @return The MLflow model's run id */
public Optional<String> getRunId() {
return Optional.ofNullable(this.runId);
}
/** @return The path to the root directory of the MLflow model */
public Optional<String> getRootPath() {
return Optional.ofNullable(this.rootPath);
}
/**
* Reads the configuration corresponding to the specified flavor name and parses it as a `Flavor`
* object
*/
public <T extends Flavor> Optional<T> getFlavor(String flavorName, Class<T> flavorClass) {
if (this.flavors.containsKey(flavorName)) {
final ObjectMapper mapper = new ObjectMapper();
T flavor = mapper.convertValue(this.flavors.get(flavorName), flavorClass);
return Optional.of(flavor);
} else {
return Optional.<T>empty();
}
}
private void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
}
|
package com.adaptris.core.cassandra.params;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
public interface StatementPrimer {
public PreparedStatement prepareStatement(Session session, String statement) throws Exception;
}
|
/*
* Copyright (C) 2020 Luke Klinker
*
* 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 xyz.heart.sms.api;
import org.junit.Test;
import java.io.IOException;
import xyz.heart.sms.api.entity.AddDraftRequest;
import xyz.heart.sms.api.entity.DraftBody;
import xyz.heart.sms.api.entity.UpdateDraftRequest;
import xyz.heart.sms.api.entity.AddDraftRequest;
import xyz.heart.sms.api.entity.DraftBody;
import xyz.heart.sms.api.entity.UpdateDraftRequest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DraftTest extends ApiTest {
@Test
public void addAndUpdateAndRemove() throws IOException {
String accountId = getAccountId();
int originalSize = api.draft().list(accountId).execute().body().length;
DraftBody draft = new DraftBody(1, 1, "test draft", "text/plain");
AddDraftRequest request = new AddDraftRequest(accountId, draft);
Object response = api.draft().add(request).execute().body();
assertNotNull(response);
UpdateDraftRequest update = new UpdateDraftRequest("new test draft", null);
api.draft().update(1, accountId, update).execute().body();
DraftBody[] drafts = api.draft().list(accountId).execute().body();
assertEquals(1, drafts.length - originalSize);
api.draft().remove(1, null, accountId).execute();
drafts = api.draft().list(accountId).execute().body();
assertEquals(drafts.length, originalSize);
}
}
|
package com.example.navigationdrawerpractica.Entidades;
import android.os.Parcel;
import android.os.Parcelable;
public class Encuestas implements Parcelable {
private String Nombre,Detalle;
public Encuestas() {
}
public Encuestas(String nombre, String detalle) {
Nombre = nombre;
Detalle = detalle;
}
protected Encuestas(Parcel in) {
Nombre = in.readString();
Detalle = in.readString();
}
public static final Creator<Encuestas> CREATOR = new Creator<Encuestas>() {
@Override
public Encuestas createFromParcel(Parcel in) {
return new Encuestas(in);
}
@Override
public Encuestas[] newArray(int size) {
return new Encuestas[size];
}
};
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public String getDetalle() {
return Detalle;
}
public void setDetalle(String detalle) {
Detalle = detalle;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Nombre);
dest.writeString(Detalle);
}
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.08.10 um 09:13:50 PM CEST
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/1999/xlink", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = {
@javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/1999/xlink", prefix = "xlink")
})
package org.w3._1999.xlink;
|
package com.wisdomguo.xifeng.modules.dice.skillcoc.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wisdomguo.xifeng.modules.dice.skillcoc.entity.SkillCoC;
/**
* SkillCocMapper
*
* @author wisdom-guo
* @since 2021/4/3
*/
public interface SkillCocMapper extends BaseMapper<SkillCoC> {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.org.gdt.enums;
/**
*
* @author Juliano
*/
public enum NomeBanco {
BancoBrasil,
Bradesco,
Itaú,
CaixaEconômicaFederal,
Santander,
HSBC,
Banrisul,
Sicredi
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysml.runtime.matrix.sort;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileRecordReader;
import org.apache.hadoop.util.IndexedSortable;
import org.apache.hadoop.util.QuickSort;
import org.apache.sysml.runtime.matrix.data.Converter;
import org.apache.sysml.runtime.matrix.data.MatrixCell;
import org.apache.sysml.runtime.matrix.data.Pair;
import org.apache.sysml.runtime.matrix.mapred.MRJobConfiguration;
@SuppressWarnings("rawtypes")
public class SamplingSortMRInputFormat<K extends WritableComparable, V extends Writable>
extends SequenceFileInputFormat<K,V>
{
public static final String PARTITION_FILENAME = "_partition.lst";
static final String SAMPLE_SIZE = "sort.partitions.sample";
private static JobConf lastConf = null;
private static InputSplit[] lastResult = null;
public static final String TARGET_KEY_CLASS="target.key.class";
public static final String TARGET_VALUE_CLASS="target.value.class";
public static void setTargetKeyValueClasses(JobConf job, Class<? extends WritableComparable> keyClass,
Class<? extends Writable> valueClass)
{
job.setClass(TARGET_KEY_CLASS, keyClass, WritableComparable.class);
job.setClass(TARGET_VALUE_CLASS, valueClass, Writable.class);
}
@Override
public RecordReader<K,V> getRecordReader(InputSplit split,JobConf job, Reporter reporter)
throws IOException
{
if(reporter!=null)
reporter.setStatus(split.toString());
return new SequenceFileRecordReader<K,V>(job, (FileSplit) split);
}
/**
* Use the input splits to take samples of the input and generate sample
* keys. By default reads 100,000 keys from 10 locations in the input, sorts
* them and picks N-1 keys to generate N equally sized partitions.
*
* @param conf the job to sample
* @param partFile where to write the output file to
* @return index value
* @throws IOException if something goes wrong
* @throws InstantiationException if InstantiationException occurs
* @throws IllegalAccessException if IllegalAccessException occurs
*/
@SuppressWarnings({ "unchecked", "unused", "deprecation" })
public static int writePartitionFile(JobConf conf, Path partFile)
throws IOException, InstantiationException, IllegalAccessException
{
SamplingSortMRInputFormat inFormat = new SamplingSortMRInputFormat();
Sampler sampler = new Sampler();
Class<? extends WritableComparable> targetKeyClass;
targetKeyClass=(Class<? extends WritableComparable>) conf.getClass(TARGET_KEY_CLASS, WritableComparable.class);
//get input converter information
int brlen = MRJobConfiguration.getNumRowsPerBlock(conf, (byte) 0);
int bclen = MRJobConfiguration.getNumColumnsPerBlock(conf, (byte) 0);
//indicate whether the matrix value in this mapper is a matrix cell or a matrix block
int partitions = conf.getNumReduceTasks();
long sampleSize = conf.getLong(SAMPLE_SIZE, 1000);
InputSplit[] splits = inFormat.getSplits(conf, conf.getNumMapTasks());
int samples = Math.min(10, splits.length);
long recordsPerSample = sampleSize / samples;
int sampleStep = splits.length / samples;
// take N samples from different parts of the input
int totalcount = 0;
for(int i=0; i < samples; i++) {
SequenceFileRecordReader reader =
(SequenceFileRecordReader) inFormat.getRecordReader(splits[sampleStep * i], conf, null);
int count=0;
WritableComparable key = (WritableComparable) reader.createKey();
Writable value = (Writable) reader.createValue();
while (reader.next(key, value) && count<recordsPerSample) {
Converter inputConverter = MRJobConfiguration.getInputConverter(conf, (byte) 0);
inputConverter.setBlockSize(brlen, bclen);
inputConverter.convert(key, value);
while(inputConverter.hasNext())
{
Pair pair=inputConverter.next();
if( pair.getKey() instanceof DoubleWritable ){
sampler.addValue(new DoubleWritable(((DoubleWritable)pair.getKey()).get()));
}
else if( pair.getValue() instanceof MatrixCell ) {
sampler.addValue(new DoubleWritable(((MatrixCell)pair.getValue()).getValue()));
}
else
throw new IOException("SamplingSortMRInputFormat unsupported key/value class: "+pair.getKey().getClass()+":"+pair.getValue().getClass());
count++;
}
key = (WritableComparable) reader.createKey();
value = (Writable) reader.createValue();
}
totalcount += count;
}
if( totalcount == 0 ) //empty input files
sampler.addValue(new DoubleWritable(0));
FileSystem outFs = partFile.getFileSystem(conf);
if (outFs.exists(partFile)) {
outFs.delete(partFile, false);
}
//note: key value always double/null as expected by partitioner
SequenceFile.Writer writer =
SequenceFile.createWriter(outFs, conf, partFile, DoubleWritable.class, NullWritable.class);
NullWritable nullValue = NullWritable.get();
int index0=-1, i=0;
boolean lessthan0=true;
for(WritableComparable splitValue : sampler.createPartitions(partitions))
{
writer.append(splitValue, nullValue);
if(lessthan0 && ((DoubleWritable)splitValue).get()>=0) {
index0=i;
lessthan0=false;
}
i++;
}
if(lessthan0)
index0=partitions-1;
writer.close();
return index0;
}
@Override
public InputSplit[] getSplits(JobConf conf, int splits) throws IOException {
if (conf == lastConf) {
return lastResult;
}
lastConf = conf;
lastResult = super.getSplits(conf, splits);
return lastResult;
}
private static class Sampler implements IndexedSortable
{
private ArrayList<WritableComparable> records = new ArrayList<WritableComparable>();
@SuppressWarnings("unchecked")
public int compare(int i, int j) {
WritableComparable left = records.get(i);
WritableComparable right = records.get(j);
return left.compareTo(right);
}
public void swap(int i, int j) {
WritableComparable left = records.get(i);
WritableComparable right = records.get(j);
records.set(j, left);
records.set(i, right);
}
public void addValue(WritableComparable r)
{
records.add(r);
}
public String toString()
{
return records.toString();
}
/**
* Find the split points for a given sample. The sample keys are sorted
* and down sampled to find even split points for the partitions. The
* returned keys should be the start of their respective partitions.
* @param numPartitions the desired number of partitions
* @return an array of size numPartitions - 1 that holds the split points
*/
public ArrayList<WritableComparable> createPartitions(int numPartitions)
{
int numRecords = records.size();
if (numPartitions > numRecords) {
throw new IllegalArgumentException
("Requested more partitions than input keys (" + numPartitions +
" > " + numRecords + ")");
}
new QuickSort().sort(this, 0, records.size());
//System.out.println("after sort: "+ toString());
float stepSize = numRecords / (float) numPartitions;
//System.out.println("Step size is " + stepSize);
ArrayList<WritableComparable> result = new ArrayList<WritableComparable>(numPartitions-1);
for(int i=1; i < numPartitions; i++) {
result.add(records.get(Math.round(stepSize * i)));
}
return result;
}
}
}
|
/**
*
*/
package moyenneException;
/**
* @author Thomas LINTANF, Gabriel RIBIER
*
*/
public class moyenneException {
public static void main(String[] argv) {
if (argv.length <= 0) {
System.out.println("Il n'y a pas d'arguments");
System.exit(1);
}
try {
System.out.println("La moyenne est " + moyenne(argv));
}
catch (NumberFormatException e) {
System.out.println("Nombre invalide : ");
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println("Division par 0 : ");
System.out.println(e.getMessage());
}
}
public static int moyenne(String[] argv) {
int somme = 0;
int cpt = 0;
for (int i = 0; i < argv.length; i++) {
somme += Integer.parseInt(argv[i]);
cpt++;
}
return somme / cpt;
}
}
|
package com.jd.blockchain.crypto.impl.def.hash;
import static com.jd.blockchain.crypto.CryptoAlgorithm.RIPEMD160;
import static com.jd.blockchain.crypto.CryptoBytes.ALGORYTHM_BYTES;
import java.util.Arrays;
import com.jd.blockchain.crypto.CryptoAlgorithm;
import com.jd.blockchain.crypto.hash.HashDigest;
import com.jd.blockchain.crypto.hash.HashFunction;
import com.jd.blockchain.utils.security.RipeMD160Utils;
public class RIPEMD160HashFunction implements HashFunction {
private static final int DIGEST_BYTES = 160 / 8;
private static final int DIGEST_LENGTH = ALGORYTHM_BYTES + DIGEST_BYTES;
@Override
public CryptoAlgorithm getAlgorithm() {
return RIPEMD160;
}
@Override
public HashDigest hash(byte[] data) {
byte[] digestBytes = RipeMD160Utils.hash(data);
return new HashDigest(RIPEMD160, digestBytes);
}
@Override
public boolean verify(HashDigest digest, byte[] data) {
HashDigest hashDigest = hash(data);
return Arrays.equals(hashDigest.toBytes(), digest.toBytes());
}
@Override
public boolean supportHashDigest(byte[] digestBytes) {
// 验证输入字节数组长度=算法标识长度+摘要长度,以及算法标识;
return RIPEMD160.CODE == digestBytes[0] && DIGEST_LENGTH == digestBytes.length;
}
@Override
public HashDigest resolveHashDigest(byte[] digestBytes) {
// 由框架调用 support 方法检查有效性,在此不做重复检查;
return new HashDigest(digestBytes);
}
}
|
package water.rapids.ast.prims.mungers;
import water.*;
import water.fvec.*;
import water.rapids.Env;
import water.rapids.Merge;
import water.rapids.Val;
import water.rapids.ast.AstPrimitive;
import water.rapids.ast.AstRoot;
import water.rapids.ast.params.AstNum;
import water.rapids.ast.params.AstNumList;
import water.rapids.vals.ValFrame;
import water.rapids.vals.ValFun;
import water.util.ArrayUtils;
import water.util.IcedHashSet;
import water.util.Log;
import java.util.Arrays;
/**
* GroupBy
* Group the rows of 'data' by unique combinations of '[group-by-cols]'.
* Apply function 'fcn' to a Frame for each group, with a single column
* argument, and a NA-handling flag. Sets of tuples {fun,col,na} are allowed.
* <p/>
* 'fcn' must be a one of a small set of functions, all reductions, and 'GB'
* returns a row per unique group, with the first columns being the grouping
* columns, and the last column(s) the reduction result(s).
* <p/>
* However, GroupBy operations will not be performed on String columns. These columns
* will be skipped.
* <p/>
* The returned column(s).
*/
public class AstGroup extends AstPrimitive {
private final boolean _per_node_aggregates;
public AstGroup() {
this(true);
}
public AstGroup(boolean perNodeAggregates) {
_per_node_aggregates = perNodeAggregates;
}
public enum NAHandling {ALL, RM, IGNORE}
// Functions handled by GroupBy
public enum FCN {
nrow() {
@Override
public void op(double[] d0s, double d1) {
d0s[0]++;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
d0s[0] += d1s[0];
}
@Override
public double postPass(double ds[], long n) {
return ds[0];
}
},
mean() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] += d1;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
d0s[0] += d1s[0];
}
@Override
public double postPass(double ds[], long n) {
return ds[0] / n;
}
},
sum() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] += d1;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
d0s[0] += d1s[0];
}
@Override
public double postPass(double ds[], long n) {
return ds[0];
}
},
sumSquares() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] += d1 * d1;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
d0s[0] += d1s[0];
}
@Override
public double postPass(double ds[], long n) {
return ds[0];
}
},
var() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] += d1 * d1;
d0s[1] += d1;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
ArrayUtils.add(d0s, d1s);
}
@Override
public double postPass(double ds[], long n) {
double numerator = ds[0] - ds[1] * ds[1] / n;
if (Math.abs(numerator) < 1e-5) numerator = 0;
return numerator / (n - 1);
}
@Override
public double[] initVal(int ignored) {
return new double[2]; /* 0 -> sum_squares; 1 -> sum*/
}
},
sdev() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] += d1 * d1;
d0s[1] += d1;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
ArrayUtils.add(d0s, d1s);
}
@Override
public double postPass(double ds[], long n) {
double numerator = ds[0] - ds[1] * ds[1] / n;
if (Math.abs(numerator) < 1e-5) numerator = 0;
return Math.sqrt(numerator / (n - 1));
}
@Override
public double[] initVal(int ignored) {
return new double[2]; /* 0 -> sum_squares; 1 -> sum*/
}
},
min() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] = Math.min(d0s[0], d1);
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
op(d0s, d1s[0]);
}
@Override
public double postPass(double ds[], long n) {
return ds[0];
}
@Override
public double[] initVal(int maxx) {
return new double[]{Double.MAX_VALUE};
}
},
max() {
@Override
public void op(double[] d0s, double d1) {
d0s[0] = Math.max(d0s[0], d1);
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
op(d0s, d1s[0]);
}
@Override
public double postPass(double ds[], long n) {
return ds[0];
}
@Override
public double[] initVal(int maxx) {
return new double[]{-Double.MAX_VALUE};
}
},
median() { // we will be doing our own thing here for median
@Override
public void op(double[] d0s, double d1) {
;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
;
}
@Override
public double postPass(double ds[], long n) {
return 0;
}
@Override
public double[] initVal(int maxx) {
return new double[maxx];
}
},
mode() {
@Override
public void op(double[] d0s, double d1) {
d0s[(int) d1]++;
}
@Override
public void atomic_op(double[] d0s, double[] d1s) {
ArrayUtils.add(d0s, d1s);
}
@Override
public double postPass(double ds[], long n) {
return ArrayUtils.maxIndex(ds);
}
@Override
public double[] initVal(int maxx) {
return new double[maxx];
}
},;
public abstract void op(double[] d0, double d1);
public abstract void atomic_op(double[] d0, double[] d1);
public abstract double postPass(double ds[], long n);
public double[] initVal(int maxx) {
return new double[]{0};
}
}
@Override
public int nargs() {
return -1;
} // (GB data [group-by-cols] {fcn col "na"}...)
@Override
public String[] args() {
return new String[]{"..."};
}
@Override
public String str() {
return "GB";
}
@Override
public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
int ncols = fr.numCols();
AstNumList groupby = check(ncols, asts[2]);
final int[] gbCols = groupby.expand4();
int validAggregatesCount = countNumberOfAggregates(fr, ncols, asts);
final AGG[] aggs = constructAggregates(fr, validAggregatesCount, env, asts);
return performGroupingWithAggregations(fr, gbCols, aggs);
}
public ValFrame performGroupingWithAggregations(Frame fr, int[] gbCols, AGG[] aggs) {
final boolean hasMedian = hasMedian(aggs);
final IcedHashSet<G> gss = doGroups(fr, gbCols, aggs, hasMedian, _per_node_aggregates);
final G[] grps = gss.toArray(new G[gss.size()]);
applyOrdering(gbCols, grps);
final int medianActionsNeeded = hasMedian ? calculateMediansForGRPS(fr, gbCols, aggs, gss, grps) : -1;
MRTask mrFill = prepareMRFillTask(grps, aggs, medianActionsNeeded);
String[] fcNames = prepareFCNames(fr, aggs);
Frame f = buildOutput(gbCols, aggs.length, fr, fcNames, grps.length, mrFill);
return new ValFrame(f);
}
private static boolean hasMedian(AGG[] aggs) {
for (AGG agg : aggs)
if (FCN.median.equals(agg._fcn))
return true;
return false;
}
private MRTask prepareMRFillTask(final G[] grps, final AGG[] aggs, final int medianCount) {
return new MRTask() {
@Override
public void map(Chunk[] c, NewChunk[] ncs) {
int start = (int) c[0].start();
for (int i = 0; i < c[0]._len; ++i) {
G g = grps[i + start]; // One Group per row
int j;
for (j = 0; j < g._gs.length; j++) // The Group Key, as a row
ncs[j].addNum(g._gs[j]);
for (int a = 0; a < aggs.length; a++) {
if ((medianCount >=0) && g.medianR._isMedian[a])
ncs[j++].addNum(g.medianR._medians[a]);
else
ncs[j++].addNum(aggs[a]._fcn.postPass(g._dss[a], g._ns[a]));
}
}
}
};
}
private String[] prepareFCNames(Frame fr, AGG[] aggs) {
String[] fcnames = new String[aggs.length];
for (int i = 0; i < aggs.length; i++) {
if (aggs[i]._fcn.toString() != "nrow") {
fcnames[i] = aggs[i]._fcn.toString() + "_" + fr.name(aggs[i]._col);
} else {
fcnames[i] = aggs[i]._fcn.toString();
}
}
return fcnames;
}
// Count of aggregates; knock off the first 4 ASTs (GB data [group-by] [order-by]...), then count by triples.
private int countNumberOfAggregates(Frame fr, int numberOfColumns, AstRoot asts[]) {
int validGroupByCols = 0;
for (int idx=3; idx < asts.length; idx+=3) { // initial loop to count operations on valid columns, ignore String columns
AstNumList col = check(numberOfColumns, asts[idx + 1]);
if (col.cnt() != 1) throw new IllegalArgumentException("Group-By functions take only a single column");
int agg_col = (int) col.min(); // Aggregate column
if (fr.vec(agg_col).isString()) {
Log.warn("Column "+fr._names[agg_col]+" is a string column. Groupby operations will be skipped for this column.");
} else
validGroupByCols++;
}
return validGroupByCols;
}
private AGG[] constructAggregates(Frame fr, int numberOfAggregates, Env env, AstRoot asts[]) {
AGG[] aggs = new AGG[numberOfAggregates];
int ncols = fr.numCols();
int countCols = 0;
for (int idx = 3; idx < asts.length; idx += 3) {
Val v = asts[idx].exec(env);
String fn = v instanceof ValFun ? v.getFun().str() : v.getStr();
FCN fcn = FCN.valueOf(fn);
AstNumList col = check(ncols, asts[idx + 1]);
if (col.cnt() != 1) throw new IllegalArgumentException("Group-By functions take only a single column");
int agg_col = (int) col.min(); // Aggregate column
if (fcn == FCN.mode && !fr.vec(agg_col).isCategorical())
throw new IllegalArgumentException("Mode only allowed on categorical columns");
NAHandling na = NAHandling.valueOf(asts[idx + 2].exec(env).getStr().toUpperCase());
if (!fr.vec(agg_col).isString())
aggs[countCols++] = new AGG(fcn, agg_col, na, (int) fr.vec(agg_col).max() + 1);
}
return aggs;
}
private void applyOrdering(final int[] gbCols, G[] grps) {
if (gbCols.length > 0)
Arrays.sort(grps, new java.util.Comparator<G>() {
// Compare 2 groups. Iterate down _gs, stop when _gs[i] > that._gs[i],
// or _gs[i] < that._gs[i]. Order by various columns specified by
// gbCols. NaN is treated as least
@Override
public int compare(G g1, G g2) {
for (int i = 0; i < gbCols.length; i++) {
if (Double.isNaN(g1._gs[i]) && !Double.isNaN(g2._gs[i])) return -1;
if (!Double.isNaN(g1._gs[i]) && Double.isNaN(g2._gs[i])) return 1;
if (g1._gs[i] != g2._gs[i]) return g1._gs[i] < g2._gs[i] ? -1 : 1;
}
return 0;
}
// I do not believe sort() calls equals() at this time, so no need to implement
@Override
public boolean equals(Object o) {
throw H2O.unimpl();
}
});
}
private int calculateMediansForGRPS(Frame fr, int[] gbCols, AGG[] aggs, IcedHashSet<G> gss, G[] grps) {
// median action exists, we do the following three things:
// 1. Find out how many columns over all groups we need to perform median on
// 2. Assign an index to the NewChunk that we will be storing the data for each median column for each group
// 3. Fill out the NewChunk for each column of each group
int numberOfMedianActionsNeeded = 0;
for (G g : grps) {
for (int index = 0; index < g.medianR._isMedian.length; index++) {
if (g.medianR._isMedian[index]) {
g.medianR._newChunkCols[index] = numberOfMedianActionsNeeded++;
}
}
}
BuildGroup buildMedians = new BuildGroup(gbCols, aggs, gss, grps, numberOfMedianActionsNeeded);
Vec[] groupChunks = buildMedians.doAll(numberOfMedianActionsNeeded, Vec.T_NUM, fr).close();
buildMedians.calcMedian(groupChunks);
return numberOfMedianActionsNeeded;
}
// Argument check helper
public static AstNumList check(long dstX, AstRoot ast) {
// Sanity check vs dst. To simplify logic, jam the 1 col/row case in as a AstNumList
AstNumList dim;
if (ast instanceof AstNumList) dim = (AstNumList) ast;
else if (ast instanceof AstNum) dim = new AstNumList(((AstNum) ast).getNum());
else throw new IllegalArgumentException("Requires a number-list, but found a " + ast.getClass());
if (dim.isEmpty()) return dim; // Allow empty
for (int col : dim.expand4())
if (!(0 <= col && col < dstX))
throw new IllegalArgumentException("Selection must be an integer from 0 to " + dstX);
return dim;
}
// Do all the grouping work. Find groups in frame 'fr', grouped according to
// the selected 'gbCols' columns, and for each group compute aggregrate
// results using 'aggs'. Return an array of groups, with the aggregate results.
public static IcedHashSet<G> doGroups(Frame fr, int[] gbCols, AGG[] aggs) {
return doGroups(fr, gbCols, aggs, false, true);
}
private static IcedHashSet<G> doGroups(Frame fr, int[] gbCols, AGG[] aggs, boolean hasMedian, boolean perNodeAggregates) {
// do the group by work now
long start = System.currentTimeMillis();
GBTask<?> p1 = makeGBTask(perNodeAggregates, gbCols, aggs, hasMedian).doAll(fr);
Log.info("Group By Task done in " + (System.currentTimeMillis() - start) / 1000. + " (s)");
return p1.getGroups();
}
private static GBTask<? extends GBTask> makeGBTask(boolean perNodeAggregates, int[] gbCols, AGG[] aggs, boolean hasMedian) {
if (perNodeAggregates)
return new GBTaskAggsPerNode(gbCols, aggs, hasMedian);
else
return new GBTaskAggsPerMap(gbCols, aggs, hasMedian);
}
// Utility for AstDdply; return a single aggregate for counting rows-per-group
public static AGG[] aggNRows() {
return new AGG[]{new AGG(FCN.nrow, 0, NAHandling.IGNORE, 0)};
}
// Build output frame from the multi-column results
public static Frame buildOutput(int[] gbCols, int noutCols, Frame fr, String[] fcnames, int ngrps, MRTask mrfill) {
// Build the output!
// the names of columns
final int nCols = gbCols.length + noutCols;
String[] names = new String[nCols];
String[][] domains = new String[nCols][];
byte[] types = new byte[nCols];
for (int i = 0; i < gbCols.length; i++) {
names[i] = fr.name(gbCols[i]);
domains[i] = fr.domains()[gbCols[i]];
types[i] = fr.vec(names[i]).get_type();
}
for (int i = 0; i < fcnames.length; i++) {
names[i + gbCols.length] = fcnames[i];
types[i + gbCols.length] = Vec.T_NUM;
}
Vec v = Vec.makeZero(ngrps); // dummy layout vec
// Convert the output arrays into a Frame, also doing the post-pass work
Frame f = mrfill.doAll(types, new Frame(v)).outputFrame(names, domains);
v.remove();
return f;
}
// Description of a single aggregate, including the reduction function, the
// column and specified NA handling
public static class AGG extends Iced {
final FCN _fcn;
public final int _col;
final NAHandling _na;
final int _maxx; // Largest integer this column
public AGG(FCN fcn, int col, NAHandling na, int maxx) {
_fcn = fcn;
_col = col;
_na = na;
_maxx = maxx;
}
// Update the array pair {ds[i],ns[i]} with d1.
// ds is the reduction array
// ns is the element count
public void op(double[][] d0ss, long[] n0s, int i, double d1) {
// Normal number or ALL : call op()
if (!Double.isNaN(d1) || _na == NAHandling.ALL) _fcn.op(d0ss[i], d1);
// Normal number or IGNORE: bump count; RM: do not bump count
if (!Double.isNaN(d1) || _na == NAHandling.IGNORE) n0s[i]++;
}
// Atomically update the array pair {dss[i],ns[i]} with the pair {d1,n1}.
// Same as op() above, but called racily and updates atomically.
public void atomic_op(double[][] d0ss, long[] n0s, int i, double[] d1s, long n1) {
synchronized (d0ss[i]) {
_fcn.atomic_op(d0ss[i], d1s);
n0s[i] += n1;
}
}
public double[] initVal() {
return _fcn.initVal(_maxx);
}
}
private static abstract class GBTask<E extends MRTask<E>> extends MRTask<E> {
final int[] _gbCols; // Columns used to define group
final AGG[] _aggs; // Aggregate descriptions
final boolean _hasMedian;
GBTask(int[] gbCols, AGG[] aggs, boolean hasMedian) {
_gbCols = gbCols;
_aggs = aggs;
_hasMedian = hasMedian;
}
abstract IcedHashSet<G> getGroups();
}
// --------------------------------------------------------------------------
// Main worker MRTask. Makes 1 pass over the data, and accumulates both all
// groups and all aggregates
// This version merges discovered groups into a per-node aggregates map - it
// more memory efficient but it seems to suffer from a race condition
// (bug PUBDEV-6319).
private static class GBTaskAggsPerNode extends GBTask<GBTaskAggsPerNode> {
final IcedHashSet<G> _gss; // Shared per-node, common, racy
GBTaskAggsPerNode(int[] gbCols, AGG[] aggs, boolean hasMedian) {
super(gbCols, aggs, hasMedian);
_gss = new IcedHashSet<>();
}
@Override
public void map(Chunk[] cs) {
// Groups found in this Chunk
IcedHashSet<G> gs = new IcedHashSet<>();
G gWork = new G(_gbCols.length, _aggs, _hasMedian); // Working Group
G gOld; // Existing Group to be filled in
for (int row = 0; row < cs[0]._len; row++) {
// Find the Group being worked on
gWork.fill(row, cs, _gbCols); // Fill the worker Group for the hashtable lookup
if (gs.addIfAbsent(gWork) == null) { // Insert if not absent (note: no race, no need for atomic)
gOld = gWork; // Inserted 'gWork' into table
gWork = new G(_gbCols.length, _aggs, _hasMedian); // need entirely new G
} else gOld = gs.get(gWork); // Else get existing group
for (int i = 0; i < _aggs.length; i++) // Accumulate aggregate reductions
_aggs[i].op(gOld._dss, gOld._ns, i, cs[_aggs[i]._col].atd(row));
}
// This is a racy update into the node-local shared table of groups
reduce(gs); // Atomically merge Group stats
}
// Racy update on a subtle path: reduction is always single-threaded, but
// the shared global hashtable being reduced into is ALSO being written by
// parallel map calls.
@Override
public void reduce(GBTaskAggsPerNode t) {
if (_gss != t._gss) {
// this means we got the result from another node
// it is easy to partition the result into distinct subsets - we don't have to worry about collisions
// => no need to synchronize (but for now we do use atomic_op anyway), we just parallelize the merge
int otherSize = t._gss.size();
if (otherSize == 0)
return;
G[] otherGroups = t._gss.toArray(new G[otherSize]);
final int subGroupSize = otherSize > H2O.ARGS.nthreads ?
(int) Math.ceil((double) otherSize / H2O.ARGS.nthreads) : otherSize;
MergeGroupsFun f = new MergeGroupsFun(_aggs, _gss, otherGroups, subGroupSize);
if (subGroupSize == otherSize) {
f.map(0); // not worth parallelizing, execute directly
} else {
H2O.submitTask(new LocalMR(f, H2O.ARGS.nthreads)).join();
}
}
}
// Non-blocking race-safe update of the shared per-node groups hashtable
private void reduce(IcedHashSet<G> r) {
for (G rg : r) {
G lg;
if ((lg = _gss.addIfAbsent(rg)) != null) {
for (int i = 0; i < _aggs.length; i++)
_aggs[i].atomic_op(lg._dss, lg._ns, i, rg._dss[i], rg._ns[i]); // Need to atomically merge groups here
}
}
}
@Override
IcedHashSet<G> getGroups() {
return _gss;
}
}
private static class MergeGroupsFun extends MrFun<MergeGroupsFun> {
private final AGG[] _aggs;
private final transient IcedHashSet<G> _gss;
private final transient G[] _other;
private final int _size;
MergeGroupsFun(AGG[] aggs, IcedHashSet<G> gss, G[] other, int size) {
_aggs = aggs;
_gss = gss;
_other = other;
_size = size;
}
@Override
protected void map(final int subGroupId) {
for (int g = subGroupId * _size; g < (subGroupId + 1) * _size && g < _other.length; g++) {
G rg = _other[g];
G lg;
if ((lg = _gss.addIfAbsent(rg)) != null) {
for (int i = 0; i < _aggs.length; i++)
_aggs[i].atomic_op(lg._dss, lg._ns, i, rg._dss[i], rg._ns[i]); // Need to atomically merge groups here
}
}
}
}
// --------------------------------------------------------------------------
// "Safe" alternative of GBTaskAggsPerNode - instead of maintaining
// a node-global map of aggregates, it creates aggregates per chunk
// and uses reduce to reduce results of map into a single aggregated.
// Consumes more memory but doesn't suffer from bug PUBDEV-6319.
public static class GBTaskAggsPerMap extends GBTask<GBTaskAggsPerMap> {
IcedHashSet<G> _gss; // each map will have its own IcedHashMap
GBTaskAggsPerMap(int[] gbCols, AGG[] aggs, boolean hasMedian) {
super(gbCols, aggs, hasMedian);
}
@Override
public void map(Chunk[] cs) {
// Groups found in this Chunk
_gss = new IcedHashSet<>();
G gWork = new G(_gbCols.length, _aggs, _hasMedian); // Working Group
G gOld; // Existing Group to be filled in
for (int row = 0; row < cs[0]._len; row++) {
// Find the Group being worked on
gWork.fill(row, cs, _gbCols); // Fill the worker Group for the hashtable lookup
if (_gss.addIfAbsent(gWork) == null) { // Insert if not absent (note: no race, no need for atomic)
gOld = gWork; // Inserted 'gWork' into table
gWork = new G(_gbCols.length, _aggs, _hasMedian); // need entirely new G
} else gOld = _gss.get(gWork); // Else get existing group
for (int i = 0; i < _aggs.length; i++) // Accumulate aggregate reductions
_aggs[i].op(gOld._dss, gOld._ns, i, cs[_aggs[i]._col].atd(row));
}
}
// combine IcedHashMap from all threads here.
@Override
public void reduce(GBTaskAggsPerMap t) {
for (G rg : t._gss) {
if (_gss.addIfAbsent(rg) != null) {
G lg = _gss.get(rg);
for (int i = 0; i < _aggs.length; i++)
_aggs[i].atomic_op(lg._dss, lg._ns, i, rg._dss[i], rg._ns[i]); // Need to atomically merge groups here
}
}
}
@Override
IcedHashSet<G> getGroups() {
return _gss;
}
}
public static class MedianResult extends Iced {
int[] _medianCols;
double[] _medians;
boolean[] _isMedian;
int[] _newChunkCols;
public NAHandling[] _na;
public MedianResult(int len) {
_medianCols = new int[len];
_medians = new double[len];
_isMedian = new boolean[len];
_newChunkCols = new int[len];
_na = new NAHandling[len];
}
}
// Groups! Contains a Group Key - an array of doubles (often just 1 entry
// long) that defines the Group. Also contains an array of doubles for the
// aggregate results, one per aggregate.
public static class G extends Iced<G> {
public final double[] _gs; // Group Key: Array is final; contents change with the "fill"
int _hash; // Hash is not final; changes with the "fill"
public final double _dss[][]; // Aggregates: usually sum or sum*2
public final long _ns[]; // row counts per aggregate, varies by NA handling and column
/* int[] _medianCols; // record which columns in reference to data frame
double[] _medians;
boolean[] _isMedian;
int[] _newChunkCols; // record which columns in newChunk to store group
public NAHandling[] _na;*/
public MedianResult medianR = null;
public G(int ncols, AGG[] aggs) {
this(ncols, aggs, false);
}
public G(int ncols, AGG[] aggs, boolean hasMedian) {
_gs = new double[ncols];
int len = aggs == null ? 0 : aggs.length;
_dss = new double[len][];
_ns = new long[len];
if (hasMedian) {
medianR = new MedianResult(len);
}
for (int i = 0; i < len; i++) {
_dss[i] = aggs[i].initVal();
if (hasMedian && (aggs[i]._fcn.toString().equals("median"))) { // for median function only
medianR._medianCols[i] = aggs[i]._col; // which column in the data set to aggregate on
medianR._isMedian[i] = true;
medianR._na[i] = aggs[i]._na;
}
}
}
public G fill(int row, Chunk chks[]) {
for (int c = 0; c < chks.length; c++) // For all selection cols
_gs[c] = chks[c].atd(row); // Load into working array
_hash = hash();
return this;
}
public G fill(int row, Chunk chks[], int cols[]) {
for (int c = 0; c < cols.length; c++) // For all selection cols
_gs[c] = chks[cols[c]].atd(row); // Load into working array
_hash = hash();
return this;
}
protected int hash() {
long h = 0; // hash is sum of field bits
for (double d : _gs) h += Double.doubleToRawLongBits(d);
// Doubles are lousy hashes; mix up the bits some
h ^= (h >>> 20) ^ (h >>> 12);
h ^= (h >>> 7) ^ (h >>> 4);
return (int) ((h ^ (h >> 32)) & 0x7FFFFFFF);
}
@Override
public boolean equals(Object o) {
return o instanceof G && Arrays.equals(_gs, ((G) o)._gs);
}
@Override
public int hashCode() {
return _hash;
}
@Override
public String toString() {
return Arrays.toString(_gs);
}
}
// --------------------------------------------------------------------------
// For each groupG and each aggregate function (median only), we separate and
// extract the column per groupG per aggregate function into a NewChunk column
// here.
private static class BuildGroup extends MRTask<BuildGroup> {
final int[] _gbCols;
private final AGG[] _aggs; // Aggregate descriptions
private final int _medianCols;
IcedHashSet<G> _gss;
private G[] _grps;
BuildGroup(int[] gbCols, AGG[] aggs, IcedHashSet<G> gss, G[] grps, int medianCols) {
_gbCols = gbCols;
_aggs = aggs;
_gss = gss;
_grps = grps;
_medianCols = medianCols;
}
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
G gWork = new G(_gbCols.length, _aggs, _medianCols > 0); // Working Group
G gOld;
for (int row = 0; row < cs[0]._len; row++) { // for each
gWork.fill(row, cs, _gbCols);
gOld = _gss.get(gWork);
for (int i = 0; i < gOld.medianR._isMedian.length; i++) { // Accumulate aggregate reductions
if (gOld.medianR._isMedian[i]) { // median action required on column and group
double d1 = cs[gOld.medianR._medianCols[i]].atd(row);
if (!Double.isNaN(d1) || gOld.medianR._na[i] != NAHandling.RM)
ncs[gOld.medianR._newChunkCols[i]].addNum(d1); // build up dataset for each group
}
}
}
}
// For the data column collected for each G and each aggregate function, make a frame out of the data
// newChunk column. Sort the column and return median as the middle value of mean of two middle values.
Vec[] close() {
Futures fs = new Futures();
int cCount = 0;
Vec[] tempVgrps = new Vec[_medianCols];
for (G oneG : _grps) {
for (int index = 0; index < oneG.medianR._isMedian.length; index++) {
if (oneG.medianR._isMedian[index]) { // median action is needed
// make a frame out of the NewChunk vector
tempVgrps[cCount++] = _appendables[oneG.medianR._newChunkCols[index]].close(_appendables[oneG.medianR._newChunkCols[index]].compute_rowLayout(), fs);
}
}
}
fs.blockForPending();
return tempVgrps;
}
public void calcMedian(Vec[] tempVgrps) {
int cCount = 0;
for (G oneG : _grps) {
for (int index = 0; index < oneG.medianR._isMedian.length; index++) {
if (oneG.medianR._isMedian[index]) {
Vec[] vgrps = new Vec[1];
vgrps[0] = tempVgrps[cCount++];
long totalRows = vgrps[0].length();
double medianVal;
if (totalRows == 0) {
medianVal = Double.NaN; // return NAN for empty frames. Should not have happened!
} else {
Frame myFrame = new Frame(Key.<Frame>make(), vgrps, true);
long midRow = totalRows / 2;
Frame tempFrame = Merge.sort(myFrame, new int[]{0});
medianVal = totalRows % 2 == 0 ? 0.5 * (tempFrame.vec(0).at(midRow - 1) +
tempFrame.vec(0).at(midRow)) : tempFrame.vec(0).at(midRow);
tempFrame.delete();
myFrame.delete();
}
oneG.medianR._medians[index] = medianVal;
}
}
}
}
}
}
|
/*
* 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.
*/
/* @test
* @bug 4115296
*
* @summary synopsis: NoSuchObjectException not thrown for non-existent
* activatable objects
* @author Ann Wollrath
*
* @library ../../../../../testlibrary
* @build TestLibrary RMID ActivationLibrary
* @build ActivateMe
* @build NonExistentActivatable
* @build NonExistentActivatable_Stub
* @run shell classpath.sh main/othervm/policy=security.policy/timeout=240 -Dtest.rmi.exportType=default NonExistentActivatable
* @run shell classpath.sh main/othervm/policy=security.policy/timeout=240 -Dtest.rmi.exportType=basic NonExistentActivatable
* @run shell classpath.sh main/othervm/policy=security.policy/timeout=240 -Dtest.rmi.exportType=jrmp NonExistentActivatable
*/
import java.io.*;
import java.rmi.*;
import java.rmi.activation.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.Properties;
import net.jini.jeri.*;
public class NonExistentActivatable
implements ActivateMe, Serializable
{
private ActivationLibrary.ExportHelper helper;
public NonExistentActivatable(ActivationID id, MarshalledObject obj)
throws ActivationException, RemoteException
{
helper = new ActivationLibrary.ExportHelper(obj, this, id);
helper.export();
}
private Object writeReplace() {
return helper.getStub();
}
public void ping()
{}
public void unregister() throws Exception {
Activatable.unregister(helper.getActivationID());
}
/**
* Spawns a thread to deactivate the object.
*/
public void shutdown() throws Exception
{
helper.deactivate();
}
public static void main(String[] args) {
System.out.println("\nRegression test for bug 4115331\n");
TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager");
String exportType =
TestLibrary.getProperty("test.rmi.exportType","default");
System.err.println("exportType: " + exportType);
RMID rmid = null;
try {
RMID.removeLog();
rmid = RMID.createRMID();
rmid.start();
/* Cause activation groups to have a security policy that will
* allow security managers to be downloaded and installed
*/
Properties p = new Properties();
// this test must always set policies/managers in its
// activation groups
p.put("java.security.policy",
TestParams.defaultGroupPolicy);
p.put("java.security.manager",
TestParams.defaultSecurityManager);
System.err.println("Create activation group");
ActivationGroupDesc groupDesc = new ActivationGroupDesc(p, null);
ActivationSystem system = ActivationGroup.getSystem();
ActivationGroupID groupID = system.registerGroup(groupDesc);
System.err.println("Creating descriptor");
ActivationDesc desc =
new ActivationDesc(groupID, "NonExistentActivatable", null,
new MarshalledObject(exportType));
System.err.println("Registering descriptor");
ActivateMe obj = (ActivateMe)
ActivationLibrary.register(exportType, desc);
System.err.println("Activate object via method call");
obj.ping();
System.err.println("Unregister object");
obj.unregister();
System.err.println("Make object inactive");
obj.shutdown();
// give server side a chance to actually go inactive
Thread.sleep(6000);
System.err.println("Reactivate object");
try {
obj.ping();
TestLibrary.bomb("ping succeeded");
} catch (NoSuchObjectException e) {
System.err.println("Test succeeded: " +
"NoSuchObjectException caught");
return;
} catch (Exception e) {
TestLibrary.bomb("Test failed: exception other than NoSuchObjectException",
e);
}
} catch (Exception e) {
TestLibrary.bomb("test failed", e);
} finally {
ActivationLibrary.rmidCleanup(rmid);
}
}
}
|
/*
* Copyright 2004-2010 the Seasar Foundation and the 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.
*/
package org.seasar.doma.wrapper;
import org.seasar.doma.DomaNullPointerException;
/**
* {@link Boolean} のラッパーです。
*
* @author taedium
*
*/
public class BooleanWrapper extends AbstractWrapper<Boolean> {
/**
* インスタンスを構築します。
*/
public BooleanWrapper() {
}
/**
* 値を指定してインスタンスを構築します。
*
* @param value
* 値
*/
public BooleanWrapper(Boolean value) {
super(value);
}
@Override
public Boolean getDefault() {
return Boolean.FALSE;
}
@Override
public <R, P, TH extends Throwable> R accept(
WrapperVisitor<R, P, TH> visitor, P p) throws TH {
if (visitor == null) {
throw new DomaNullPointerException("visitor");
}
if (visitor instanceof BooleanWrapperVisitor<?, ?, ?>) {
BooleanWrapperVisitor<R, P, TH> v = (BooleanWrapperVisitor<R, P, TH>) visitor;
return v.visitBooleanWrapper(this, p);
}
return visitor.visitUnknownWrapper(this, p);
}
}
|
package com.cattong.weibo.impl.netease;
import org.json.JSONException;
import org.json.JSONObject;
import com.cattong.commons.LibResultCode;
import com.cattong.commons.LibRuntimeException;
import com.cattong.commons.ServiceProvider;
import com.cattong.commons.util.StringUtil;
class NetEaseErrorAdaptor {
public static LibRuntimeException parseError(String errorString) {
try {
JSONObject json = new JSONObject(errorString);
int messageCode = json.getInt("message_code");
// errorCode去messageCode后5位数
int errorCode = ((messageCode % 1000000) % 100000);
String errorDesc = json.getString("error");
String requestPath = json.getString("request");
LibRuntimeException apiException = new LibRuntimeException(errorCode,
requestPath, errorDesc, ServiceProvider.NetEase);
parseStatusCode(apiException);
return apiException;
} catch (JSONException e) {
return new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR,
e, ServiceProvider.NetEase);
}
}
private static void parseStatusCode(LibRuntimeException apiException) {
if (apiException == null ||
apiException.getErrorCode() == LibResultCode.E_UNKNOWN_ERROR ||
StringUtil.isEmpty(apiException.getErrorDescr())) {
return;
}
String errorDesc = apiException.getErrorDescr().toLowerCase();
int errorCode = apiException.getErrorCode();
int errorCodePlaform = LibResultCode.E_UNKNOWN_ERROR;
//取前三位
int errorCodeHeaderThree = errorCode / 100;
if (errorCodeHeaderThree == 400) {
errorCodePlaform = LibResultCode.API_MB_PARAMS_ERROR;
}
if (errorCodeHeaderThree == 401) {
if (errorCode < 40104) {
errorCodePlaform = LibResultCode.API_MB_USER_NOT_EXIST;
} else {
switch (errorCode) {
case 40104:
errorCodePlaform = LibResultCode.OAUTH_VERSION_REJECTED;
break;
case 40105:
errorCodePlaform = LibResultCode.OAUTH_PARAMETER_ABSENT;
break;
case 40106:
errorCodePlaform = LibResultCode.OAUTH_PARAMETER_REJECTED;
break;
case 40107:
errorCodePlaform = LibResultCode.OAUTH_TIMESTAMP_REFUSED;
break;
case 40108:
errorCodePlaform = LibResultCode.OAUTH_NONCE_USED;
break;
case 40109:
errorCodePlaform = LibResultCode.OAUTH_SIGNATURE_METHOD_REJECTED;
break;
case 40110:
errorCodePlaform = LibResultCode.OAUTH_SIGNATURE_INVALID;
break;
case 40111:
errorCodePlaform = LibResultCode.OAUTH_CONSUMER_KEY_UNKNOWN;
break;
case 40112:
errorCodePlaform = LibResultCode.OAUTH_CONSUMER_KEY_REJECTED;
break;
case 40113:
errorCodePlaform = LibResultCode.OAUTH_CONSUMER_KEY_REFUSED;
break;
case 40114:
errorCodePlaform = LibResultCode.OAUTH_TOKEN_USED;
break;
case 40115:
errorCodePlaform = LibResultCode.OAUTH_TOKEN_EXPIRED;
break;
case 40116:
errorCodePlaform = LibResultCode.OAUTH_TOKEN_REVOKED;
break;
case 40117:
errorCodePlaform = LibResultCode.OAUTH_TOKEN_REJECTED;
break;
case 40118:
errorCodePlaform = LibResultCode.OAUTH_ADDITIONAL_AUTHORIZATION_REQUIRED;
break;
case 40119:
errorCodePlaform = LibResultCode.OAUTH_PERMISSION_UNKNOWN;
break;
case 40120:
errorCodePlaform = LibResultCode.OAUTH_PERMISSION_DENIED;
break;
case 40121:
errorCodePlaform = LibResultCode.OAUTH_USER_REFUSED;
break;
default:
errorCodePlaform = LibResultCode.E_UNKNOWN_ERROR;
}
}
}
if (errorCodeHeaderThree == 403) {
switch (errorCode) {
case 40303:
errorCodePlaform = LibResultCode.API_MB_IP_LIMITED;
break;
case 40306:
errorCodePlaform = LibResultCode.API_MB_CONTENT_ILLEGAL;
break;
case 40307:
errorCodePlaform = LibResultCode.API_MB_PERMISSION_ACCESS_LIMITED;
break;
case 40308:
case 40312:
errorCodePlaform = LibResultCode.API_MB_INVOKE_RATE_TOO_QUICK;
break;
case 40314:
errorCodePlaform = LibResultCode.API_MB_MESSAGE_RECEIVER_NOT_FOLLOWER;
break;
case 40316:
errorCodePlaform = LibResultCode.API_MB_MESSAGE_NOT_OWNER;
break;
case 40319:
errorCodePlaform = LibResultCode.API_MB_MESSAGE_LIMITED;
break;
case 40320:
errorCodePlaform = LibResultCode.API_MB_CONTENT_OVER_LENGTH;
break;
default:
errorCodePlaform = LibResultCode.E_UNKNOWN_ERROR;
}
}
if (errorCodeHeaderThree == 404) {
switch (errorCode) {
case 40401:
errorCodePlaform = LibResultCode.API_MB_USER_NOT_EXIST;
break;
case 40402:
errorCodePlaform = LibResultCode.API_MB_TWEET_NOT_EXIST;
break;
case 40404:
errorCodePlaform = LibResultCode.API_MB_MESSAGE_NOT_EXIST;
break;
case 40407:
errorCodePlaform = LibResultCode.API_MB_USER_NOT_EXIST;
break;
}
}
if (errorCodeHeaderThree == 500) {
errorCodePlaform = LibResultCode.SC_INTERNAL_SERVER_ERROR;
}
apiException.setStatusCode(errorCodePlaform);
apiException.setErrorCode(errorCode);
apiException.setErrorDescr(errorDesc);
}
}
|
/*
* Copyright 2016 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.keycloak.testsuite.exportimport;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Test;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.exportimport.ExportImportConfig;
import org.keycloak.exportimport.dir.DirExportProvider;
import org.keycloak.exportimport.dir.DirExportProviderFactory;
import org.keycloak.exportimport.singlefile.SingleFileExportProviderFactory;
import org.keycloak.representations.idm.*;
import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.Assert;
import org.keycloak.testsuite.runonserver.RunHelpers;
import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import org.keycloak.testsuite.util.UserBuilder;
import java.io.File;
import java.net.URL;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
/**
*
*
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class ExportImportTest extends AbstractKeycloakTest {
@Deployment
public static WebArchive deploy() {
return RunOnServerDeployment.create(ExportImportTest.class);
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation testRealm1 = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
testRealm1.getUsers().add(makeUser("user1"));
testRealm1.getUsers().add(makeUser("user2"));
testRealm1.getUsers().add(makeUser("user3"));
testRealm1.getSmtpServer().put("password", "secret");
setEventsConfig(testRealm1);
testRealms.add(testRealm1);
RealmRepresentation testRealm2 = loadJson(getClass().getResourceAsStream("/model/testrealm.json"), RealmRepresentation.class);
testRealm2.setId("test-realm");
testRealms.add(testRealm2);
}
private void setEventsConfig(RealmRepresentation realm) {
realm.setEventsEnabled(true);
realm.setAdminEventsEnabled(true);
realm.setAdminEventsDetailsEnabled(true);
realm.setEventsExpiration(600);
realm.setEnabledEventTypes(Arrays.asList("REGISTER", "REGISTER_ERROR", "LOGIN", "LOGIN_ERROR", "LOGOUT_ERROR"));
}
private void checkEventsConfig(RealmEventsConfigRepresentation config) {
Assert.assertTrue(config.isEventsEnabled());
Assert.assertTrue(config.isAdminEventsEnabled());
Assert.assertTrue(config.isAdminEventsDetailsEnabled());
Assert.assertEquals((Long) 600L, config.getEventsExpiration());
Assert.assertNames(new HashSet(config.getEnabledEventTypes()),"REGISTER", "REGISTER_ERROR", "LOGIN", "LOGIN_ERROR", "LOGOUT_ERROR");
}
private UserRepresentation makeUser(String userName) {
return UserBuilder.create()
.username(userName)
.email(userName + "@test.com")
.password("password")
.build();
}
@After
public void clearExportImportProps() throws LifecycleException {
clearExportImportProperties();
}
@Test
public void testDirFullExportImport() throws Throwable {
testingClient.testing().exportImport().setProvider(DirExportProviderFactory.PROVIDER_ID);
String targetDirPath = testingClient.testing().exportImport().getExportImportTestDirectory()+ File.separator + "dirExport";
DirExportProvider.recursiveDeleteDir(new File(targetDirPath));
testingClient.testing().exportImport().setDir(targetDirPath);
testingClient.testing().exportImport().setUsersPerFile(ExportImportConfig.DEFAULT_USERS_PER_FILE);
testFullExportImport();
// There should be 6 files in target directory (3 realm, 3 user)
assertEquals(6, new File(targetDirPath).listFiles().length);
}
@Test
public void testDirRealmExportImport() throws Throwable {
testingClient.testing()
.exportImport()
.setProvider(DirExportProviderFactory.PROVIDER_ID);
String targetDirPath = testingClient.testing().exportImport().getExportImportTestDirectory() + File.separator + "dirRealmExport";
DirExportProvider.recursiveDeleteDir(new File(targetDirPath));
testingClient.testing().exportImport().setDir(targetDirPath);
testingClient.testing().exportImport().setUsersPerFile(3);
testRealmExportImport();
// There should be 3 files in target directory (1 realm, 4 user)
File[] files = new File(targetDirPath).listFiles();
assertEquals(5, files.length);
}
@Test
public void testSingleFileFullExportImport() throws Throwable {
testingClient.testing().exportImport().setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
String targetFilePath = testingClient.testing().exportImport().getExportImportTestDirectory() + File.separator + "singleFile-full.json";
testingClient.testing().exportImport().setFile(targetFilePath);
testFullExportImport();
}
@Test
public void testSingleFileRealmExportImport() throws Throwable {
testingClient.testing().exportImport().setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
String targetFilePath = testingClient.testing().exportImport().getExportImportTestDirectory() + File.separator + "singleFile-realm.json";
testingClient.testing().exportImport().setFile(targetFilePath);
testRealmExportImport();
}
@Test
public void testSingleFileRealmWithoutBuiltinsImport() throws Throwable {
// Remove test realm
removeRealm("test-realm");
// Set the realm, which doesn't have builtin clients/roles inside JSON
testingClient.testing().exportImport().setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
URL url = ExportImportTest.class.getResource("/model/testrealm.json");
String targetFilePath = new File(url.getFile()).getAbsolutePath();
testingClient.testing().exportImport().setFile(targetFilePath);
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_IMPORT);
testingClient.testing().exportImport().runImport();
RealmResource testRealmRealm = adminClient.realm("test-realm");
ExportImportUtil.assertDataImportedInRealm(adminClient, testingClient, testRealmRealm.toRepresentation());
}
@Test
public void testImportFromPartialExport() {
// import a realm with clients without roles
importRealmFromFile("/import/partial-import.json");
Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("partial-import"));
// import a realm with clients without roles
importRealmFromFile("/import/import-without-roles.json");
Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("import-without-roles"));
// import a realm with roles without clients
importRealmFromFile("/import/import-without-clients.json");
Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("import-without-clients"));
}
private boolean isRealmPresent(String realmId) {
return adminClient.realms().findAll().stream().filter(realm -> realmId.equals(realm.getId())).findFirst().isPresent();
}
private void testFullExportImport() throws LifecycleException {
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_EXPORT);
testingClient.testing().exportImport().setRealmName("");
testingClient.testing().exportImport().runExport();
removeRealm("test");
removeRealm("test-realm");
Assert.assertNames(adminClient.realms().findAll(), "master");
assertNotAuthenticated("test", "test-user@localhost", "password");
assertNotAuthenticated("test", "user1", "password");
assertNotAuthenticated("test", "user2", "password");
assertNotAuthenticated("test", "user3", "password");
// Configure import
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_IMPORT);
testingClient.testing().exportImport().runImport();
// Ensure data are imported back
Assert.assertNames(adminClient.realms().findAll(), "master", "test", "test-realm");
assertAuthenticated("test", "test-user@localhost", "password");
assertAuthenticated("test", "user1", "password");
assertAuthenticated("test", "user2", "password");
assertAuthenticated("test", "user3", "password");
// KEYCLOAK-6050 Check SMTP password is exported/imported
assertEquals("secret", testingClient.server("test").fetch(RunHelpers.internalRealm()).getSmtpServer().get("password"));
}
private void testRealmExportImport() throws LifecycleException {
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_EXPORT);
testingClient.testing().exportImport().setRealmName("test");
testingClient.testing().exportImport().runExport();
List<ComponentRepresentation> components = adminClient.realm("test").components().query();
KeysMetadataRepresentation keyMetadata = adminClient.realm("test").keys().getKeyMetadata();
String sampleRealmRoleId = adminClient.realm("test").roles().get("sample-realm-role").toRepresentation().getId();
String testAppId = adminClient.realm("test").clients().findByClientId("test-app").get(0).getId();
String sampleClientRoleId = adminClient.realm("test").clients().get(testAppId).roles().get("sample-client-role").toRepresentation().getId();
// Delete some realm (and some data in admin realm)
adminClient.realm("test").remove();
Assert.assertNames(adminClient.realms().findAll(), "test-realm", "master");
assertNotAuthenticated("test", "test-user@localhost", "password");
assertNotAuthenticated("test", "user1", "password");
assertNotAuthenticated("test", "user2", "password");
assertNotAuthenticated("test", "user3", "password");
// Configure import
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_IMPORT);
testingClient.testing().exportImport().runImport();
// Ensure data are imported back, but just for "test" realm
Assert.assertNames(adminClient.realms().findAll(), "master", "test", "test-realm");
assertAuthenticated("test", "test-user@localhost", "password");
assertAuthenticated("test", "user1", "password");
assertAuthenticated("test", "user2", "password");
assertAuthenticated("test", "user3", "password");
List<ComponentRepresentation> componentsImported = adminClient.realm("test").components().query();
assertComponents(components, componentsImported);
KeysMetadataRepresentation keyMetadataImported = adminClient.realm("test").keys().getKeyMetadata();
assertEquals(keyMetadata.getActive(), keyMetadataImported.getActive());
String importedSampleRealmRoleId = adminClient.realm("test").roles().get("sample-realm-role").toRepresentation().getId();
assertEquals(sampleRealmRoleId, importedSampleRealmRoleId);
String importedSampleClientRoleId = adminClient.realm("test").clients().get(testAppId).roles().get("sample-client-role").toRepresentation().getId();
assertEquals(sampleClientRoleId, importedSampleClientRoleId);
checkEventsConfig(adminClient.realm("test").getRealmEventsConfig());
}
private void assertAuthenticated(String realmName, String username, String password) {
assertAuth(true, realmName, username, password);
}
private void assertNotAuthenticated(String realmName, String username, String password) {
assertAuth(false, realmName, username, password);
}
private void assertAuth(boolean expectedResult, String realmName, String username, String password) {
assertEquals(expectedResult, testingClient.testing().validCredentials(realmName, username, password));
}
private void assertComponents(List<ComponentRepresentation> expected, List<ComponentRepresentation> actual) {
expected.sort((o1, o2) -> o1.getId().compareTo(o2.getId()));
actual.sort((o1, o2) -> o1.getId().compareTo(o2.getId()));
assertEquals(expected.size(), actual.size());
for (int i = 0 ; i < expected.size(); i++) {
ComponentRepresentation e = expected.get(i);
ComponentRepresentation a = actual.get(i);
assertEquals(e.getId(), a.getId());
assertEquals(e.getName(), a.getName());
assertEquals(e.getProviderId(), a.getProviderId());
assertEquals(e.getProviderType(), a.getProviderType());
assertEquals(e.getParentId(), a.getParentId());
assertEquals(e.getSubType(), a.getSubType());
Assert.assertNames(e.getConfig().keySet(), a.getConfig().keySet().toArray(new String[] {}));
// Compare config values without take order into account
for (Map.Entry<String, List<String>> entry : e.getConfig().entrySet()) {
List<String> eList = entry.getValue();
List<String> aList = a.getConfig().getList(entry.getKey());
Assert.assertNames(eList, aList.toArray(new String[] {}));
}
}
}
private void clearExportImportProperties() {
// Clear export/import properties after test
Properties systemProps = System.getProperties();
Set<String> propsToRemove = new HashSet<String>();
for (Object key : systemProps.keySet()) {
if (key.toString().startsWith(ExportImportConfig.PREFIX)) {
propsToRemove.add(key.toString());
}
}
for (String propToRemove : propsToRemove) {
systemProps.remove(propToRemove);
}
}
private void importRealmFromFile(String path) {
testingClient.testing().exportImport().setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
URL url = ExportImportTest.class.getResource(path);
String targetFilePath = new File(url.getFile()).getAbsolutePath();
testingClient.testing().exportImport().setFile(targetFilePath);
testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_IMPORT);
testingClient.testing().exportImport().runImport();
}
}
|
package app.eeui.framework.ui.module;
import android.app.Activity;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import app.eeui.framework.extend.module.eeuiJson;
import app.eeui.framework.extend.module.eeuiPage;
import app.eeui.framework.ui.eeui;
public class WeexNavigatorModule extends WXModule {
private eeui __obj;
private eeui myApp() {
if (__obj == null) {
__obj = new eeui();
}
return __obj;
}
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
@JSMethod
public void push(String object, JSCallback callback) {
JSONObject json = eeuiJson.parseObject(object);
if (json.size() == 0) {
json.put("url", object);
}
String pageTitle = eeuiJson.getString(json, "pageTitle", "");
json.put("pageTitle", json.containsKey("pageTitle") ? pageTitle : " ");
myApp().openPage(mWXSDKInstance, json.toJSONString(), callback);
}
@JSMethod
public void pop(String object, JSCallback callback) {
JSONObject json = eeuiJson.parseObject(object);
if (eeuiJson.getString(json, "pageName", null) == null) {
json.put("pageName", eeuiPage.getPageName((Activity) mWXSDKInstance.getContext()));
}
if (callback != null) {
json.put("listenerName", "__navigatorPop");
myApp().setPageStatusListener(mWXSDKInstance.getContext(), json.toJSONString(), callback);
}
myApp().closePage(mWXSDKInstance.getContext(), json.toJSONString());
}
}
|
package fr.brouillard.oss.cssfx.impl.events;
/*
* #%L
* CSSFX
* %%
* Copyright (C) 2014 CSSFX by Matthieu Brouillard
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@FunctionalInterface
public interface CSSFXEventListener {
public void onEvent(CSSFXEvent<?> event);
}
|
/**
* projectName: autobots
* fileName: FakerUtils.java
* packageName: com.autobots.utils.faker
* date: 2019-11-27 下午4:17
*/
package com.ceshiren.hogwarts.service.wechat.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @version: V1.0
* @author: kuohai
* @className: FakerUtils
* @packageName: com.autobots.utils.faker
* @description: 数据伪造工具类
* @data: 2019-11-27 下午4:17
**/
public class FakerUtils {
private final static int delta = 0x9fa5 - 0x4e00 + 1;
/**
* @author: kuohai
* @methodsName: getRandomInt
* @description:
* @param: [lengh] 获取的随机数的长度
* @return: int 随机数
* @throws:
*/
public static int getRandomInt(int lengh) {
lengh = lengh - 1;
int randomint = (int) ((Math.random() * 9 + 1) * Math.pow(10, (double) lengh));
return randomint;
}
/**
* @param min 获取的随机数左边界
* @param max 获取的随机数右边界
* @author: kuohai
* @methodsName: getRandomInt
* @description:
* @return: int 随机数
* @throws:
*/
public static int getRandomInt(int min, int max) {
Random random = new Random();
int s = random.nextInt(max) % (max - min + 1) + min;
return s;
}
/**
* @author: kuohai
* @methodsName: getTimeStamp
* @description:
* @param: []
* @return: java.lang.String
* @throws:
*/
public static String getTimeStamp(){
return String.valueOf(System.currentTimeMillis());
}
/**
* @author: kuohai
* @methodsName: getNum
* @description:
* @param: [start, end]
* @return: int
*/
public static int getNum(
int start, int end) {
return (int) (Math.random() * (end - start + 1) + start);
}
/**
* @author: kuohai
* @methodsName: orderNo
* @description:14位订单号生成器
* @param: []
* @return: java.lang.String
* @throws:
*/
public static String orderNo() {
String cardNo = "123456";
for (int i = 0; i < 8; i++) {
cardNo += getNum(0, 9);
}
return cardNo;
}
/**
* 电话号码生成器
*/
private static String[] telFirst = "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,188,185,181".split(",");
/**
* @author: kuohai
* @methodsName: getTel
* @description:
* @return: java.lang.String
*/
public static String getTel() {
int index = getNum(0, telFirst.length - 1);
String first = telFirst[index];
String second = String.valueOf(getNum(1, 888) + 10000).substring(1);
String thrid = String.valueOf(getNum(1, 9100) + 10000).substring(1);
return first + second + thrid;
}
/**
* @author: kuohai
* @methodsName: getTestData
* @description:
* @param: [fileName]
* @return: java.lang.Object[][]
* @throws: IOException
*/
public static Object[][] getTestData(String fileName) throws IOException {
String projectRoot = new File("").getAbsolutePath();
List<Object[]> records = new ArrayList<Object[]>();
String record;
//设置字符集为UTF-8
BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(projectRoot + fileName), "UTF-8"));
//忽略CSV文件的标题行(第一行)
file.readLine();
//遍历读取文件中除第一行外的其它所有行内容,并存储在名为records的ArrayList中,每一个records中存储的对象为一个string数组;
while ((record = file.readLine()) != null) {
String fields[] = record.split(",");
records.add(fields);
}
//关闭文件
file.close();
//定义函数返回值Object[][],将list转换为一个Object的二维数组;
Object[][] results = new Object[records.size()][];
//设置二维数组每行的值,每行是一个Object对象
for (int i = 0; i < records.size(); i++) {
results[i] = records.get(i);
}
return results;
}
}
|
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.openapi.generators;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Constants for openapi code generator.
*/
public class GeneratorConstants {
/**
* Enum to select the code generation mode.
* Ballerina service, mock and client generation is available
*/
public enum GenType {
GEN_SERVICE("gen_service"),
GEN_CLIENT("gen_client"),
GEN_BOTH("gen_both");
private String name;
GenType(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
/**
* Enum to select the relevant ballerina http auth record.
*/
public enum AuthConfigTypes {
BASIC("http:CredentialsConfig"),
BEARER("http:BearerTokenConfig"),
CLIENT_CREDENTIAL("http:OAuth2ClientCredentialsGrantConfig"),
REFRESH_TOKEN("http:OAuth2RefreshTokenGrantConfig"),
PASSWORD("http:OAuth2PasswordGrantConfig");
private final String authType;
AuthConfigTypes(String authType) {
this.authType = authType;
}
public String getValue() {
return authType;
}
}
public static final String CLIENT_TEMPLATE_NAME = "client-ep";
public static final String TYPE_FILE_NAME = "types.bal";
public static final String CLIENT_FILE_NAME = "client.bal";
public static final String UTIL_FILE_NAME = "utils.bal";
public static final String TEST_FILE_NAME = "test.bal";
public static final String CONFIG_FILE_NAME = "Config.toml";
public static final String BALLERINA_TOML = "Ballerina.toml";
public static final String BALLERINA_TOML_CONTENT = "[package]\n" +
"org= \"ballerina\"\n" +
"name= \"testopenapi\"\n" +
"version= \"0.0.0\"\n";
public static final String TEMPLATES_SUFFIX = ".mustache";
public static final String TEMPLATES_DIR_PATH_KEY = "templates.dir.path";
public static final String DEFAULT_TEMPLATE_DIR = "/templates";
public static final String DEFAULT_CLIENT_DIR = DEFAULT_TEMPLATE_DIR + "/client";
public static final String DEFAULT_CLIENT_PKG = "client";
public static final String DEFAULT_MOCK_PKG = "mock";
public static final String OAS_PATH_SEPARATOR = "/";
public static final String USER_DIR = "user.dir";
public static final String UNTITLED_SERVICE = "UntitledAPI";
public static final List<String> RESERVED_KEYWORDS = Collections.unmodifiableList(
Arrays.asList("abort", "aborted", "abstract", "all", "annotation",
"any", "anydata", "boolean", "break", "byte", "catch", "channel", "check", "checkpanic", "client",
"committed", "const", "continue", "decimal", "else", "error", "external", "fail", "final",
"finally", "float", "flush", "fork", "function", "future", "handle", "if", "import", "in", "int",
"is", "join", "json", "listener", "lock", "match", "new", "object", "OBJECT_INIT", "onretry",
"parameter", "panic", "private", "public", "record", "remote", "resource", "retries", "retry",
"return", "returns", "service", "source", "start", "stream", "string", "table", "transaction",
"try", "type", "typedesc", "typeof", "trap", "throw", "wait", "while", "with", "worker", "var",
"version", "xml", "xmlns", "BOOLEAN_LITERAL", "NULL_LITERAL", "ascending", "descending", "foreach",
"map", "group", "from", "default", "field", "limit", "as", "on", "isolated", "readonly",
"distinct", "where", "select", "do", "transactional", "commit", "enum", "base16", "base64",
"rollback", "configurable", "class", "module", "never", "outer", "order", "null", "key", "let",
"by", "equals"));
public static final String ESCAPE_PATTERN = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/\\_{}\\s|.$])";
//ClientCode generator
public static final String HTTP = "http";
public static final String URL = "url";
public static final String MODULE_TEST = "test";
public static final String BALLERINA = "ballerina";
public static final String PUBLIC = "public";
public static final String PUBLIC_ISOLATED = "public isolated";
public static final String CLIENT = "client";
public static final String CLIENT_CLASS = "Client";
public static final String CLIENT_EP = "clientEp";
public static final String CLASS = "class";
public static final String EQUAL = "=";
public static final String CONFIG = "config";
public static final String FUNCTION = "function";
public static final String RETURN = "returns";
public static final String PREFIX_TEST = " test";
public static final String ANNOT_TEST = "test:Config";
public static final String TEST_DIR = "tests";
public static final String STRING = "string";
public static final String XML = "xml";
public static final String BYTE = "byte";
public static final String JSON = "json";
public static final String SERVICE_URL = "serviceUrl";
public static final String RECORD = "record";
public static final String IDENTIFIER = "identifier";
public static final String TYPE_NAME = "typeName";
// auth related constants
public static final String API_KEY = "apikey";
public static final String API_KEYS_CONFIG = "ApiKeysConfig";
public static final String API_KEY_CONFIG_PARAM = "apiKeyConfig";
public static final String API_KEY_CONFIG_RECORD_FIELD = "apiKeys";
public static final String AUTH = "auth";
public static final String AUTH_CONFIG = "authConfig";
public static final String BASIC = "basic";
public static final String BEARER = "bearer";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String CLIENT_CRED = "client_cred";
public static final String PASSWORD = "password";
public static final String CONFIG_RECORD_ARG = "clientConfig";
public static final String CLIENT_CONFIG = "ClientConfig";
public static final String OAUTH2 = "oauth2";
public static final String SSL_FIELD_NAME = "secureSocket";
public static final String DEFAULT_API_KEY_DESC = "API keys for authorization";
public static final String RESPONSE = "response";
public static final String TYPE = "type";
public static final String ANY_DATA = "anydata";
//Http Methods
public static final String POST = "post";
public static final String GET = "get";
public static final String PUT = "put";
public static final String DELETE = "delete";
public static final String PATCH = "patch";
public static final String EXECUTE = "execute";
public static final String HEAD = "head";
public static final String CONNECT = "connect";
public static final String OPTIONS = "options";
public static final String TRACE = "trace";
//Encoding related constants
public static final String DEEP_OBJECT = "DEEPOBJECT";
public static final String FORM = "FORM";
public static final String SPACE_DELIMITED = "SPACEDELIMITED";
public static final String PIPE_DELIMITED = "PIPEDELIMITED";
public static final String ENCODING = "Encoding";
public static final String ENCODING_STYLE = "EncodingStyle";
public static final String STYLE = "style";
public static final String EXPLODE = "explode";
//OpenAPI Ballerina extensions
public static final String X_BALLERINA_INIT_DESCRIPTION = "x-ballerina-init-description";
public static final String X_BALLERINA_DISPLAY = "x-ballerina-display";
public static final String X_BALLERINA_DEPRECATED_REASON = "x-ballerina-deprecated-reason";
//Service related
public static final String HOST = "host";
public static final String NEW = "new";
public static final String RESOURCE = "resource";
public static final String QUERY = "query";
public static final String HTTP_RESPONSE = "http:Response";
public static final String DEFAULT = "default";
/**
* Util for select http key words with http codes.
* @param code http code.
* @return Http identification word.
*/
public static final Map<String, String> HTTP_CODES_DES;
static {
Map<String, String> aMap = new HashMap<>();
aMap.put("100", "Continue");
aMap.put("101", "SwitchingProtocols");
aMap.put("200", "Ok");
aMap.put("201", "Created");
aMap.put("202", "Accepted");
aMap.put("203", "NonAuthoritativeInformation");
aMap.put("204", "NoContent");
aMap.put("205", "RestContent");
aMap.put("206", "PartialContent");
aMap.put("300", "MultipleChoices");
aMap.put("301", "MovedPermanently");
aMap.put("302", "Found");
aMap.put("303", "SeeOther");
aMap.put("304", "NotModified");
aMap.put("305", "UseProxy");
aMap.put("308", "TemporaryRedirect");
aMap.put("400", "BadRequest");
aMap.put("401", "Unauthorized");
aMap.put("402", "PaymentRequired");
aMap.put("403", "Forbidden");
aMap.put("404", "NotFound");
aMap.put("405", "MethodNotAllowed");
aMap.put("406", "NotAccepted");
aMap.put("407", "ProxyAuthenticationRequires");
aMap.put("408", "RequestTimeOut");
aMap.put("409", "Conflict");
aMap.put("410", "Gone");
aMap.put("411", "LengthRequired");
aMap.put("412", "PreconditionFailed");
aMap.put("413", "UriTooLong");
aMap.put("414", "UnsupportedMediaType");
aMap.put("415", "RangeNotSatisfied");
aMap.put("416", "ExpectationFailed");
aMap.put("426", "UpgradeRequired");
aMap.put("431", "RequestHeaderFieldsTooLarge");
aMap.put("500", "InternalServerError");
aMap.put("501", "NotImplemented");
aMap.put("502", "BadGateway");
aMap.put("503", "ServiceUnavailable");
aMap.put("504", "GatewayTimeOut");
aMap.put("505", "HttpVersionNotSupported");
HTTP_CODES_DES = Collections.unmodifiableMap(aMap);
}
public static final String HTTP_200 = "200";
public static final String INTEGER = "integer";
public static final String BOOLEAN = "boolean";
public static final String NUMBER = "number";
public static final Integer MAX_ARRAY_LENGTH = 2147483637;
public static final String NILLABLE = "?";
public static final String BAL_EXTENSION = ".bal";
public static final String JSON_EXTENSION = ".json";
public static final String YAML_EXTENSION = ".yaml";
public static final String YML_EXTENSION = ".yml";
}
|
package com.portalmedia.embarc.gui.model;
import java.util.HashMap;
import java.util.List;
import com.portalmedia.embarc.parser.ColumnDef;
import com.portalmedia.embarc.validation.IValidationRule;
import com.portalmedia.embarc.validation.ValidationRuleSetEnum;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Wrapper for a DPXColumn and necessary methods for getting and display
* information in table.
*
* @author PortalMedia
* @since 2019-05-01
**/
public class DPXMetadataColumnViewModel {
private final IntegerProperty length;
private final StringProperty sectionDisplayName;
private Boolean hasSubsection;
private ColumnDef column;
private HashMap<ValidationRuleSetEnum, List<IValidationRule>> validationRules;
public DPXMetadataColumnViewModel() {
this.length = new SimpleIntegerProperty();
this.sectionDisplayName = new SimpleStringProperty();
this.setHasSubsection(false);
}
public ColumnDef getColumn() {
return column;
}
public final String getDisplayName() {
return column.getDisplayName();
}
public Boolean getHasSubsection() {
return hasSubsection;
}
public final Integer getLength() {
return this.lengthProperty().get();
}
public final String getSectionDisplayName() {
return column.getSectionDisplayName();
}
public String getSubsectionName() {
return column.getSubsection().getDisplayName();
}
public boolean isEditable() {
return column.getEditable();
}
public boolean isValid(ValidationRuleSetEnum ruleType, String value) {
final List<IValidationRule> rules = validationRules.get(ruleType);
if (rules != null) {
for (final IValidationRule rule : rules) {
if (!rule.isValid(value)) {
return false;
}
}
}
return true;
}
public final IntegerProperty lengthProperty() {
return this.length;
}
public final StringProperty sectionDisplayNameProperty() {
return this.sectionDisplayName;
}
public void setColumn(ColumnDef column) {
this.column = column;
}
public void setHasSubsection(Boolean hasSubsection) {
this.hasSubsection = hasSubsection;
}
public final void setLength(final Integer length) {
this.lengthProperty().set(length);
}
public void setValidationRules(HashMap<ValidationRuleSetEnum, List<IValidationRule>> validationRules) {
this.validationRules = validationRules;
}
}
|
package com.hsuforum.easjavatemplate.web.jsf.converter;
import java.util.Calendar;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import com.hsuforum.common.web.util.DateUtils;
import com.hsuforum.common.web.util.StringUtils;
/**
* Taiwan date converter。
* @author Marvin
*
*/
@FacesConverter("taiwanDateConverter")
public class TaiwanDateConvert implements Converter {
/**
* @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
*/
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Calendar c = null;
boolean flag = false;
try {
if (StringUtils.isNotBlank(value)) {
c = DateUtils.getCalendarByTaiwanStr(value);
flag = true;
}
if (c == null && flag) {
throw new ConverterException();
}
} catch (Exception e) {
throw e;
}
return c;
}
/**
* @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
*/
public String getAsString(FacesContext context, UIComponent component, Object value) {
Calendar c = null;
int len = 7;
try {
String length = (String) component.getAttributes().get("length");
if (length != null) {
len = Integer.parseInt(length);
}
} catch (Exception e) {
throw e;
}
try {
if (value == null) {
return "";
}
c = (Calendar) value;
} catch (Exception e) {
throw e;
}
return StringUtils.substring(StringUtils.leftPad(DateUtils.getTaiwanDateStr(c.getTime(), "", false), 7, "0"), 0,
len);
}
}
|
/**
* 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.apereo.portal.persondir.support;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.security.IPerson;
import org.apereo.portal.security.IPersonManager;
import org.apereo.portal.url.IPortalRequestUtils;
import org.jasig.services.persondir.support.ICurrentUserProvider;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Provides the username of the current portal user
*
* @author Eric Dalquist
* @version $Revision$
*/
public class PersonManagerCurrentUserProvider implements ICurrentUserProvider {
protected final Log logger = LogFactory.getLog(this.getClass());
private IPersonManager personManager;
private IPortalRequestUtils portalRequestUtils;
public IPersonManager getPersonManager() {
return personManager;
}
/**
* @param personManager the personManager to set
*/
@Autowired
public void setPersonManager(IPersonManager personManager) {
this.personManager = personManager;
}
public IPortalRequestUtils getPortalRequestUtils() {
return portalRequestUtils;
}
/**
* @param portalRequestUtils the portalRequestUtils to set
*/
@Autowired
public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) {
this.portalRequestUtils = portalRequestUtils;
}
/* (non-Javadoc)
* @see org.jasig.services.persondir.support.ICurrentUserProvider#getCurrentUserName()
*/
public String getCurrentUserName() {
final HttpServletRequest portalRequest;
try {
portalRequest = this.portalRequestUtils.getCurrentPortalRequest();
}
catch (IllegalStateException ise) {
this.logger.warn("No current portal request available, cannot determine current user name.");
return null;
}
final IPerson person = this.personManager.getPerson(portalRequest);
if (person == null) {
this.logger.warn("IPersonManager returned no IPerson for request, cannot determine current user name. " + portalRequest);
return null;
}
return person.getUserName();
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.compat;
public final class R {
public static final class attr {
public static final int font = 0x7f020071;
public static final int fontProviderAuthority = 0x7f020073;
public static final int fontProviderCerts = 0x7f020074;
public static final int fontProviderFetchStrategy = 0x7f020075;
public static final int fontProviderFetchTimeout = 0x7f020076;
public static final int fontProviderPackage = 0x7f020077;
public static final int fontProviderQuery = 0x7f020078;
public static final int fontStyle = 0x7f020079;
public static final int fontWeight = 0x7f02007a;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f030000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f04003e;
public static final int notification_icon_bg_color = 0x7f04003f;
public static final int ripple_material_light = 0x7f040049;
public static final int secondary_text_default_material_light = 0x7f04004b;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f05004d;
public static final int compat_button_inset_vertical_material = 0x7f05004e;
public static final int compat_button_padding_horizontal_material = 0x7f05004f;
public static final int compat_button_padding_vertical_material = 0x7f050050;
public static final int compat_control_corner_material = 0x7f050051;
public static final int notification_action_icon_size = 0x7f05005b;
public static final int notification_action_text_size = 0x7f05005c;
public static final int notification_big_circle_margin = 0x7f05005d;
public static final int notification_content_margin_start = 0x7f05005e;
public static final int notification_large_icon_height = 0x7f05005f;
public static final int notification_large_icon_width = 0x7f050060;
public static final int notification_main_column_padding_top = 0x7f050061;
public static final int notification_media_narrow_margin = 0x7f050062;
public static final int notification_right_icon_size = 0x7f050063;
public static final int notification_right_side_padding_top = 0x7f050064;
public static final int notification_small_icon_background_padding = 0x7f050065;
public static final int notification_small_icon_size_as_large = 0x7f050066;
public static final int notification_subtext_size = 0x7f050067;
public static final int notification_top_pad = 0x7f050068;
public static final int notification_top_pad_large_text = 0x7f050069;
}
public static final class drawable {
public static final int notification_action_background = 0x7f060053;
public static final int notification_bg = 0x7f060054;
public static final int notification_bg_low = 0x7f060055;
public static final int notification_bg_low_normal = 0x7f060056;
public static final int notification_bg_low_pressed = 0x7f060057;
public static final int notification_bg_normal = 0x7f060058;
public static final int notification_bg_normal_pressed = 0x7f060059;
public static final int notification_icon_background = 0x7f06005a;
public static final int notification_template_icon_bg = 0x7f06005b;
public static final int notification_template_icon_low_bg = 0x7f06005c;
public static final int notification_tile_bg = 0x7f06005d;
public static final int notify_panel_notification_icon_bg = 0x7f06005e;
}
public static final class id {
public static final int action_container = 0x7f07000d;
public static final int action_divider = 0x7f07000f;
public static final int action_image = 0x7f070010;
public static final int action_text = 0x7f070016;
public static final int actions = 0x7f070017;
public static final int async = 0x7f07001d;
public static final int blocking = 0x7f07001f;
public static final int chronometer = 0x7f070026;
public static final int forever = 0x7f070037;
public static final int icon = 0x7f07003a;
public static final int icon_group = 0x7f07003b;
public static final int info = 0x7f07003e;
public static final int italic = 0x7f07003f;
public static final int line1 = 0x7f070041;
public static final int line3 = 0x7f070042;
public static final int normal = 0x7f07004a;
public static final int notification_background = 0x7f07004b;
public static final int notification_main_column = 0x7f07004c;
public static final int notification_main_column_container = 0x7f07004d;
public static final int right_icon = 0x7f07005b;
public static final int right_side = 0x7f07005c;
public static final int tag_transition_group = 0x7f070079;
public static final int text = 0x7f07007a;
public static final int text2 = 0x7f07007b;
public static final int time = 0x7f07007e;
public static final int title = 0x7f07007f;
}
public static final class integer {
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
public static final int notification_action = 0x7f09001c;
public static final int notification_action_tombstone = 0x7f09001d;
public static final int notification_template_custom_big = 0x7f09001e;
public static final int notification_template_icon_group = 0x7f09001f;
public static final int notification_template_part_chronometer = 0x7f090020;
public static final int notification_template_part_time = 0x7f090021;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0b0023;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0c00e7;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00e8;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00e9;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00ea;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00eb;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0c0153;
public static final int Widget_Compat_NotificationActionText = 0x7f0c0154;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f020073, 0x7f020074, 0x7f020075, 0x7f020076, 0x7f020077, 0x7f020078 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f020071, 0x7f020079, 0x7f02007a };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/bigtable/v2/bigtable.proto
package com.google.bigtable.v2;
public interface CheckAndMutateRowRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.bigtable.v2.CheckAndMutateRowRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The unique name of the table to which the conditional mutation should be
* applied.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* </pre>
*
* <code>string table_name = 1;</code>
*/
java.lang.String getTableName();
/**
* <pre>
* The unique name of the table to which the conditional mutation should be
* applied.
* Values are of the form
* `projects/<project>/instances/<instance>/tables/<table>`.
* </pre>
*
* <code>string table_name = 1;</code>
*/
com.google.protobuf.ByteString
getTableNameBytes();
/**
* <pre>
* This value specifies routing for replication. If not specified, the
* "default" application profile will be used.
* </pre>
*
* <code>string app_profile_id = 7;</code>
*/
java.lang.String getAppProfileId();
/**
* <pre>
* This value specifies routing for replication. If not specified, the
* "default" application profile will be used.
* </pre>
*
* <code>string app_profile_id = 7;</code>
*/
com.google.protobuf.ByteString
getAppProfileIdBytes();
/**
* <pre>
* The key of the row to which the conditional mutation should be applied.
* </pre>
*
* <code>bytes row_key = 2;</code>
*/
com.google.protobuf.ByteString getRowKey();
/**
* <pre>
* The filter to be applied to the contents of the specified row. Depending
* on whether or not any results are yielded, either `true_mutations` or
* `false_mutations` will be executed. If unset, checks that the row contains
* any values at all.
* </pre>
*
* <code>.google.bigtable.v2.RowFilter predicate_filter = 6;</code>
*/
boolean hasPredicateFilter();
/**
* <pre>
* The filter to be applied to the contents of the specified row. Depending
* on whether or not any results are yielded, either `true_mutations` or
* `false_mutations` will be executed. If unset, checks that the row contains
* any values at all.
* </pre>
*
* <code>.google.bigtable.v2.RowFilter predicate_filter = 6;</code>
*/
com.google.bigtable.v2.RowFilter getPredicateFilter();
/**
* <pre>
* The filter to be applied to the contents of the specified row. Depending
* on whether or not any results are yielded, either `true_mutations` or
* `false_mutations` will be executed. If unset, checks that the row contains
* any values at all.
* </pre>
*
* <code>.google.bigtable.v2.RowFilter predicate_filter = 6;</code>
*/
com.google.bigtable.v2.RowFilterOrBuilder getPredicateFilterOrBuilder();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* yields at least one cell when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `false_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation true_mutations = 4;</code>
*/
java.util.List<com.google.bigtable.v2.Mutation>
getTrueMutationsList();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* yields at least one cell when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `false_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation true_mutations = 4;</code>
*/
com.google.bigtable.v2.Mutation getTrueMutations(int index);
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* yields at least one cell when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `false_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation true_mutations = 4;</code>
*/
int getTrueMutationsCount();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* yields at least one cell when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `false_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation true_mutations = 4;</code>
*/
java.util.List<? extends com.google.bigtable.v2.MutationOrBuilder>
getTrueMutationsOrBuilderList();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* yields at least one cell when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `false_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation true_mutations = 4;</code>
*/
com.google.bigtable.v2.MutationOrBuilder getTrueMutationsOrBuilder(
int index);
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* does not yield any cells when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `true_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation false_mutations = 5;</code>
*/
java.util.List<com.google.bigtable.v2.Mutation>
getFalseMutationsList();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* does not yield any cells when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `true_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation false_mutations = 5;</code>
*/
com.google.bigtable.v2.Mutation getFalseMutations(int index);
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* does not yield any cells when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `true_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation false_mutations = 5;</code>
*/
int getFalseMutationsCount();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* does not yield any cells when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `true_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation false_mutations = 5;</code>
*/
java.util.List<? extends com.google.bigtable.v2.MutationOrBuilder>
getFalseMutationsOrBuilderList();
/**
* <pre>
* Changes to be atomically applied to the specified row if `predicate_filter`
* does not yield any cells when applied to `row_key`. Entries are applied in
* order, meaning that earlier mutations can be masked by later ones.
* Must contain at least one entry if `true_mutations` is empty, and at most
* 100000.
* </pre>
*
* <code>repeated .google.bigtable.v2.Mutation false_mutations = 5;</code>
*/
com.google.bigtable.v2.MutationOrBuilder getFalseMutationsOrBuilder(
int index);
}
|
/**
* Exception hierarchy enabling sophisticated error handling independent of the data access approach
* in use. For example, when DAOs and data access frameworks use the exceptions in this package (and
* custom subclasses), calling code can detect and handle common problems such as deadlocks without
* being tied to a particular data access strategy, such as JDBC.
*
* <p>All these exceptions are unchecked, meaning that calling code can leave them uncaught and
* treat all data access exceptions as fatal.
*
* <p>The classes in this package are discussed in Chapter 9 of <a
* href="https://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design
* and Development</a> by Rod Johnson (Wrox, 2002).
*/
@NonNullApi
@NonNullFields
package org.springframework.dao;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.oi;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import frc.robot.Constants;
import frc.robot.RobotContainer;
import frc.robot.commands.ControlArmCommand;
import frc.robot.commands.IntakeCommand;
import frc.robot.commands.StopIntakeCommand;
/**
* CoDriver OI Controls
*/
public class CoDriverOI extends OI {
public CoDriverOI(int channel, RobotContainer robotContainer) {
super(channel);
rightBumper = new JoystickButton(joystick, Constants.RIGHT_BUMPER);
rightBumper.whileHeld(new IntakeCommand(robotContainer, Constants.INTAKE_OUT));
rightBumper.whenReleased(new StopIntakeCommand(robotContainer));
leftBumper = new JoystickButton(joystick, Constants.LEFT_BUMPER);
leftBumper.whileHeld(new IntakeCommand(robotContainer, Constants.INTAKE_IN));
leftBumper.whenReleased(new StopIntakeCommand(robotContainer));
// ARM Control Up
a = new JoystickButton(joystick, Constants.A);
a.whenPressed(new ControlArmCommand(robotContainer, Constants.ARM_UP));
// ARM Control down
b = new JoystickButton(joystick, Constants.B);
b.whenPressed(new ControlArmCommand(robotContainer, Constants.ARM_DOWN));
leftJoystick = new JoystickButton(joystick, Constants.LEFT_JOYSTICK);
rightJoystick = new JoystickButton(joystick, Constants.RIGHT_JOYSTICK);
}
}
|
package net.rim99.demo.account.support.repository;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
public class HikariCPDataSourceFactory extends UnpooledDataSourceFactory {
public HikariCPDataSourceFactory() {
String filepath = this.getClass()
.getClassLoader()
.getResource("config/hikari.properties")
.getPath();
HikariConfig config = new HikariConfig(filepath);
HikariDataSource dataSource = new HikariDataSource(config);
this.dataSource = dataSource;
}
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.goyazbarber;
import android.content.Context;
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.android.utils.FlipperUtils;
import com.facebook.flipper.core.FlipperClient;
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;
public class ReactNativeFlipper {
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
client.addPlugin(new ReactFlipperPlugin());
client.addPlugin(new DatabasesFlipperPlugin(context));
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
client.addPlugin(CrashReporterPlugin.getInstance());
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
// Hence we run if after all native modules have been initialized
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
reactInstanceManager.addReactInstanceEventListener(
new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext reactContext) {
reactInstanceManager.removeReactInstanceEventListener(this);
reactContext.runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
client.addPlugin(new FrescoFlipperPlugin());
}
});
}
});
} else {
client.addPlugin(new FrescoFlipperPlugin());
}
}
}
}
|
package org.oza.ego.portal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.oza.ego.base.utils.HttpClientUtils;
import org.oza.ego.portal.service.ContentService;
import org.oza.ego.portal.service.impl.ContentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:spring-mvc.xml")
public class HttpClientUtilsTest {
@Autowired
private ContentService contentService;
@Test
public void getTest() {
String url = "http://localhost:8081/rest/item/all";
Map<String, String> params = new HashMap<>();
params.put("callback", "list");
String result = HttpClientUtils.doGet(url, params);
System.out.println(result);
}
@Test
public void postTest() {
String url = "http://localhost:8081/rest/item/all";
Map<String, String> params = new HashMap<>();
params.put("callback", "list");
String result = HttpClientUtils.doPost(url, params);
System.out.println(result);
}
@Test
public void serviceTest() {
System.out.println(contentService.getAdItemList());
}
}
|
package js.lang.external.highcharts;
import com.github.fluorumlabs.disconnect.core.annotations.Import;
import com.github.fluorumlabs.disconnect.core.annotations.NpmPackage;
import java.lang.String;
import javax.annotation.Nullable;
import js.lang.Any;
import org.teavm.jso.JSProperty;
/**
* (Highcharts, Highstock) Options for the series data sorting.
*
*/
@NpmPackage(
name = "highcharts",
version = "^8.1.2"
)
@Import(
module = "highcharts/es-modules/masters/highcharts.src.js"
)
public interface PlotErrorbarDataSortingOptions extends Any {
/**
* (Highcharts, Highstock) Enable or disable data sorting for the series.
* Use xAxis.reversed to change the sorting order.
*
*/
@JSProperty("enabled")
boolean getEnabled();
/**
* (Highcharts, Highstock) Enable or disable data sorting for the series.
* Use xAxis.reversed to change the sorting order.
*
*/
@JSProperty("enabled")
void setEnabled(boolean value);
/**
* (Highcharts, Highstock) Whether to allow matching points by name in an
* update. If this option is disabled, points will be matched by order.
*
*/
@JSProperty("matchByName")
boolean getMatchByName();
/**
* (Highcharts, Highstock) Whether to allow matching points by name in an
* update. If this option is disabled, points will be matched by order.
*
*/
@JSProperty("matchByName")
void setMatchByName(boolean value);
/**
* (Highcharts, Highstock) Determines what data value should be used to sort
* by.
*
*/
@JSProperty("sortKey")
@Nullable
String getSortKey();
/**
* (Highcharts, Highstock) Determines what data value should be used to sort
* by.
*
*/
@JSProperty("sortKey")
void setSortKey(@Nullable String value);
static Builder builder() {
return new Builder();
}
final class Builder {
private final PlotErrorbarDataSortingOptions object = Any.empty();
private Builder() {
}
public PlotErrorbarDataSortingOptions build() {
return object;
}
/**
* (Highcharts, Highstock) Enable or disable data sorting for the series.
* Use xAxis.reversed to change the sorting order.
*
*/
public Builder enabled(boolean value) {
object.setEnabled(value);
return this;
}
/**
* (Highcharts, Highstock) Whether to allow matching points by name in an
* update. If this option is disabled, points will be matched by order.
*
*/
public Builder matchByName(boolean value) {
object.setMatchByName(value);
return this;
}
/**
* (Highcharts, Highstock) Determines what data value should be used to sort
* by.
*
*/
public Builder sortKey(@Nullable String value) {
object.setSortKey(value);
return this;
}
}
}
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.model;
import io.fabric8.kubernetes.api.model.Affinity;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecurityContext;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.Toleration;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentStrategy;
import io.fabric8.kubernetes.api.model.apps.DeploymentStrategyBuilder;
import io.strimzi.api.kafka.model.ContainerEnvVar;
import io.strimzi.api.kafka.model.Kafka;
import io.strimzi.api.kafka.model.KafkaClusterSpec;
import io.strimzi.api.kafka.model.KafkaExporterResources;
import io.strimzi.api.kafka.model.KafkaExporterSpec;
import io.strimzi.api.kafka.model.Probe;
import io.strimzi.api.kafka.model.ProbeBuilder;
import io.strimzi.api.kafka.model.template.KafkaExporterTemplate;
import io.strimzi.operator.cluster.ClusterOperatorConfig;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class KafkaExporter extends AbstractModel {
protected static final String APPLICATION_NAME = "kafka-exporter";
// Configuration for mounting certificates
protected static final String KAFKA_EXPORTER_CERTS_VOLUME_NAME = "kafka-exporter-certs";
protected static final String KAFKA_EXPORTER_CERTS_VOLUME_MOUNT = "/etc/kafka-exporter/kafka-exporter-certs/";
protected static final String CLUSTER_CA_CERTS_VOLUME_NAME = "cluster-ca-certs";
protected static final String CLUSTER_CA_CERTS_VOLUME_MOUNT = "/etc/kafka-exporter/cluster-ca-certs/";
// Configuration defaults
private static final int DEFAULT_HEALTHCHECK_DELAY = 15;
private static final int DEFAULT_HEALTHCHECK_TIMEOUT = 5;
public static final Probe READINESS_PROBE_OPTIONS = new ProbeBuilder().withTimeoutSeconds(DEFAULT_HEALTHCHECK_TIMEOUT).withInitialDelaySeconds(DEFAULT_HEALTHCHECK_DELAY).build();
protected static final String ENV_VAR_KAFKA_EXPORTER_LOGGING = "KAFKA_EXPORTER_LOGGING";
protected static final String ENV_VAR_KAFKA_EXPORTER_KAFKA_VERSION = "KAFKA_EXPORTER_KAFKA_VERSION";
protected static final String ENV_VAR_KAFKA_EXPORTER_GROUP_REGEX = "KAFKA_EXPORTER_GROUP_REGEX";
protected static final String ENV_VAR_KAFKA_EXPORTER_TOPIC_REGEX = "KAFKA_EXPORTER_TOPIC_REGEX";
protected static final String ENV_VAR_KAFKA_EXPORTER_KAFKA_SERVER = "KAFKA_EXPORTER_KAFKA_SERVER";
protected static final String ENV_VAR_KAFKA_EXPORTER_ENABLE_SARAMA = "KAFKA_EXPORTER_ENABLE_SARAMA";
protected String groupRegex = ".*";
protected String topicRegex = ".*";
protected boolean saramaLoggingEnabled;
protected String logging;
protected String version;
private boolean isDeployed;
protected List<ContainerEnvVar> templateContainerEnvVars;
protected SecurityContext templateContainerSecurityContext;
/**
* Constructor
*
* @param resource Kubernetes/OpenShift resource with metadata containing the namespace and cluster name
*/
protected KafkaExporter(HasMetadata resource) {
super(resource, APPLICATION_NAME);
this.name = KafkaExporterResources.deploymentName(cluster);
this.serviceName = KafkaExporterResources.serviceName(cluster);
this.replicas = 1;
this.readinessPath = "/metrics";
this.readinessProbeOptions = READINESS_PROBE_OPTIONS;
this.livenessPath = "/metrics";
this.livenessProbeOptions = READINESS_PROBE_OPTIONS;
this.saramaLoggingEnabled = false;
this.mountPath = "/var/lib/kafka";
// Kafka Exporter is all about metrics - they are always enabled
this.isMetricsEnabled = true;
}
public static KafkaExporter fromCrd(Kafka kafkaAssembly, KafkaVersion.Lookup versions) {
KafkaExporter kafkaExporter = new KafkaExporter(kafkaAssembly);
KafkaExporterSpec spec = kafkaAssembly.getSpec().getKafkaExporter();
if (spec != null) {
kafkaExporter.isDeployed = true;
kafkaExporter.setResources(spec.getResources());
if (spec.getReadinessProbe() != null) {
kafkaExporter.setReadinessProbe(spec.getReadinessProbe());
}
if (spec.getLivenessProbe() != null) {
kafkaExporter.setLivenessProbe(spec.getLivenessProbe());
}
kafkaExporter.setGroupRegex(spec.getGroupRegex());
kafkaExporter.setTopicRegex(spec.getTopicRegex());
String image = spec.getImage();
if (image == null) {
KafkaClusterSpec kafkaClusterSpec = kafkaAssembly.getSpec().getKafka();
image = System.getenv().getOrDefault(ClusterOperatorConfig.STRIMZI_DEFAULT_KAFKA_EXPORTER_IMAGE, versions.kafkaImage(kafkaClusterSpec.getImage(), versions.defaultVersion().version()));
}
kafkaExporter.setImage(image);
kafkaExporter.setLogging(spec.getLogging());
kafkaExporter.setSaramaLoggingEnabled(spec.getEnableSaramaLogging());
if (spec.getTemplate() != null) {
KafkaExporterTemplate template = spec.getTemplate();
if (template.getDeployment() != null && template.getDeployment().getMetadata() != null) {
kafkaExporter.templateDeploymentLabels = template.getDeployment().getMetadata().getLabels();
kafkaExporter.templateDeploymentAnnotations = template.getDeployment().getMetadata().getAnnotations();
}
if (template.getService() != null && template.getService().getMetadata() != null) {
kafkaExporter.templateServiceLabels = template.getService().getMetadata().getLabels();
kafkaExporter.templateServiceAnnotations = template.getService().getMetadata().getAnnotations();
}
if (template.getContainer() != null && template.getContainer().getEnv() != null) {
kafkaExporter.templateContainerEnvVars = template.getContainer().getEnv();
}
if (template.getContainer() != null && template.getContainer().getSecurityContext() != null) {
kafkaExporter.templateContainerSecurityContext = template.getContainer().getSecurityContext();
}
ModelUtils.parsePodTemplate(kafkaExporter, template.getPod());
}
kafkaExporter.setUserAffinity(affinity(spec));
kafkaExporter.setTolerations(tolerations(spec));
kafkaExporter.setVersion(versions.version(kafkaAssembly.getSpec().getKafka().getVersion()).version());
kafkaExporter.setOwnerReference(kafkaAssembly);
} else {
kafkaExporter.isDeployed = false;
}
return kafkaExporter;
}
protected void setSaramaLoggingEnabled(boolean saramaLoggingEnabled) {
this.saramaLoggingEnabled = saramaLoggingEnabled;
}
static List<Toleration> tolerations(KafkaExporterSpec spec) {
if (spec.getTemplate() != null
&& spec.getTemplate().getPod() != null
&& spec.getTemplate().getPod().getTolerations() != null) {
return spec.getTemplate().getPod().getTolerations();
} else {
return null;
}
}
static Affinity affinity(KafkaExporterSpec spec) {
if (spec.getTemplate() != null
&& spec.getTemplate().getPod() != null
&& spec.getTemplate().getPod().getAffinity() != null) {
return spec.getTemplate().getPod().getAffinity();
} else {
return null;
}
}
public Service generateService() {
if (!isDeployed()) {
return null;
}
List<ServicePort> ports = new ArrayList<>(1);
ports.add(createServicePort(METRICS_PORT_NAME, METRICS_PORT, METRICS_PORT, "TCP"));
return createService("ClusterIP", ports, mergeLabelsOrAnnotations(getPrometheusAnnotations(), templateServiceAnnotations));
}
protected List<ContainerPort> getContainerPortList() {
List<ContainerPort> portList = new ArrayList<>(1);
portList.add(createContainerPort(METRICS_PORT_NAME, METRICS_PORT, "TCP"));
return portList;
}
public Deployment generateDeployment(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets) {
if (!isDeployed()) {
return null;
}
DeploymentStrategy updateStrategy = new DeploymentStrategyBuilder()
.withType("RollingUpdate")
.build();
return createDeployment(
updateStrategy,
Collections.emptyMap(),
Collections.emptyMap(),
getMergedAffinity(),
getInitContainers(imagePullPolicy),
getContainers(imagePullPolicy),
getVolumes(isOpenShift),
imagePullSecrets
);
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
List<Container> containers = new ArrayList<>();
Container container = new ContainerBuilder()
.withName(name)
.withImage(getImage())
.withCommand("/opt/kafka-exporter/kafka_exporter_run.sh")
.withEnv(getEnvVars())
.withPorts(getContainerPortList())
.withLivenessProbe(ModelUtils.createHttpProbe(livenessPath, METRICS_PORT_NAME, livenessProbeOptions))
.withReadinessProbe(ModelUtils.createHttpProbe(readinessPath, METRICS_PORT_NAME, readinessProbeOptions))
.withResources(getResources())
.withVolumeMounts(VolumeUtils.createVolumeMount(KAFKA_EXPORTER_CERTS_VOLUME_NAME, KAFKA_EXPORTER_CERTS_VOLUME_MOUNT),
VolumeUtils.createVolumeMount(CLUSTER_CA_CERTS_VOLUME_NAME, CLUSTER_CA_CERTS_VOLUME_MOUNT))
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateContainerSecurityContext)
.build();
containers.add(container);
return containers;
}
@Override
protected List<EnvVar> getEnvVars() {
List<EnvVar> varList = new ArrayList<>();
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_LOGGING, logging));
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_KAFKA_VERSION, version));
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_GROUP_REGEX, groupRegex));
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_TOPIC_REGEX, topicRegex));
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_KAFKA_SERVER, KafkaCluster.serviceName(cluster) + ":" + KafkaCluster.REPLICATION_PORT));
varList.add(buildEnvVar(ENV_VAR_KAFKA_EXPORTER_ENABLE_SARAMA, String.valueOf(saramaLoggingEnabled)));
addContainerEnvsToExistingEnvs(varList, templateContainerEnvVars);
return varList;
}
private List<Volume> getVolumes(boolean isOpenShift) {
List<Volume> volumeList = new ArrayList<>();
volumeList.add(VolumeUtils.createSecretVolume(KAFKA_EXPORTER_CERTS_VOLUME_NAME, KafkaExporter.secretName(cluster), isOpenShift));
volumeList.add(VolumeUtils.createSecretVolume(CLUSTER_CA_CERTS_VOLUME_NAME, AbstractModel.clusterCaCertSecretName(cluster), isOpenShift));
return volumeList;
}
/**
* Generates the name of the Kafka Exporter deployment
*
* @param kafkaCluster Name of the Kafka Custom Resource
* @return Name of the Kafka Exporter deployment
*/
public static String kafkaExporterName(String kafkaCluster) {
return KafkaExporterResources.deploymentName(kafkaCluster);
}
/**
* Generates the name of the Kafka Exporter secret with certificates for connecting to Kafka brokers
*
* @param kafkaCluster Name of the Kafka Custom Resource
* @return Name of the Kafka Exporter secret
*/
public static String secretName(String kafkaCluster) {
return KafkaExporterResources.secretName(kafkaCluster);
}
/**
* Get the name of the Kafka Exporter service account given the name of the {@code kafkaCluster}.
* @param kafkaCluster The cluster name
* @return The name of the KE service account.
*/
public static String containerServiceAccountName(String kafkaCluster) {
return kafkaExporterName(kafkaCluster);
}
@Override
protected String getDefaultLogConfigFileName() {
return null;
}
private void setGroupRegex(String groupRegex) {
this.groupRegex = groupRegex;
}
private void setTopicRegex(String topicRegex) {
this.topicRegex = topicRegex;
}
@Override
protected String getServiceAccountName() {
return KafkaExporterResources.serviceAccountName(cluster);
}
private void setLogging(String logging) {
this.logging = logging;
}
private void setVersion(String version) {
this.version = version;
}
/**
* Returns whether the Kafka Exporter is enabled or not
*
* @return True if Kafka exporter is enabled. False otherwise.
*/
private boolean isDeployed() {
return isDeployed;
}
/**
* Generate the Secret containing the Kafka Exporter certificate signed by the cluster CA certificate used for TLS based
* internal communication with Kafka and Zookeeper.
* It also contains the related Kafka Exporter private key.
*
* @param clusterCa The cluster CA.
* @param isMaintenanceTimeWindowsSatisfied Indicates whether we are in the maintenance window or not.
* This is used for certificate renewals
* @return The generated Secret.
*/
public Secret generateSecret(ClusterCa clusterCa, boolean isMaintenanceTimeWindowsSatisfied) {
if (!isDeployed()) {
return null;
}
Secret secret = clusterCa.kafkaExporterSecret();
return ModelUtils.buildSecret(clusterCa, secret, namespace, KafkaExporter.secretName(cluster), name,
"kafka-exporter", labels, createOwnerReference(), isMaintenanceTimeWindowsSatisfied);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bohutskyi.logloader.ui;
/**
*
* @author Serhii_Bohutskyi
*/
public class LoaderFrame extends javax.swing.JFrame {
/**
* Creates new form LoaderFrame
*/
public LoaderFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
protected void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
host = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
port = new javax.swing.JTextField();
username = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
password = new javax.swing.JPasswordField();
jLabel5 = new javax.swing.JLabel();
logPath = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
resultLogPath = new javax.swing.JTextField();
useTempLogFile = new javax.swing.JCheckBox();
jLabel7 = new javax.swing.JLabel();
localDirPath = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
startButton = new javax.swing.JButton();
stopButton = new javax.swing.JButton();
status = new javax.swing.JLabel();
openButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("LogLoader"));
jPanel1.setToolTipText("LogLoader");
jLabel1.setText("Host:");
jLabel2.setText("Username:");
host.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
hostActionPerformed(evt);
}
});
jLabel3.setText("Port:");
port.setText("22");
port.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
portActionPerformed(evt);
}
});
jLabel4.setText("Password:");
password.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordActionPerformed(evt);
}
});
jLabel5.setText("Server log:");
jLabel6.setText("Server tail file:");
resultLogPath.setEnabled(false);
useTempLogFile.setSelected(true);
useTempLogFile.setText("use temporary file for result log");
useTempLogFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
useTempLogFileActionPerformed(evt);
}
});
jLabel7.setText("Local directory:");
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
stopButton.setText("Stop");
stopButton.setEnabled(false);
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
status.setText(" ");
openButton.setText("Open");
openButton.setEnabled(false);
openButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(stopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(openButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(115, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel5)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(useTempLogFile)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(port))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(logPath)
.addComponent(resultLogPath)
.addComponent(localDirPath)))
.addComponent(status, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(logPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(resultLogPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(useTempLogFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(localDirPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(status)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(stopButton)
.addComponent(openButton)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1))
);
pack();
}// </editor-fold>//GEN-END:initComponents
protected void hostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hostActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_hostActionPerformed
protected void portActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_portActionPerformed
protected void passwordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_passwordActionPerformed
protected void useTempLogFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useTempLogFileActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_useTempLogFileActionPerformed
protected void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_startButtonActionPerformed
protected void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_stopButtonActionPerformed
protected void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_openButtonActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
protected javax.swing.JTextField host;
protected javax.swing.JLabel jLabel1;
protected javax.swing.JLabel jLabel2;
protected javax.swing.JLabel jLabel3;
protected javax.swing.JLabel jLabel4;
protected javax.swing.JLabel jLabel5;
protected javax.swing.JLabel jLabel6;
protected javax.swing.JLabel jLabel7;
protected javax.swing.JPanel jPanel1;
protected javax.swing.JProgressBar jProgressBar1;
protected javax.swing.JTextField localDirPath;
protected javax.swing.JTextField logPath;
protected javax.swing.JButton openButton;
protected javax.swing.JPasswordField password;
protected javax.swing.JTextField port;
protected javax.swing.JTextField resultLogPath;
protected javax.swing.JButton startButton;
protected javax.swing.JLabel status;
protected javax.swing.JButton stopButton;
protected javax.swing.JCheckBox useTempLogFile;
protected javax.swing.JTextField username;
// End of variables declaration//GEN-END:variables
}
|
package game.geography.geography;
public class Map implements LandChangeListener {
private final LandRepository landRepository;
public Map(LandRepository landRepository) {
// in first version we have two lands
// later, add its own class of LandGenerator or Seed
this.landRepository = landRepository;
this.landRepository.save(new Land(new LandName("Stormland"), this));
this.landRepository.save(new Land(new LandName("Rainland"), this));
}
public Land lookup(LandName landName) {
return landRepository.findById(landName);
}
@Override
public void landHasChanged(Land land) {
landRepository.save(land);
}
}
|
package com.historiasclinicas.log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
public class Log {
public static String path = System.getProperty("user.home");
public static File folder = new File(path+"\\.HistoriasClinicas");
public static void CreaLog(String Operacion) throws IOException {
FileWriter archivo = null;
final Calendar fechaActual = Calendar.getInstance();
final String fecha = fechaActual.get(Calendar.DAY_OF_MONTH) + " " + (fechaActual.get(Calendar.MONTH) + 1) + " "
+ fechaActual.get(Calendar.YEAR);
archivo = new FileWriter(new File(folder+"\\log-HistoCons - " + fecha + ".log"), true);
if (!(new File(folder+"\\log-HistoCons - " + fecha + ".log").exists()))
archivo = new FileWriter(new File(folder+"\\log-HistoCons - " + fecha + ".log"),
false);
else
archivo = new FileWriter(new File(folder+"\\log-HistoCons - " + fecha + ".log"), true);
// Calendar fechaActual = Calendar.getInstance(); //Para poder utilizar
// el paquete calendar
archivo.write((String.valueOf(fechaActual.get(Calendar.DAY_OF_MONTH)) + "/"
+ String.valueOf(fechaActual.get(Calendar.MONTH) + 1) + "/"
+ String.valueOf(fechaActual.get(Calendar.YEAR)) + ";"
+ String.valueOf(fechaActual.get(Calendar.HOUR_OF_DAY)) + ":"
+ String.valueOf(fechaActual.get(Calendar.MINUTE)) + ":"
+ String.valueOf(fechaActual.get(Calendar.SECOND))) + ";" + Operacion + "\r\n");
archivo.close();
}
public static void crearLog(String Operacion) throws IOException {
// Pregunta el archivo existe, caso contrario crea uno con el nombre
// log.txt
if (!folder.exists()) {
folder.mkdirs();
CreaLog(Operacion);
} else
CreaLog(Operacion);
}
}
|
import java.util.*;
/**
* Given two words (start and end), and a dictionary, find all shortest
* transformation sequence(s) from start to end, such that:
*
* Only one letter can be changed at a time
* Each intermediate word must exist in the dictionary
* For example,
*
* Given:
* start = "hit"
* end = "cog"
* dict = ["hot","dot","dog","lot","log"]
* Return
* [
* ["hit","hot","dot","dog","cog"],
* ["hit","hot","lot","log","cog"]
* ]
* Note:
* All words have the same length.
* All words contain only lowercase alphabetic characters.
*
* Tags: Array, Backtracking, BFS, String
*/
class WordLadder2 {
public static void main(String[] args) {
String start = "hit";
String end = "cog";
String[] arr = {"hot","dot","dog","lot","log"};
Set<String> dict = new HashSet<String>(Arrays.asList(arr));
System.out.println(new WordLadder2().findLadders(start, end, dict).toString());
}
/**
* BFS then DFS
*/
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
List<List<String>> res = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>(); // string to the words which only has one diffrent char.
Map<String, Integer> dist = new HashMap<String, Integer>(); // string to the minimum distance to the start
bfs(map, dist, start, end, dict);
dfs(res, new LinkedList<String>(), end, start, dist, map);
return res;
}
/**
* Create a queue, add start to it and put start in dist map
* Initialize map with lists
*/
void bfs(Map<String, List<String>> map, Map<String, Integer> dist,
String start, String end, Set<String> dict) {
Queue<String> q = new LinkedList<String>();
q.offer(start);
dict.add(start); // make sure start and end in dictionary
dict.add(end);
dist.put(start, 0);
for (String s : dict) map.put(s, new ArrayList<String>());
while (!q.isEmpty()) { // never use end.
String word = q.poll();
List<String> expansion = expand(word, dict); // generate all words
for (String next : expansion) {
map.get(next).add(word); //step 1
if (!dist.containsKey(next)) { // not in dist map yet
dist.put(next, dist.get(word) + 1); //step2
q.offer(next);
}
}
}
}
/**
* Generate a list of words the word
* Skip if it's the same character
* If word is in dictionary, add to expansion list
*/
List<String> expand(String word, Set<String> dict) {
List<String> res = new ArrayList<String>();
for (int i = 0; i < word.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
char[] chs = word.toCharArray(); // chs was changed in last loop.
if (ch != chs[i]) {
chs[i] = ch;
String next = new String(chs);
if (dict.contains(next)) res.add(next); // compared to I, next is not removed from dict.
}
}
}
return res;
}
/**
* Add current word to first position
* Add path to result if word is start
*/
void dfs(List<List<String>> res, List<String> path, String word, String start, Map<String, Integer> dist, Map<String, List<String>> map) {
if (word.equals(start)) {
path.add(0, word);
res.add(new ArrayList<String>(path));
path.remove(0);
return; // note to return
}
for (String next : map.get(word)) {
// if next is in word's mapping, next must been added to dist. See line 65 - 67.
if (/*dist.containsKey(next) && */dist.get(word) == dist.get(next) + 1) { // backward, so word = next + 1
path.add(0, word); // add current word
dfs(res, path, next, start, dist, map); // dfs next word
path.remove(0);
}
}
}
}
|
package de.fraunhofer.iais.eis;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import de.fraunhofer.iais.eis.util.*;
/**
* A location identified by geo coordinates.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type")
@JsonSubTypes({
@JsonSubTypes.Type(value = GeoPointImpl.class)
})
public interface GeoPoint extends Location {
// standard methods
@Beta
public GeoPoint deepCopy();
// accessor methods as derived from the IDS Information Model ontology
/**
* Latitude of a GeoPoint (decimal degrees).
*
* More information under https://w3id.org/idsa/core/latitude
*
* @return Returns the float for the property _latitude.
*/
@NotNull
float getLatitude();
/**
* Latitude of a GeoPoint (decimal degrees).
*
* More information under https://w3id.org/idsa/core/latitude
*
* @param _latitude_ desired value for the property _latitude.
*/
void setLatitude(float _latitude_);
/**
* Longitude of a GeoPoint (decimal degrees).
*
* More information under https://w3id.org/idsa/core/longitude
*
* @return Returns the float for the property _longitude.
*/
@NotNull
float getLongitude();
/**
* Longitude of a GeoPoint (decimal degrees).
*
* More information under https://w3id.org/idsa/core/longitude
*
* @param _longitude_ desired value for the property _longitude.
*/
void setLongitude(float _longitude_);
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fescar.common;
import java.util.Random;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* The type Xid test.
*
* @author Otis.z
* @date 2019 /2/22
*/
public class XIDTest {
/**
* Test set ip address.
*/
@Test
public void testSetIpAddress() {
XID.setIpAddress("127.0.0.1");
assertThat(XID.getIpAddress()).isEqualTo("127.0.0.1");
}
/**
* Test set port.
*/
@Test
public void testSetPort() {
XID.setPort(8080);
assertThat(XID.getPort()).isEqualTo(8080);
}
/**
* Test generate xid.
*/
@Test
public void testGenerateXID() {
long tranId = new Random().nextLong();
XID.setPort(8080);
XID.setIpAddress("127.0.0.1");
assertThat(XID.generateXID(tranId)).isEqualTo(XID.getIpAddress() + ":" + XID.getPort() + ":" + tranId);
}
/**
* Test get transaction id.
*/
@Test
public void testGetTransactionId() {
assertThat(XID.getTransactionId(null)).isEqualTo(-1);
assertThat(XID.getTransactionId("127.0.0.1:8080:8577662204289747564")).isEqualTo(8577662204289747564L);
}
}
|
package com.yhcdhp.cai;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
@ViewInject(R.id.container)
private ViewPager mViewPager;
@ViewInject(R.id.toolbar)
private Toolbar toolbar;
@ViewInject(R.id.tabs)
private TabLayout tabLayout;
private SectionsPagerAdapter mSectionsPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
return new HttpFragment();
}
case 1: {
return new DbFragment();
}
case 2: {
return new ImageFragment();
}
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Http";
case 1:
return "Database";
case 2:
return "Image";
}
return null;
}
}
}
|
package class0325lecture9;
import java.io.FileWriter;
import java.io.IOException;
public class FWriter {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileWriter fw = new FileWriter ("C:\\Users\\kopo39\\Desktop\\new.txt", true);
for (int i = 11; i < 16; i++) {
String data = "Line #" + i + "\n";
fw.write(data);
}
fw.close();
}
}
|
package com.hortonworks.streamline.streams.catalog.topology.component;
import com.hortonworks.streamline.common.QueryParam;
import com.hortonworks.streamline.registries.model.client.MLModelRegistryClient;
import com.hortonworks.streamline.streams.catalog.Topology;
import com.hortonworks.streamline.streams.catalog.TopologyComponent;
import com.hortonworks.streamline.streams.catalog.TopologyEdge;
import com.hortonworks.streamline.streams.catalog.TopologyProcessor;
import com.hortonworks.streamline.streams.catalog.TopologySink;
import com.hortonworks.streamline.streams.catalog.TopologySource;
import com.hortonworks.streamline.streams.catalog.service.StreamCatalogService;
import com.hortonworks.streamline.streams.layout.component.TopologyDag;
import java.util.ArrayList;
import java.util.List;
public class TopologyDagBuilder {
private final StreamCatalogService catalogService;
private final TopologyComponentFactory factory;
public TopologyDagBuilder(StreamCatalogService catalogService, MLModelRegistryClient modelRegistryClient) {
this.catalogService = catalogService;
factory = new TopologyComponentFactory(catalogService, modelRegistryClient);
}
public TopologyDag getDag(Topology topology) {
try {
TopologyDag dag = new TopologyDag();
addSources(dag, topology);
addProcessors(dag, topology);
addSinks(dag, topology);
addEdges(dag, topology);
return dag;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void addSources(TopologyDag dag, Topology topology) throws Exception {
for (TopologySource topologySource : catalogService.listTopologySources(queryParam(topology))) {
dag.add(factory.getStreamlineSource(topologySource));
}
}
private void addProcessors(TopologyDag dag, Topology topology) throws Exception {
for (TopologyProcessor topologyProcessor : catalogService.listTopologyProcessors(queryParam(topology))) {
dag.add(factory.getStreamlineProcessor(topologyProcessor));
}
}
private void addSinks(TopologyDag dag, Topology topology) throws Exception {
for (TopologySink topologySink : catalogService.listTopologySinks(queryParam(topology))) {
dag.add(factory.getStreamlineSink(topologySink));
}
}
private void addEdges(TopologyDag dag, Topology topology) throws Exception {
for (TopologyEdge topologyEdge: catalogService.listTopologyEdges(queryParam(topology))) {
dag.addEdge(factory.getStreamlineEdge(topologyEdge));
}
}
private List<QueryParam> queryParam(Topology topology) {
List<QueryParam> queryParams = new ArrayList<>();
queryParams.add(new QueryParam(TopologyComponent.TOPOLOGYID, topology.getId().toString()));
queryParams.add(new QueryParam(TopologyComponent.VERSIONID, topology.getVersionId().toString()));
return queryParams;
}
}
|
package org.hl7.davinci.endpoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.jsonwebtoken.Jwts;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hl7.davinci.endpoint.database.PublicKeyRepository;
import org.hl7.davinci.endpoint.database.RequestLog;
import org.hl7.davinci.endpoint.database.RequestService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
RequestService requestService;
private PublicKeyRepository publicKeyRepository;
public JwtAuthorizationFilter(AuthenticationManager authManager, RequestService requestService,
PublicKeyRepository publicKeyRepository) {
super(authManager);
this.requestService = requestService;
this.publicKeyRepository = publicKeyRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String requestStr;
try {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter w = mapper.writer();
requestStr = w.writeValueAsString(req);
} catch (Exception e) {
logger.error("failed to write request json: " + e.getMessage());
requestStr = "{\"error\": \"Authorization failed, request rejected\"}";
}
RequestLog requestLog = new RequestLog(requestStr.getBytes(), new Date().getTime());
String header = req.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer")) {
requestService.create(requestLog);
logger.warn("JWT authorization failed - no bearer auth token present");
chain.doFilter(req, res);
return;
}
logger.info("Bearer auth token recieved");
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
if (authentication == null) {
requestService.create(requestLog);
}
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
// parse the token.
token = token.replace("Bearer ", "");
String user = isTokenWellFormed(token);
// Check the token's signature. Throws an exception if the token is rejected
try {
// The KeyResolver fetches the public key from the jku
// will throw an exception if the signature cannot be verified
Jwts.parser()
.setSigningKeyResolver(new SigningKeyResolverCrd(publicKeyRepository))
.parseClaimsJws(token).getSignature();
} catch (io.jsonwebtoken.SignatureException sigEx) {
logger.info("Failed to verify token signature, rejecting token.");
return null;
}
if (user != null) {
logger.info("Validated JWT token structure from " + user);
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
logger.warn("Invalid Bearer token - the token was not well formed.");
return null;
}
/**
* Checks if the token is well formed. This includes following
* rfc7515 standard for JWT and the CDS-Hooks specification.
*
* @param token the JWT to be checked
* @return a boolean indicating whether the token is well formed
*/
private String isTokenWellFormed(String token) {
JsonParser parser = new JsonParser();
// JWT tokens are of the form:
// header payload signature
// xxxxxxxxx.yyyyyyyyyyy.zzzzzzzzzzzz
// where each section is base64 encoded JSON.
// We need to check if the header and the payload
// have the correct keys and if the signature is present.
// The signature will be validated later.
String[] tokens = token.split("\\.");
if (tokens.length != 3) {
logger.warn("Token doesn't have proper format, rejecting");
// tokens without all three sections are invalid
return null;
}
try {
String header = new String(Base64.getDecoder().decode(tokens[0]));
String payload = new String(Base64.getDecoder().decode(tokens[1]));
// we just want to make sure the json has the correct fields
// their contents aren't really important, if the contents are
// bad we can reject them later.
List<String> requiredHeaders = Arrays.asList("alg","typ","kid");
List<String> requiredPayload = Arrays.asList("iss","aud","exp","iat","jti");
JsonObject jsonHeader = parser
.parse(header)
.getAsJsonObject();
boolean validHeader = jsonHeader
.keySet()
.containsAll(requiredHeaders);
JsonObject jsonPayload = parser
.parse(payload)
.getAsJsonObject();
boolean validPayload = jsonPayload
.keySet()
.containsAll(requiredPayload);
if (validHeader && validPayload) {
return jsonPayload.get("iss").toString();
} else {
if (!validHeader) {
requiredHeaders.removeAll(jsonHeader.keySet());
logger.warn("Token header rejected, missing required properties - " + requiredHeaders);
}
if (!validPayload) {
requiredPayload.removeAll(jsonPayload.keySet());
logger.warn("Token payload rejected, missing required properties - " + requiredPayload);
}
return null;
}
// if any part of the above fails, the token
// is of invalid format
} catch (IllegalArgumentException decodingError) {
logger.warn("The token was not properly base64 encoded - cannot parse token");
return null;
} catch (IllegalStateException parsingError) {
logger.warn("The token contained invalid JSON");
return null;
}
}
}
|
package sguest.villagelife.item;
import java.util.function.Supplier;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.IArmorMaterial;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.LazyValue;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.SoundEvents;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.Tags;
import sguest.villagelife.VillageLife;
public class ModArmorMaterial implements IArmorMaterial {
public static IArmorMaterial EMERALD;
public static void register() {
EMERALD = new ModArmorMaterial("emerald", 25, new int[]{2, 5, 6, 2}, 25, SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, () -> Ingredient.fromTag(Tags.Items.GEMS_EMERALD), 1.0F, 0.0F);
}
private final String name;
private final int maxDamageFactor;
private final int[] damageReductionAmountArray;
private final int enchantability;
private final SoundEvent soundEvent;
private final LazyValue<Ingredient> repairMaterial;
private final float toughness;
private final float knockbackResistance;
public ModArmorMaterial(String name, int maxDamageFactor, int[] damageReductionAmountArray, int enchantability, SoundEvent soundEvent, Supplier<Ingredient> repairMaterial, float toughness, float knockbackResistance) {
this.name = VillageLife.MOD_ID + ":" + name;
this.maxDamageFactor = maxDamageFactor;
this.damageReductionAmountArray = damageReductionAmountArray;
this.enchantability = enchantability;
this.soundEvent = soundEvent;
this.repairMaterial = new LazyValue<>(repairMaterial);
this.toughness = toughness;
this.knockbackResistance = knockbackResistance;
}
private static final int[] MAX_DAMAGE_ARRAY = new int[]{13, 15, 16, 11};
@Override
public int getDurability(EquipmentSlotType slotIn) {
return MAX_DAMAGE_ARRAY[slotIn.getIndex()] * maxDamageFactor;
}
@Override
public int getDamageReductionAmount(EquipmentSlotType slotIn) {
return damageReductionAmountArray[slotIn.getIndex()];
}
@Override
public int getEnchantability() {
return enchantability;
}
@Override
public SoundEvent getSoundEvent() {
return soundEvent;
}
@Override
public Ingredient getRepairMaterial() {
return repairMaterial.getValue();
}
@Override
@OnlyIn(Dist.CLIENT)
public String getName() {
return name;
}
@Override
public float getToughness() {
return toughness;
}
@Override
public float getKnockbackResistance() {
return knockbackResistance;
}
}
|
package cn.omsfuk.blog.controller;
import cn.omsfuk.blog.dao.RoleDao;
import cn.omsfuk.blog.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by omsfuk on 17-5-5.
*/
@RestController
@RequestMapping("/api")
public class TestController {
@Autowired
private RoleDao roleDao;
@RequestMapping(value = "/role/name/{name}", method = RequestMethod.GET)
public Role getRole() {
return roleDao.getRoleByName("Administrator");
}
}
|
package com.opensymphony.workflow.loader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Element;
/**
* @author Andrea Capitani (a.capitani@leonardomultimedia.it)
*/
public class ConfigValidatorDescriptor extends ValidatorDescriptor implements ArgsAware
{
protected String name;
protected String plugin;
protected String description;
protected List modifiableArgs = new ArrayList();
protected Map argTypeMap = new HashMap();
private PaletteDescriptor palette;
public ConfigValidatorDescriptor(PaletteDescriptor palette)
{
this.palette = palette;
}
public ConfigValidatorDescriptor(PaletteDescriptor palette, Element validator)
{
this.palette = palette;
init(validator);
}
public ConfigValidatorDescriptor(ConfigValidatorDescriptor other)
{
this.setPlugin(other.getPlugin());
this.setName(other.getName());
this.setType(other.getType());
this.getArgs().putAll(other.getArgs());
description = other.description;
modifiableArgs = other.modifiableArgs;
palette = other.palette;
}
public PaletteDescriptor getPalette()
{
return palette;
}
public void setPalette(PaletteDescriptor palette)
{
this.palette = palette;
}
protected void init(Element validator)
{
type = validator.getAttribute("type");
List args = XMLUtil.getChildElements(validator, "arg");
for(int l = 0; l < args.size(); l++)
{
Element arg = (Element)args.get(l);
this.args.put(arg.getAttribute("name"), XMLUtil.getText(arg));
if("true".equals(arg.getAttribute("modifiable")))
{
modifiableArgs.add(arg.getAttribute("name"));
String sArgType = arg.getAttribute("argtype");
if (sArgType!=null)
{
ArgType at = (ArgType)palette.getArgType(sArgType);
if (at!=null)
{
argTypeMap.put(arg.getAttribute("name"), at);
}
}
}
}
plugin = XMLUtil.getChildText(validator, "plugin");
name = XMLUtil.getChildText(validator, "name");
}
public boolean isArgModifiable(String name)
{
return modifiableArgs.contains(name);
}
public ArgType getArgType(String name)
{
return (ArgType)argTypeMap.get(name);
}
public void writeXML(PrintWriter writer, int indent)
{
throw new UnsupportedOperationException();
}
public String getDescription()
{
return description;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPlugin()
{
return plugin;
}
public void setDescription(String string)
{
description = string;
}
public void setPlugin(String string)
{
plugin = string;
}
public String toString()
{
return getName();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.startup;
import org.apache.tomcat.util.digester.Digester;
import org.apache.tomcat.util.digester.RuleSetBase;
/**
* <p><strong>RuleSet</strong> for processing the contents of a
* Context or DefaultContext definition element. To enable parsing of a
* DefaultContext, be sure to specify a prefix that ends with "/Default".</p>
*
* @author Craig R. McClanahan
* @version $Revision: 707757 $ $Date: 2008-10-24 23:54:48 +0200 (Fri, 24 Oct 2008) $
*/
public class ContextRuleSet extends RuleSetBase {
// ----------------------------------------------------- Instance Variables
/**
* The matching pattern prefix to use for recognizing our elements.
*/
protected String prefix = null;
/**
* Should the context be created.
*/
protected boolean create = true;
// ------------------------------------------------------------ Constructor
/**
* Construct an instance of this <code>RuleSet</code> with the default
* matching pattern prefix.
*/
public ContextRuleSet() {
this("");
}
/**
* Construct an instance of this <code>RuleSet</code> with the specified
* matching pattern prefix.
*
* @param prefix Prefix for matching pattern rules (including the
* trailing slash character)
*/
public ContextRuleSet(String prefix) {
super();
this.namespaceURI = null;
this.prefix = prefix;
}
/**
* Construct an instance of this <code>RuleSet</code> with the specified
* matching pattern prefix.
*
* @param prefix Prefix for matching pattern rules (including the
* trailing slash character)
*/
public ContextRuleSet(String prefix, boolean create) {
super();
this.namespaceURI = null;
this.prefix = prefix;
this.create = create;
}
// --------------------------------------------------------- Public Methods
/**
* <p>Add the set of Rule instances defined in this RuleSet to the
* specified <code>Digester</code> instance, associating them with
* our namespace URI (if any). This method should only be called
* by a Digester instance.</p>
*
* @param digester Digester instance to which the new Rule instances
* should be added.
*/
public void addRuleInstances(Digester digester) {
if (create) {
digester.addObjectCreate(prefix + "Context",
"org.apache.catalina.core.StandardContext", "className");
digester.addSetProperties(prefix + "Context");
} else {
digester.addRule(prefix + "Context", new SetContextPropertiesRule());
}
if (create) {
digester.addRule(prefix + "Context",
new LifecycleListenerRule
("org.apache.catalina.startup.ContextConfig",
"configClass"));
digester.addSetNext(prefix + "Context",
"addChild",
"org.apache.catalina.Container");
}
digester.addCallMethod(prefix + "Context/InstanceListener",
"addInstanceListener", 0);
digester.addObjectCreate(prefix + "Context/Listener",
null, // MUST be specified in the element
"className");
digester.addSetProperties(prefix + "Context/Listener");
digester.addSetNext(prefix + "Context/Listener",
"addLifecycleListener",
"org.apache.catalina.LifecycleListener");
digester.addObjectCreate(prefix + "Context/Loader",
"org.apache.catalina.loader.WebappLoader",
"className");
digester.addSetProperties(prefix + "Context/Loader");
digester.addSetNext(prefix + "Context/Loader",
"setLoader",
"org.apache.catalina.Loader");
digester.addObjectCreate(prefix + "Context/Manager",
"org.apache.catalina.session.StandardManager",
"className");
digester.addSetProperties(prefix + "Context/Manager");
digester.addSetNext(prefix + "Context/Manager",
"setManager",
"org.apache.catalina.Manager");
digester.addObjectCreate(prefix + "Context/Manager/Store",
null, // MUST be specified in the element
"className");
digester.addSetProperties(prefix + "Context/Manager/Store");
digester.addSetNext(prefix + "Context/Manager/Store",
"setStore",
"org.apache.catalina.Store");
digester.addObjectCreate(prefix + "Context/Parameter",
"org.apache.catalina.deploy.ApplicationParameter");
digester.addSetProperties(prefix + "Context/Parameter");
digester.addSetNext(prefix + "Context/Parameter",
"addApplicationParameter",
"org.apache.catalina.deploy.ApplicationParameter");
digester.addRuleSet(new RealmRuleSet(prefix + "Context/"));
digester.addObjectCreate(prefix + "Context/Resources",
"org.apache.naming.resources.FileDirContext",
"className");
digester.addSetProperties(prefix + "Context/Resources");
digester.addSetNext(prefix + "Context/Resources",
"setResources",
"javax.naming.directory.DirContext");
digester.addObjectCreate(prefix + "Context/ResourceLink",
"org.apache.catalina.deploy.ContextResourceLink");
digester.addSetProperties(prefix + "Context/ResourceLink");
digester.addRule(prefix + "Context/ResourceLink",
new SetNextNamingRule("addResourceLink",
"org.apache.catalina.deploy.ContextResourceLink"));
digester.addObjectCreate(prefix + "Context/Valve",
null, // MUST be specified in the element
"className");
digester.addSetProperties(prefix + "Context/Valve");
digester.addSetNext(prefix + "Context/Valve",
"addValve",
"org.apache.catalina.Valve");
digester.addCallMethod(prefix + "Context/WatchedResource",
"addWatchedResource", 0);
digester.addCallMethod(prefix + "Context/WrapperLifecycle",
"addWrapperLifecycle", 0);
digester.addCallMethod(prefix + "Context/WrapperListener",
"addWrapperListener", 0);
}
}
|
package org.akhq.controllers;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.security.annotation.Secured;
import io.swagger.v3.oas.annotations.Operation;
import org.akhq.configs.Role;
import org.akhq.models.Cluster;
import org.akhq.models.Config;
import org.akhq.models.LogDir;
import org.akhq.models.Node;
import org.akhq.repositories.ClusterRepository;
import org.akhq.repositories.ConfigRepository;
import org.akhq.repositories.LogDirRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
@Secured(Role.ROLE_NODE_READ)
@Controller("${akhq.server.base-path:}/")
public class NodeController extends AbstractController {
private final ClusterRepository clusterRepository;
private final ConfigRepository configRepository;
private final LogDirRepository logDirRepository;
@Inject
public NodeController(ClusterRepository clusterRepository, ConfigRepository configRepository, LogDirRepository logDirRepository) {
this.clusterRepository = clusterRepository;
this.configRepository = configRepository;
this.logDirRepository = logDirRepository;
}
@Get("api/{cluster}/node")
@Operation(tags = {"node"}, summary = "List all nodes")
public Cluster list(String cluster) throws ExecutionException, InterruptedException {
return this.clusterRepository.get(cluster);
}
@Get("api/{cluster}/node/{nodeId}")
@Operation(tags = {"node"}, summary = "Retrieve a nodes")
public Node node(String cluster, Integer nodeId) throws ExecutionException, InterruptedException {
return findNode(cluster, nodeId);
}
@Get("api/{cluster}/node/{nodeId}/logs")
@Operation(tags = {"node"}, summary = "List all logs for a node")
public List<LogDir> nodeLog(String cluster, Integer nodeId) throws ExecutionException, InterruptedException {
return logDirRepository.findByBroker(cluster, nodeId);
}
@Get("api/{cluster}/node/{nodeId}/configs")
@Operation(tags = {"node"}, summary = "List all configs for a node")
public List<Config> nodeConfig(String cluster, Integer nodeId) throws ExecutionException, InterruptedException {
List<Config> configs = this.configRepository.findByBroker(cluster, nodeId);
if (configs == null) {
return new ArrayList<>();
}
configs.sort((o1, o2) -> o1.isReadOnly() == o2.isReadOnly() ? 0 :
(o1.isReadOnly() ? 1 : -1 )
);
return configs;
}
@Post("api/{cluster}/node/{nodeId}/configs")
@Operation(tags = {"node"}, summary = "Update configs for a node")
public List<Config> nodeConfigUpdate(String cluster, Integer nodeId, Map<String, String> configs) throws ExecutionException, InterruptedException {
List<Config> updated = ConfigRepository.updatedConfigs(configs, this.configRepository.findByBroker(cluster, nodeId), false);
if (updated.size() == 0) {
throw new IllegalArgumentException("No config to update");
}
this.configRepository.updateBroker(
cluster,
nodeId,
updated
);
return updated;
}
private Node findNode(String cluster, Integer nodeId) throws ExecutionException, InterruptedException {
return this.clusterRepository.get(cluster)
.getNodes()
.stream()
.filter(e -> e.getId() == nodeId)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Node '" + nodeId + "' doesn't exist"));
}
}
|
/*
* Copyright 2019 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.compute.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;
@Generated("by GAPIC")
@BetaApi
public final class AggregatedListNodeTypesHttpRequest implements ApiMessage {
private final String access_token;
private final String callback;
private final String fields;
private final String filter;
private final String key;
private final Integer maxResults;
private final String orderBy;
private final String pageToken;
private final String prettyPrint;
private final String project;
private final String quotaUser;
private final String userIp;
private AggregatedListNodeTypesHttpRequest() {
this.access_token = null;
this.callback = null;
this.fields = null;
this.filter = null;
this.key = null;
this.maxResults = null;
this.orderBy = null;
this.pageToken = null;
this.prettyPrint = null;
this.project = null;
this.quotaUser = null;
this.userIp = null;
}
private AggregatedListNodeTypesHttpRequest(
String access_token,
String callback,
String fields,
String filter,
String key,
Integer maxResults,
String orderBy,
String pageToken,
String prettyPrint,
String project,
String quotaUser,
String userIp) {
this.access_token = access_token;
this.callback = callback;
this.fields = fields;
this.filter = filter;
this.key = key;
this.maxResults = maxResults;
this.orderBy = orderBy;
this.pageToken = pageToken;
this.prettyPrint = prettyPrint;
this.project = project;
this.quotaUser = quotaUser;
this.userIp = userIp;
}
@Override
public Object getFieldValue(String fieldName) {
if ("access_token".equals(fieldName)) {
return access_token;
}
if ("callback".equals(fieldName)) {
return callback;
}
if ("fields".equals(fieldName)) {
return fields;
}
if ("filter".equals(fieldName)) {
return filter;
}
if ("key".equals(fieldName)) {
return key;
}
if ("maxResults".equals(fieldName)) {
return maxResults;
}
if ("orderBy".equals(fieldName)) {
return orderBy;
}
if ("pageToken".equals(fieldName)) {
return pageToken;
}
if ("prettyPrint".equals(fieldName)) {
return prettyPrint;
}
if ("project".equals(fieldName)) {
return project;
}
if ("quotaUser".equals(fieldName)) {
return quotaUser;
}
if ("userIp".equals(fieldName)) {
return userIp;
}
return null;
}
@Nullable
@Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@Nullable
@Override
public List<String> getFieldMask() {
return null;
}
public String getAccessToken() {
return access_token;
}
public String getCallback() {
return callback;
}
public String getFields() {
return fields;
}
public String getFilter() {
return filter;
}
public String getKey() {
return key;
}
public Integer getMaxResults() {
return maxResults;
}
public String getOrderBy() {
return orderBy;
}
public String getPageToken() {
return pageToken;
}
public String getPrettyPrint() {
return prettyPrint;
}
public String getProject() {
return project;
}
public String getQuotaUser() {
return quotaUser;
}
public String getUserIp() {
return userIp;
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(AggregatedListNodeTypesHttpRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
public static AggregatedListNodeTypesHttpRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final AggregatedListNodeTypesHttpRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new AggregatedListNodeTypesHttpRequest();
}
public static class Builder {
private String access_token;
private String callback;
private String fields;
private String filter;
private String key;
private Integer maxResults;
private String orderBy;
private String pageToken;
private String prettyPrint;
private String project;
private String quotaUser;
private String userIp;
Builder() {}
public Builder mergeFrom(AggregatedListNodeTypesHttpRequest other) {
if (other == AggregatedListNodeTypesHttpRequest.getDefaultInstance()) return this;
if (other.getAccessToken() != null) {
this.access_token = other.access_token;
}
if (other.getCallback() != null) {
this.callback = other.callback;
}
if (other.getFields() != null) {
this.fields = other.fields;
}
if (other.getFilter() != null) {
this.filter = other.filter;
}
if (other.getKey() != null) {
this.key = other.key;
}
if (other.getMaxResults() != null) {
this.maxResults = other.maxResults;
}
if (other.getOrderBy() != null) {
this.orderBy = other.orderBy;
}
if (other.getPageToken() != null) {
this.pageToken = other.pageToken;
}
if (other.getPrettyPrint() != null) {
this.prettyPrint = other.prettyPrint;
}
if (other.getProject() != null) {
this.project = other.project;
}
if (other.getQuotaUser() != null) {
this.quotaUser = other.quotaUser;
}
if (other.getUserIp() != null) {
this.userIp = other.userIp;
}
return this;
}
Builder(AggregatedListNodeTypesHttpRequest source) {
this.access_token = source.access_token;
this.callback = source.callback;
this.fields = source.fields;
this.filter = source.filter;
this.key = source.key;
this.maxResults = source.maxResults;
this.orderBy = source.orderBy;
this.pageToken = source.pageToken;
this.prettyPrint = source.prettyPrint;
this.project = source.project;
this.quotaUser = source.quotaUser;
this.userIp = source.userIp;
}
public String getAccessToken() {
return access_token;
}
public Builder setAccessToken(String access_token) {
this.access_token = access_token;
return this;
}
public String getCallback() {
return callback;
}
public Builder setCallback(String callback) {
this.callback = callback;
return this;
}
public String getFields() {
return fields;
}
public Builder setFields(String fields) {
this.fields = fields;
return this;
}
public String getFilter() {
return filter;
}
public Builder setFilter(String filter) {
this.filter = filter;
return this;
}
public String getKey() {
return key;
}
public Builder setKey(String key) {
this.key = key;
return this;
}
public Integer getMaxResults() {
return maxResults;
}
public Builder setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
return this;
}
public String getOrderBy() {
return orderBy;
}
public Builder setOrderBy(String orderBy) {
this.orderBy = orderBy;
return this;
}
public String getPageToken() {
return pageToken;
}
public Builder setPageToken(String pageToken) {
this.pageToken = pageToken;
return this;
}
public String getPrettyPrint() {
return prettyPrint;
}
public Builder setPrettyPrint(String prettyPrint) {
this.prettyPrint = prettyPrint;
return this;
}
public String getProject() {
return project;
}
public Builder setProject(String project) {
this.project = project;
return this;
}
public String getQuotaUser() {
return quotaUser;
}
public Builder setQuotaUser(String quotaUser) {
this.quotaUser = quotaUser;
return this;
}
public String getUserIp() {
return userIp;
}
public Builder setUserIp(String userIp) {
this.userIp = userIp;
return this;
}
public AggregatedListNodeTypesHttpRequest build() {
String missing = "";
if (project == null) {
missing += " project";
}
if (!missing.isEmpty()) {
throw new IllegalStateException("Missing required properties:" + missing);
}
return new AggregatedListNodeTypesHttpRequest(
access_token,
callback,
fields,
filter,
key,
maxResults,
orderBy,
pageToken,
prettyPrint,
project,
quotaUser,
userIp);
}
public Builder clone() {
Builder newBuilder = new Builder();
newBuilder.setAccessToken(this.access_token);
newBuilder.setCallback(this.callback);
newBuilder.setFields(this.fields);
newBuilder.setFilter(this.filter);
newBuilder.setKey(this.key);
newBuilder.setMaxResults(this.maxResults);
newBuilder.setOrderBy(this.orderBy);
newBuilder.setPageToken(this.pageToken);
newBuilder.setPrettyPrint(this.prettyPrint);
newBuilder.setProject(this.project);
newBuilder.setQuotaUser(this.quotaUser);
newBuilder.setUserIp(this.userIp);
return newBuilder;
}
}
@Override
public String toString() {
return "AggregatedListNodeTypesHttpRequest{"
+ "access_token="
+ access_token
+ ", "
+ "callback="
+ callback
+ ", "
+ "fields="
+ fields
+ ", "
+ "filter="
+ filter
+ ", "
+ "key="
+ key
+ ", "
+ "maxResults="
+ maxResults
+ ", "
+ "orderBy="
+ orderBy
+ ", "
+ "pageToken="
+ pageToken
+ ", "
+ "prettyPrint="
+ prettyPrint
+ ", "
+ "project="
+ project
+ ", "
+ "quotaUser="
+ quotaUser
+ ", "
+ "userIp="
+ userIp
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof AggregatedListNodeTypesHttpRequest) {
AggregatedListNodeTypesHttpRequest that = (AggregatedListNodeTypesHttpRequest) o;
return Objects.equals(this.access_token, that.getAccessToken())
&& Objects.equals(this.callback, that.getCallback())
&& Objects.equals(this.fields, that.getFields())
&& Objects.equals(this.filter, that.getFilter())
&& Objects.equals(this.key, that.getKey())
&& Objects.equals(this.maxResults, that.getMaxResults())
&& Objects.equals(this.orderBy, that.getOrderBy())
&& Objects.equals(this.pageToken, that.getPageToken())
&& Objects.equals(this.prettyPrint, that.getPrettyPrint())
&& Objects.equals(this.project, that.getProject())
&& Objects.equals(this.quotaUser, that.getQuotaUser())
&& Objects.equals(this.userIp, that.getUserIp());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(
access_token,
callback,
fields,
filter,
key,
maxResults,
orderBy,
pageToken,
prettyPrint,
project,
quotaUser,
userIp);
}
}
|
package de.ma_vin.ape.users.controller.it.steps;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.ma_vin.ape.users.enums.Role;
import de.ma_vin.ape.users.model.gen.dto.group.UserIdRoleDto;
import de.ma_vin.ape.users.model.gen.dto.user.UserDto;
import de.ma_vin.ape.utils.TestUtil;
import de.ma_vin.ape.utils.controller.response.Status;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.MultiValueMap;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsAnything.anything;
import static org.junit.jupiter.api.Assertions.fail;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
public class UserSteps extends AbstractIntegrationTestSteps {
@Given("There exists an user with first name {string} and last name {string} with alias {string} at common group {string}")
public void createUser(String firstName, String lastName, String userAlias, String commonGroupAlias) throws Exception {
if (!shared.containsKey(commonGroupAlias)) {
fail("There is not any common group with alias " + commonGroupAlias);
}
MultiValueMap<String, String> createUserValues = createValueMap("firstName", firstName, "lastName", lastName
, "commonGroupIdentification", getIdentification(commonGroupAlias));
MockHttpServletResponse createUserResponse = performPostWithAuthorization("/user/createUser", createUserValues)
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("status", is(Status.OK.name())))
.andExpect(jsonPath("response.firstName", is(firstName)))
.andExpect(jsonPath("response.lastName", is(lastName)))
.andExpect(jsonPath("response.identification", anything()))
.andReturn().getResponse();
String createdUserText = TestUtil.getObjectMapper().readTree(createUserResponse.getContentAsString()).findValue("response").toString();
shared.put(userAlias, TestUtil.getObjectMapper().readValue(createdUserText, UserDto.class));
}
@Given("There are users with first and last name and alias at common group {string}")
public void createBaseGroups(String commonGroupAlias, DataTable dataTable) {
dataTable.asLists().forEach(row -> {
if (row.size() != 3) {
fail("Wrong number of columns while creating users");
}
try {
createUser(row.get(0), row.get(1), row.get(2), commonGroupAlias);
} catch (Exception e) {
fail(e.getMessage());
}
});
}
@Given("The users are added to base group")
public void addBaseToBaseGroup(DataTable dataTable) {
dataTable.asLists().forEach(row -> {
if (row.size() != 2) {
fail("Wrong number of columns while adding users to base one");
}
try {
callControllerToAddUserToBaseGroup(row.get(0), row.get(1));
} catch (Exception e) {
fail(e.getMessage());
}
});
}
@Given("The users are added to privilege group with role")
public void addBaseToPrivilegeGroup(DataTable dataTable) {
dataTable.asLists().forEach(row -> {
if (row.size() != 3) {
fail("Wrong number of columns while adding users to privilege one");
}
try {
callControllerToAddUserToPrivilegeGroup(row.get(0), Role.valueOf(row.get(2)), row.get(1));
} catch (Exception e) {
fail(e.getMessage());
}
});
}
@Given("The {string} of the user with alias {string} is set to {string}")
public void setUserValue(String property, String alias, String valueToSet) {
setStringValue(property, alias, valueToSet);
}
@Given("There exists an user with first name {string}, last name {string}, password {string} and role {roleValue} with alias {string} at common group {string}")
public void createUser(String firstName, String lastName, String password, Role role, String userAlias, String commonGroupAlias) throws Exception {
createUser(firstName, lastName, userAlias, commonGroupAlias);
callControllerToSetUsersPassword(password, userAlias);
checkResponseExistsAndOk();
callControllerToSetUsersRole(role, userAlias);
checkResponseExistsAndOk();
}
@When("The Controller is called to create an user with first name {string} and last name {string} at common group {string}")
public void callControllerToCreateUser(String firstName, String lastName, String commonGroupAlias) {
MultiValueMap<String, String> createUserValues = createValueMap("firstName", firstName, "lastName", lastName
, "commonGroupIdentification", getIdentification(commonGroupAlias));
shared.setResultActions(performPostWithAuthorization("/user/createUser", createUserValues));
}
@When("Controller is called to get the user with the identification of the alias {string}")
public void callControllerToGetUser(String userAlias) {
shared.setResultActions(performGetWithAuthorization("/user/getUser", getIdentification(userAlias)));
}
@When("Controller is called to update the user with the identification of the alias {string}")
public void callControllerToUpdateUser(String userAlias) {
shared.setResultActions(performPutWithAuthorization("/user/updateUser", getIdentification(userAlias), userAlias));
}
@When("Controller is called to delete the user with the identification of the alias {string}")
public void callControllerToDeleteUser(String userAlias) {
shared.setResultActions(performDeleteWithAuthorization("/user/deleteUser", getIdentification(userAlias)));
}
@When("Controller is called to count users at common group with alias {string}")
public void callControllerToCountUsers(String commonGroupAlias) {
shared.setResultActions(performGetWithAuthorization("/user/countUsers", getIdentification(commonGroupAlias)));
}
@When("Controller is called to get all users from common group with identification of {string}")
public void callControllerToGetAllUsers(String commonGroupAlias) {
shared.setResultActions(performGetWithAuthorization("/user/getAllUsers", getIdentification(commonGroupAlias)));
}
@When("Controller is called to get all users at page {int} with size {int} from common group with alias {string}")
public void callControllerToGetAllUsers(int page, int size, String commonGroupAlias) {
MultiValueMap<String, String> getAllUsersValues = createValueMap("page", "" + page
, "size", "" + size);
shared.setResultActions(performGetWithAuthorization("/user/getAllUsers", getIdentification(commonGroupAlias), getAllUsersValues));
}
@When("Controller is called to add the user with alias {string} to base group with alias {string}")
public void callControllerToAddUserToBaseGroup(String userAlias, String baseGroupAlias) {
shared.setResultActions(performPatchWithAuthorization("/user/addUserToBaseGroup", getIdentification(baseGroupAlias)
, getIdentification(userAlias)));
}
@When("Controller is called to remove the user with alias {string} from base group with alias {string}")
public void callControllerToRemoveUserFromBaseGroup(String userAlias, String baseGroupAlias) {
shared.setResultActions(performPatchWithAuthorization("/user/removeUserFromBaseGroup", getIdentification(baseGroupAlias)
, getIdentification(userAlias)));
}
@When("Controller is called to count users at base group with alias {string}")
public void callControllerToCountUsersAtBaseGroup(String baseGroupAlias) {
shared.setResultActions(performGetWithAuthorization("/user/countUsersAtBaseGroup", getIdentification(baseGroupAlias)));
}
@When("Controller is called to get all user of base group with alias {string} and dissolving sub groups {booleanValue}")
public void callControllerToGetAllUsersFromBaseGroup(String baseGroupAlias, Boolean dissolveSubgroups) {
MultiValueMap<String, String> findAllUsers = createValueMap("dissolveSubgroups", dissolveSubgroups.toString());
shared.setResultActions(performGetWithAuthorization("/user/getAllUsersFromBaseGroup", getIdentification(baseGroupAlias), findAllUsers));
}
@When("Controller is called to get all users at page {int} with size {int} from base group with alias {string}")
public void callControllerToGetAllUsersFromBaseGroup(int page, int size, String baseGroupAlias) {
MultiValueMap<String, String> getAllUsersValues = createValueMap("page", "" + page, "size", "" + size);
shared.setResultActions(performGetWithAuthorization("/user/getAllUsersFromBaseGroup", getIdentification(baseGroupAlias), getAllUsersValues));
}
@When("Controller is called to add the user with alias {string} as {roleValue} to privilege group with alias {string}")
public void callControllerToAddUserToPrivilegeGroup(String userAlias, Role role, String privilegeGroupAlias) {
UserIdRoleDto baseGroupIdRoleDto = new UserIdRoleDto();
baseGroupIdRoleDto.setUserIdentification(getIdentification(userAlias));
baseGroupIdRoleDto.setRole(role);
try {
shared.setResultActions(performPatchWithAuthorization("/user/addUserToPrivilegeGroup", getIdentification(privilegeGroupAlias)
, TestUtil.getObjectMapper().writeValueAsString(baseGroupIdRoleDto)));
} catch (JsonProcessingException e) {
fail("JsonProcessingException: " + e.getMessage());
}
}
@When("Controller is called to count users at privilege group with alias {string} with role {roleValue}")
public void callControllerToCountUsersAtPrivilegeGroup(String privilegeGroupAlias, Role role) {
MultiValueMap<String, String> countUsers = createValueMap("role", role.name());
shared.setResultActions(performGetWithAuthorization("/user/countUsersAtPrivilegeGroup", getIdentification(privilegeGroupAlias), countUsers));
}
@When("Controller is called to get all user of privilege group with alias {string} with role {roleValue} and dissolving sub groups {booleanValue}")
public void callControllerToGetAllUsersFromPrivilegeGroup(String privilegeGroupAlias, Role role, Boolean dissolveSubgroups) {
MultiValueMap<String, String> findAllUsers = createValueMap("dissolveSubgroups", dissolveSubgroups.toString(), "role", role.name());
shared.setResultActions(performGetWithAuthorization("/user/getAllUsersFromPrivilegeGroup", getIdentification(privilegeGroupAlias), findAllUsers));
}
@When("Controller is called to get all users with role {roleValue} at page {int} with size {int} from privilege group with alias {string}")
public void callControllerToGetAllUsersFromPrivilegeGroup(Role role, int page, int size, String privilegeGroupAlias) {
MultiValueMap<String, String> getAllUsersValues = createValueMap("page", "" + page, "size", "" + size, "role", role.name());
shared.setResultActions(performGetWithAuthorization("/user/getAllUsersFromPrivilegeGroup", getIdentification(privilegeGroupAlias), getAllUsersValues));
}
@When("Controller is called to remove the user with alias {string} from privilege group with alias {string}")
public void callControllerToRemoveUserFromPrivilegeGroup(String userAlias, String privilegeGroupAlias) {
shared.setResultActions(performPatchWithAuthorization("/user/removeUserFromPrivilegeGroup", getIdentification(privilegeGroupAlias)
, getIdentification(userAlias)));
}
@When("Controller is called to set the password {string} of user with the identification of the alias {string}")
public void callControllerToSetUsersPassword(String password, String userAlias) {
shared.setResultActions(performPatchWithAuthorization("/user/setUserPassword", getIdentification(userAlias)
, password));
}
@When("Controller is called to set the role {roleValue} of user with the identification of the alias {string}")
public void callControllerToSetUsersRole(Role role, String userAlias) throws JsonProcessingException {
shared.setResultActions(performPatchWithAuthorization("/user/setUserRole", getIdentification(userAlias)
, TestUtil.getObjectMapper().writeValueAsString(role)));
}
private void checkResponseExistsAndOk() throws Exception {
shared.getResultActions().andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
}
|
/*
* onprom-umleditor
*
* RelationForm.java
*
* Copyright (C) 2016-2018 Free University of Bozen-Bolzano
*
* This product includes software developed under
* KAOS: Knowledge-Aware Operational Support project
* (https://kaos.inf.unibz.it).
*
* Please visit https://onprom.inf.unibz.it for more information.
*
* 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 it.unibz.inf.kaos.ui.form;
import it.unibz.inf.kaos.data.Association;
import it.unibz.inf.kaos.data.Cardinality;
import it.unibz.inf.kaos.data.UMLClass;
import it.unibz.inf.kaos.interfaces.UMLDiagram;
import it.unibz.inf.kaos.ui.edit.EditFactory;
import it.unibz.inf.kaos.ui.utility.DiagramUndoManager;
import it.unibz.inf.kaos.ui.utility.UIUtility;
import it.unibz.inf.kaos.ui.utility.UMLEditorButtons;
import it.unibz.inf.kaos.ui.utility.UMLEditorLabels;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/**
* Relation form
* <p>
* @author T. E. Kalayci
*/
public class RelationForm extends JPanel {
private final JComboBox<Cardinality> cmbFirstCardinality;
private final JComboBox<Cardinality> cmbSecondCardinality;
private final JComboBox<UMLClass> cmbFirstClass;
private final JComboBox<UMLClass> cmbSecondClass;
private final Association association;
private final JTextField txtRelationName;
public RelationForm(UMLDiagram drawingPanel, Association _association) {
association = _association;
final boolean isUpdateAllowed = drawingPanel.isUpdateAllowed();
setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints = UIUtility.getGridBagConstraints();
final Dimension lblDimension = new Dimension(100, 25);
final Dimension txtDimension = new Dimension(200, 25);
gridBagConstraints.gridy = 1;
gridBagConstraints.gridx = 0;
add(UIUtility.createLabel(UMLEditorLabels.FROM_TO, lblDimension), gridBagConstraints);
gridBagConstraints.gridx = 1;
cmbFirstClass = UIUtility.createWideComboBox(drawingPanel.getClasses(), txtDimension, null, isUpdateAllowed, true);
add(cmbFirstClass, gridBagConstraints);
gridBagConstraints.gridx = 2;
cmbSecondClass = UIUtility.createWideComboBox(drawingPanel.getClasses(), txtDimension, null, isUpdateAllowed, true);
add(cmbSecondClass, gridBagConstraints);
gridBagConstraints.gridy = 2;
gridBagConstraints.gridx = 0;
add(UIUtility.createLabel(UMLEditorLabels.CARDINALITY, lblDimension), gridBagConstraints);
gridBagConstraints.gridx = 1;
cmbFirstCardinality = UIUtility.createWideComboBox(Cardinality.values(), txtDimension, null, isUpdateAllowed, false);
add(cmbFirstCardinality, gridBagConstraints);
gridBagConstraints.gridx = 2;
cmbSecondCardinality = UIUtility.createWideComboBox(Cardinality.values(), txtDimension, null, isUpdateAllowed, false);
add(cmbSecondCardinality, gridBagConstraints);
gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 0;
add(UIUtility.createLabel(UMLEditorLabels.RELATION_NAME, lblDimension), gridBagConstraints);
gridBagConstraints.gridx = 1;
gridBagConstraints.gridwidth = 2;
txtRelationName = UIUtility.createTextField(UMLEditorLabels.RELATION_NAME.getTooltip(), new Dimension(400, 25), isUpdateAllowed);
add(txtRelationName, gridBagConstraints);
txtRelationName.setText(association.getName());
gridBagConstraints.gridy = 1;
gridBagConstraints.gridx = 3;
add(UIUtility.createButton(UMLEditorButtons.CANCEL, e -> setVisible(false), lblDimension), gridBagConstraints);
if (isUpdateAllowed) {
gridBagConstraints.gridy = 0;
add(UIUtility.createButton(UMLEditorButtons.SAVE, e -> {
String prevName = association.getName();
Cardinality prevFirst = association.getFirstMultiplicity();
Cardinality prevSecond = association.getSecondMultiplicity();
association.setName(txtRelationName.getText());
association.setFirstMultiplicity((Cardinality) cmbFirstCardinality.getSelectedItem());
association.setSecondMultiplicity((Cardinality) cmbSecondCardinality.getSelectedItem());
association.setFirstClass((UMLClass) cmbFirstClass.getSelectedItem());
association.setSecondClass((UMLClass) cmbSecondClass.getSelectedItem());
setVisible(false);
//undo operation
DiagramUndoManager.addEdit(EditFactory.relationUpdated(association, prevName, prevFirst, prevSecond));
}, lblDimension), gridBagConstraints);
}
cmbFirstCardinality.setSelectedItem(association.getFirstMultiplicity());
cmbSecondCardinality.setSelectedItem(association.getSecondMultiplicity());
cmbFirstClass.setSelectedItem(association.getFirstClass());
cmbSecondClass.setSelectedItem(association.getSecondClass());
}
}
|
import java.awt.*;
/**
* Class Name: Weapon Cache <br>
* Class Purpose: WeaponCache class implementing IUsable and IInventory<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @author Flavio Sanguinetti
*/
public class WeaponCache extends Container implements IUsable, IInventory {
EquipmentManager inventory;
public WeaponCache() {
inventory = new EquipmentManager();
}
@Override
public boolean use(Actor actor)
{
return false;
}
public void pickup(Equipment equipment) {
inventory.addEquipment(equipment);
}
/**
* Class Name: transferAllEquipment <br>
* Class Purpose: Takes a parameter and counts the equipment and makes the other size = to, runs a for-loop until the next parameter<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @author Flavio Sanguinetti
*/
public void transferAllEquipmentFrom(IInventory other) {
int otherSize = other.countEquipment();
for (int i = 0; i < otherSize; i++) {
pickup(other.getEquipment(i));
}
other.dropAllEquipment();
/**
* Class Name: countArmor <br>
* Class Purpose: looks at inventory and is supposed to count/return armor count<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @author Flavio Sanguinetti
*/
}
public int countArmor() {
return inventory.countArmor();
}
/**
* Class Name: countWeapons <br>
* Class Purpose: return weapon count<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @author Flavio Sanguinetti
*/
public int countWeapons() {
return inventory.countWeapons();
}
/**
* Class Name: countConsumables<br>
* Class Purpose: return consumables count<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @author Flavio Sanguinetti
*/
public int countConsumables() {
return inventory.countConsumables();
}
/**
* Class Name: countEquipment <br>
* Class Purpose: return equipment count<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @return countEquipment
* @author Flavio Sanguinetti
*/
public int countEquipment() {
return countEquipment();
}
/**
* Class Name: getEquipmentList <br>
* Class Purpose: get EquipmentList<br>
*
* <hr>
* Date created: 11-30-2020
* Date last modified: 12-02-2020
* @return EquipmentList
* @author Flavio Sanguinetti
*/
public String getEquipmentList() {
return inventory.getEquipmentList();
}
public String getEquipmentInfo(int index) {
return inventory.getEquipmentDetails(index);
}
public Equipment getEquipment(int index) {
return inventory.getEquipment(index);
}
public void dropEquipment(int index) {
inventory.removeEquipment(index);
}
public void dropAllEquipment() {
inventory.clearAll();
}
}
|
/*
* Copyright 2013-2018 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.ecs.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Details on a volume mount point that is used in a container definition.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/MountPoint" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MountPoint implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of task
* definition <code>volume</code>.
* </p>
*/
private String sourceVolume;
/**
* <p>
* The path on the container to mount the host volume at.
* </p>
*/
private String containerPath;
/**
* <p>
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* </p>
*/
private Boolean readOnly;
/**
* <p>
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of task
* definition <code>volume</code>.
* </p>
*
* @param sourceVolume
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of
* task definition <code>volume</code>.
*/
public void setSourceVolume(String sourceVolume) {
this.sourceVolume = sourceVolume;
}
/**
* <p>
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of task
* definition <code>volume</code>.
* </p>
*
* @return The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of
* task definition <code>volume</code>.
*/
public String getSourceVolume() {
return this.sourceVolume;
}
/**
* <p>
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of task
* definition <code>volume</code>.
* </p>
*
* @param sourceVolume
* The name of the volume to mount. Must be a volume name referenced in the <code>name</code> parameter of
* task definition <code>volume</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MountPoint withSourceVolume(String sourceVolume) {
setSourceVolume(sourceVolume);
return this;
}
/**
* <p>
* The path on the container to mount the host volume at.
* </p>
*
* @param containerPath
* The path on the container to mount the host volume at.
*/
public void setContainerPath(String containerPath) {
this.containerPath = containerPath;
}
/**
* <p>
* The path on the container to mount the host volume at.
* </p>
*
* @return The path on the container to mount the host volume at.
*/
public String getContainerPath() {
return this.containerPath;
}
/**
* <p>
* The path on the container to mount the host volume at.
* </p>
*
* @param containerPath
* The path on the container to mount the host volume at.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MountPoint withContainerPath(String containerPath) {
setContainerPath(containerPath);
return this;
}
/**
* <p>
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* </p>
*
* @param readOnly
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
*/
public void setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
}
/**
* <p>
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* </p>
*
* @return If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
*/
public Boolean getReadOnly() {
return this.readOnly;
}
/**
* <p>
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* </p>
*
* @param readOnly
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MountPoint withReadOnly(Boolean readOnly) {
setReadOnly(readOnly);
return this;
}
/**
* <p>
* If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
* </p>
*
* @return If this value is <code>true</code>, the container has read-only access to the volume. If this value is
* <code>false</code>, then the container can write to the volume. The default value is <code>false</code>.
*/
public Boolean isReadOnly() {
return this.readOnly;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSourceVolume() != null)
sb.append("SourceVolume: ").append(getSourceVolume()).append(",");
if (getContainerPath() != null)
sb.append("ContainerPath: ").append(getContainerPath()).append(",");
if (getReadOnly() != null)
sb.append("ReadOnly: ").append(getReadOnly());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof MountPoint == false)
return false;
MountPoint other = (MountPoint) obj;
if (other.getSourceVolume() == null ^ this.getSourceVolume() == null)
return false;
if (other.getSourceVolume() != null && other.getSourceVolume().equals(this.getSourceVolume()) == false)
return false;
if (other.getContainerPath() == null ^ this.getContainerPath() == null)
return false;
if (other.getContainerPath() != null && other.getContainerPath().equals(this.getContainerPath()) == false)
return false;
if (other.getReadOnly() == null ^ this.getReadOnly() == null)
return false;
if (other.getReadOnly() != null && other.getReadOnly().equals(this.getReadOnly()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSourceVolume() == null) ? 0 : getSourceVolume().hashCode());
hashCode = prime * hashCode + ((getContainerPath() == null) ? 0 : getContainerPath().hashCode());
hashCode = prime * hashCode + ((getReadOnly() == null) ? 0 : getReadOnly().hashCode());
return hashCode;
}
@Override
public MountPoint clone() {
try {
return (MountPoint) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.ecs.model.transform.MountPointMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package com.alibaba.excel.metadata.csv;
import java.io.Closeable;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.enums.NumericCellTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.AutoFilter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellRange;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Footer;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PaneInformation;
/**
* csv sheet
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CsvSheet implements Sheet, Closeable {
/**
* workbook
*/
private CsvWorkbook csvWorkbook;
/**
* output
*/
private Appendable out;
/**
* row cache
*/
private Integer rowCacheCount;
/**
* format
*/
public CSVFormat csvFormat;
/**
* last row index
*/
private Integer lastRowIndex;
/**
* row cache
*/
private List<CsvRow> rowCache;
/**
* csv printer
*/
private CSVPrinter csvPrinter;
public CsvSheet(CsvWorkbook csvWorkbook, Appendable out) {
this.csvWorkbook = csvWorkbook;
this.out = out;
this.rowCacheCount = 3000;
this.csvFormat = CSVFormat.DEFAULT;
this.lastRowIndex = -1;
}
@Override
public Row createRow(int rownum) {
// Initialize the data when the row is first created
initSheet();
lastRowIndex++;
assert rownum == lastRowIndex : "csv create row must be in order.";
printData();
CsvRow csvRow = new CsvRow(csvWorkbook, this, rownum);
rowCache.add(csvRow);
return csvRow;
}
private void initSheet() {
if (csvPrinter != null) {
return;
}
rowCache = ListUtils.newArrayListWithExpectedSize(rowCacheCount);
try {
csvPrinter = csvFormat.print(out);
} catch (IOException e) {
throw new ExcelGenerateException(e);
}
}
@Override
public void removeRow(Row row) {
throw new UnsupportedOperationException("csv cannot move row.");
}
@Override
public Row getRow(int rownum) {
int actualRowIndex = rownum - (lastRowIndex - rowCache.size()) - 1;
if (actualRowIndex < 0 || actualRowIndex > rowCache.size() - 1) {
throw new UnsupportedOperationException("The current data does not exist or has been flushed to disk\n.");
}
return rowCache.get(actualRowIndex);
}
@Override
public int getPhysicalNumberOfRows() {
return lastRowIndex - rowCache.size();
}
@Override
public int getFirstRowNum() {
if (lastRowIndex < 0) {
return -1;
}
return 0;
}
@Override
public int getLastRowNum() {
return lastRowIndex;
}
@Override
public void setColumnHidden(int columnIndex, boolean hidden) {
}
@Override
public boolean isColumnHidden(int columnIndex) {
return false;
}
@Override
public void setRightToLeft(boolean value) {
}
@Override
public boolean isRightToLeft() {
return false;
}
@Override
public void setColumnWidth(int columnIndex, int width) {
}
@Override
public int getColumnWidth(int columnIndex) {
return 0;
}
@Override
public float getColumnWidthInPixels(int columnIndex) {
return 0;
}
@Override
public void setDefaultColumnWidth(int width) {
}
@Override
public int getDefaultColumnWidth() {
return 0;
}
@Override
public short getDefaultRowHeight() {
return 0;
}
@Override
public float getDefaultRowHeightInPoints() {
return 0;
}
@Override
public void setDefaultRowHeight(short height) {
}
@Override
public void setDefaultRowHeightInPoints(float height) {
}
@Override
public CellStyle getColumnStyle(int column) {
return null;
}
@Override
public int addMergedRegion(CellRangeAddress region) {
return 0;
}
@Override
public int addMergedRegionUnsafe(CellRangeAddress region) {
return 0;
}
@Override
public void validateMergedRegions() {
}
@Override
public void setVerticallyCenter(boolean value) {
}
@Override
public void setHorizontallyCenter(boolean value) {
}
@Override
public boolean getHorizontallyCenter() {
return false;
}
@Override
public boolean getVerticallyCenter() {
return false;
}
@Override
public void removeMergedRegion(int index) {
}
@Override
public void removeMergedRegions(Collection<Integer> indices) {
}
@Override
public int getNumMergedRegions() {
return 0;
}
@Override
public CellRangeAddress getMergedRegion(int index) {
return null;
}
@Override
public List<CellRangeAddress> getMergedRegions() {
return null;
}
@Override
public Iterator<Row> rowIterator() {
return (Iterator<Row>)(Iterator<? extends Row>)rowCache.iterator();
}
@Override
public void setForceFormulaRecalculation(boolean value) {
}
@Override
public boolean getForceFormulaRecalculation() {
return false;
}
@Override
public void setAutobreaks(boolean value) {
}
@Override
public void setDisplayGuts(boolean value) {
}
@Override
public void setDisplayZeros(boolean value) {
}
@Override
public boolean isDisplayZeros() {
return false;
}
@Override
public void setFitToPage(boolean value) {
}
@Override
public void setRowSumsBelow(boolean value) {
}
@Override
public void setRowSumsRight(boolean value) {
}
@Override
public boolean getAutobreaks() {
return false;
}
@Override
public boolean getDisplayGuts() {
return false;
}
@Override
public boolean getFitToPage() {
return false;
}
@Override
public boolean getRowSumsBelow() {
return false;
}
@Override
public boolean getRowSumsRight() {
return false;
}
@Override
public boolean isPrintGridlines() {
return false;
}
@Override
public void setPrintGridlines(boolean show) {
}
@Override
public boolean isPrintRowAndColumnHeadings() {
return false;
}
@Override
public void setPrintRowAndColumnHeadings(boolean show) {
}
@Override
public PrintSetup getPrintSetup() {
return null;
}
@Override
public Header getHeader() {
return null;
}
@Override
public Footer getFooter() {
return null;
}
@Override
public void setSelected(boolean value) {
}
@Override
public double getMargin(short margin) {
return 0;
}
@Override
public void setMargin(short margin, double size) {
}
@Override
public boolean getProtect() {
return false;
}
@Override
public void protectSheet(String password) {
}
@Override
public boolean getScenarioProtect() {
return false;
}
@Override
public void setZoom(int scale) {
}
@Override
public short getTopRow() {
return 0;
}
@Override
public short getLeftCol() {
return 0;
}
@Override
public void showInPane(int topRow, int leftCol) {
}
@Override
public void shiftRows(int startRow, int endRow, int n) {
}
@Override
public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
}
@Override
public void shiftColumns(int startColumn, int endColumn, int n) {
}
@Override
public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
}
@Override
public void createFreezePane(int colSplit, int rowSplit) {
}
@Override
public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
}
@Override
public PaneInformation getPaneInformation() {
return null;
}
@Override
public void setDisplayGridlines(boolean show) {
}
@Override
public boolean isDisplayGridlines() {
return false;
}
@Override
public void setDisplayFormulas(boolean show) {
}
@Override
public boolean isDisplayFormulas() {
return false;
}
@Override
public void setDisplayRowColHeadings(boolean show) {
}
@Override
public boolean isDisplayRowColHeadings() {
return false;
}
@Override
public void setRowBreak(int row) {
}
@Override
public boolean isRowBroken(int row) {
return false;
}
@Override
public void removeRowBreak(int row) {
}
@Override
public int[] getRowBreaks() {
return new int[0];
}
@Override
public int[] getColumnBreaks() {
return new int[0];
}
@Override
public void setColumnBreak(int column) {
}
@Override
public boolean isColumnBroken(int column) {
return false;
}
@Override
public void removeColumnBreak(int column) {
}
@Override
public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
}
@Override
public void groupColumn(int fromColumn, int toColumn) {
}
@Override
public void ungroupColumn(int fromColumn, int toColumn) {
}
@Override
public void groupRow(int fromRow, int toRow) {
}
@Override
public void ungroupRow(int fromRow, int toRow) {
}
@Override
public void setRowGroupCollapsed(int row, boolean collapse) {
}
@Override
public void setDefaultColumnStyle(int column, CellStyle style) {
}
@Override
public void autoSizeColumn(int column) {
}
@Override
public void autoSizeColumn(int column, boolean useMergedCells) {
}
@Override
public Comment getCellComment(CellAddress ref) {
return null;
}
@Override
public Map<CellAddress, ? extends Comment> getCellComments() {
return null;
}
@Override
public Drawing<?> getDrawingPatriarch() {
return null;
}
@Override
public Drawing<?> createDrawingPatriarch() {
return null;
}
@Override
public Workbook getWorkbook() {
return csvWorkbook;
}
@Override
public String getSheetName() {
return null;
}
@Override
public boolean isSelected() {
return false;
}
@Override
public CellRange<? extends Cell> setArrayFormula(
String formula, CellRangeAddress range) {
return null;
}
@Override
public CellRange<? extends Cell> removeArrayFormula(Cell cell) {
return null;
}
@Override
public DataValidationHelper getDataValidationHelper() {
return null;
}
@Override
public List<? extends DataValidation> getDataValidations() {
return null;
}
@Override
public void addValidationData(DataValidation dataValidation) {
}
@Override
public AutoFilter setAutoFilter(CellRangeAddress range) {
return null;
}
@Override
public SheetConditionalFormatting getSheetConditionalFormatting() {
return null;
}
@Override
public CellRangeAddress getRepeatingRows() {
return null;
}
@Override
public CellRangeAddress getRepeatingColumns() {
return null;
}
@Override
public void setRepeatingRows(CellRangeAddress rowRangeRef) {
}
@Override
public void setRepeatingColumns(CellRangeAddress columnRangeRef) {
}
@Override
public int getColumnOutlineLevel(int columnIndex) {
return 0;
}
@Override
public Hyperlink getHyperlink(int row, int column) {
return null;
}
@Override
public Hyperlink getHyperlink(CellAddress addr) {
return null;
}
@Override
public List<? extends Hyperlink> getHyperlinkList() {
return null;
}
@Override
public CellAddress getActiveCell() {
return null;
}
@Override
public void setActiveCell(CellAddress address) {
}
@Override
public Iterator<Row> iterator() {
return rowIterator();
}
@Override
public void close() throws IOException {
// Avoid empty sheets
initSheet();
flushData();
csvPrinter.flush();
csvPrinter.close();
}
public void printData() {
if (rowCache.size() >= rowCacheCount) {
flushData();
}
}
public void flushData() {
try {
for (CsvRow row : rowCache) {
Iterator<Cell> cellIterator = row.cellIterator();
int columnIndex = 0;
while (cellIterator.hasNext()) {
CsvCell csvCell = (CsvCell)cellIterator.next();
while (csvCell.getColumnIndex() > columnIndex++) {
csvPrinter.print(null);
}
csvPrinter.print(buildCellValue(csvCell));
}
csvPrinter.println();
}
rowCache.clear();
} catch (IOException e) {
throw new ExcelGenerateException(e);
}
}
private String buildCellValue(CsvCell csvCell) {
switch (csvCell.getCellType()) {
case STRING:
case ERROR:
return csvCell.getStringCellValue();
case NUMERIC:
Short dataFormat = null;
String dataFormatString = null;
if (csvCell.getCellStyle() != null) {
dataFormat = csvCell.getCellStyle().getDataFormat();
dataFormatString = csvCell.getCellStyle().getDataFormatString();
}
if (csvCell.getNumericCellType() == NumericCellTypeEnum.DATE) {
if (csvCell.getDateValue() == null) {
return null;
}
// date
if (dataFormat == null) {
dataFormatString = DateUtils.defaultDateFormat;
dataFormat = csvWorkbook.createDataFormat().getFormat(dataFormatString);
}
if (dataFormatString == null) {
dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat);
}
return NumberDataFormatterUtils.format(BigDecimal.valueOf(
DateUtil.getExcelDate(csvCell.getDateValue(), csvWorkbook.getUse1904windowing())),
dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(),
csvWorkbook.getUseScientificFormat());
} else {
if (csvCell.getNumberValue() == null) {
return null;
}
//number
if (dataFormat == null) {
dataFormat = BuiltinFormats.GENERAL;
dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat);
}
if (dataFormatString == null) {
dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat);
}
return NumberDataFormatterUtils.format(csvCell.getNumberValue(), dataFormat, dataFormatString,
csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(),
csvWorkbook.getUseScientificFormat());
}
case BOOLEAN:
return csvCell.getBooleanValue().toString();
case BLANK:
return StringUtils.EMPTY;
default:
return null;
}
}
}
|
/*
* Copyright (C) 2018-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.phive.ublbe.mock;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.CommonsHashMap;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.io.resource.ClassPathResource;
import com.helger.commons.io.resource.IReadableResource;
import com.helger.phive.api.executorset.VESID;
import com.helger.phive.api.executorset.ValidationExecutorSetRegistry;
import com.helger.phive.engine.mock.MockFile;
import com.helger.phive.engine.source.IValidationSourceXML;
import com.helger.phive.peppol.legacy.PeppolLegacyValidation;
import com.helger.phive.ublbe.UBLBEValidation;
@Immutable
@SuppressWarnings ("deprecation")
public final class CTestFiles
{
public static final ValidationExecutorSetRegistry <IValidationSourceXML> VES_REGISTRY = new ValidationExecutorSetRegistry <> ();
static
{
// Peppol is a prerequisite
PeppolLegacyValidation.init (VES_REGISTRY);
UBLBEValidation.initUBLBE (VES_REGISTRY);
}
private CTestFiles ()
{}
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <MockFile> getAllTestFiles ()
{
final ICommonsList <MockFile> ret = new CommonsArrayList <> ();
for (final VESID aESID : new VESID [] { UBLBEValidation.VID_EFFF_INVOICE,
UBLBEValidation.VID_EFFF_CREDIT_NOTE,
UBLBEValidation.VID_UBL_BE_INVOICE_100,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_100,
UBLBEValidation.VID_UBL_BE_INVOICE_110,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_110,
UBLBEValidation.VID_UBL_BE_INVOICE_120,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_120,
UBLBEValidation.VID_UBL_BE_INVOICE_123,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_123,
UBLBEValidation.VID_UBL_BE_INVOICE_125,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_125,
UBLBEValidation.VID_UBL_BE_INVOICE_126,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_126,
UBLBEValidation.VID_UBL_BE_INVOICE_127,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_127,
UBLBEValidation.VID_UBL_BE_INVOICE_128,
UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_128 })
for (final IReadableResource aRes : getAllMatchingTestFiles (aESID))
ret.add (MockFile.createGoodCase (aRes, aESID));
return ret;
}
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <? extends IReadableResource> getAllMatchingTestFiles (@Nonnull final VESID aVESID)
{
ValueEnforcer.notNull (aVESID, "VESID");
final ICommonsMap <VESID, ICommonsList <IReadableResource>> aMap = new CommonsHashMap <> ();
final String sPathPrefix = "/test-files/";
{
final String sPath = sPathPrefix + "3.0.0/";
aMap.put (UBLBEValidation.VID_EFFF_INVOICE,
new CommonsArrayList <> (new ClassPathResource (sPath + "efff_BE0827405743_V01-15000001-1.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml")));
aMap.put (UBLBEValidation.VID_EFFF_CREDIT_NOTE,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml")));
}
// 1.0.0
{
final String sPath = sPathPrefix + "en16931/v1/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_100,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000007.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000015.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_100,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.1.0
{
final String sPath = sPathPrefix + "en16931/v1.1/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_110,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 - Temporary.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000007.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000015.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_110,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.0
{
final String sPath = sPathPrefix + "en16931/v1.2/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_120,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 - Temporary.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000007.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000015.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_120,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.3
{
final String sPath = sPathPrefix + "en16931/v1.2.3/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_123,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000007.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000015.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000031.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_123,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.5
{
final String sPath = sPathPrefix + "en16931/v1.2.5/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_125,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000007.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000015.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000031.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_125,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.6
{
final String sPath = sPathPrefix + "en16931/v1.2.6/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_126,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000031.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000032.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_126,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.7
{
final String sPath = sPathPrefix + "en16931/v1.2.7/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_127,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000031.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000032.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_127,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
// 1.2.8
{
final String sPath = sPathPrefix + "en16931/v1.2.8/";
aMap.put (UBLBEValidation.VID_UBL_BE_INVOICE_128,
new CommonsArrayList <> (new ClassPathResource (sPath +
"UBLBE_BE0000000196_V01-15000001 - DocumentStatusCode Converted.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001 Full.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000001.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000003.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000004.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000005.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000006.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000008.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000009.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000010.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000012.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000013.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000016.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000017.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000018.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000019.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000020.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000021.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000022.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000023.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000025.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000026.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000027.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000028.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000029.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000030.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000031.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000032.xml")));
aMap.put (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_128,
new CommonsArrayList <> (new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000002.xml"),
new ClassPathResource (sPath + "UBLBE_BE0000000196_V01-15000024.xml")));
}
final ICommonsList <IReadableResource> ret = aMap.get (aVESID);
if (ret != null)
return ret;
// TODO work around
if (aVESID.equals (UBLBEValidation.VID_UBL_BE_INVOICE_110) || aVESID.equals (UBLBEValidation.VID_UBL_BE_CREDIT_NOTE_110))
return new CommonsArrayList <> ();
throw new IllegalArgumentException ("Invalid VESID: " + aVESID);
}
}
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.cmmn.test.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.flowable.cmmn.api.history.HistoricCaseInstance;
import org.flowable.cmmn.api.history.HistoricMilestoneInstance;
import org.flowable.cmmn.api.history.HistoricPlanItemInstance;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.CaseInstanceState;
import org.flowable.cmmn.api.runtime.PlanItemDefinitionType;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.api.runtime.UserEventListenerInstance;
import org.flowable.cmmn.engine.CmmnEngineConfiguration;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.cmmn.engine.test.CmmnDeployment;
import org.flowable.cmmn.test.impl.CustomCmmnConfigurationFlowableTestCase;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.api.scope.ScopeTypes;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.entitylink.api.EntityLinkType;
import org.flowable.entitylink.api.history.HistoricEntityLink;
import org.flowable.entitylink.api.history.HistoricEntityLinkService;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.identitylink.api.IdentityLinkType;
import org.flowable.identitylink.api.history.HistoricIdentityLink;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskLogEntry;
import org.flowable.task.api.history.HistoricTaskLogEntryBuilder;
import org.flowable.task.api.history.HistoricTaskLogEntryType;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.junit.Test;
/**
* @author Joram Barrez
*/
public class AsyncCmmnHistoryTest extends CustomCmmnConfigurationFlowableTestCase {
@Override
protected String getEngineName() {
return "AsyncCmmnHistoryTest";
}
@Override
protected void configureConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) {
cmmnEngineConfiguration.setAsyncHistoryEnabled(true);
cmmnEngineConfiguration.setAsyncExecutorActivate(false);
cmmnEngineConfiguration.setAsyncHistoryJsonGroupingEnabled(true);
cmmnEngineConfiguration.setAsyncHistoryJsonGroupingThreshold(1);
cmmnEngineConfiguration.setAsyncFailedJobWaitTime(1);
cmmnEngineConfiguration.setDefaultFailedJobWaitTime(1);
cmmnEngineConfiguration.setAsyncHistoryExecutorNumberOfRetries(10);
cmmnEngineConfiguration.setAsyncHistoryExecutorDefaultAsyncJobAcquireWaitTime(1000);
}
@Test
@CmmnDeployment
public void testCaseInstanceStartAndEnd() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneHumanTaskCase")
.name("someName")
.businessKey("someBusinessKey")
.start();
assertEquals(0, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
HistoricCaseInstance historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery().singleResult();
assertEquals(caseInstance.getId(), historicCaseInstance.getId());
assertEquals("someName", historicCaseInstance.getName());
assertNull(historicCaseInstance.getParentId());
assertEquals("someBusinessKey", historicCaseInstance.getBusinessKey());
assertEquals(caseInstance.getCaseDefinitionId(), historicCaseInstance.getCaseDefinitionId());
assertEquals(CaseInstanceState.ACTIVE, historicCaseInstance.getState());
assertNotNull(historicCaseInstance.getStartTime());
assertNull(historicCaseInstance.getEndTime());
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertCaseInstanceEnded(caseInstance);
historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery().singleResult();
assertEquals(caseInstance.getId(), historicCaseInstance.getId());
assertEquals("someName", historicCaseInstance.getName());
assertNull(historicCaseInstance.getParentId());
assertEquals("someBusinessKey", historicCaseInstance.getBusinessKey());
assertEquals(caseInstance.getCaseDefinitionId(), historicCaseInstance.getCaseDefinitionId());
assertEquals(CaseInstanceState.COMPLETED, historicCaseInstance.getState());
assertNotNull(historicCaseInstance.getStartTime());
assertNotNull(historicCaseInstance.getEndTime());
}
@Test
@CmmnDeployment
public void testHistoricCaseInstanceDeleted() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneHumanTaskCase")
.name("someName")
.businessKey("someBusinessKey")
.variable("test", "test")
.start();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnRuntimeService.createPlanItemInstanceQuery().count());
assertEquals(1, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
cmmnHistoryService.deleteHistoricCaseInstance(caseInstance.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
}
@Test
public void testCreateTaskHistory() {
Task task = cmmnTaskService.createTaskBuilder().id("task1").create();
assertNull(cmmnHistoryService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertNotNull(cmmnHistoryService.createHistoricTaskInstanceQuery().taskId(task.getId()).singleResult());
assertEquals("task1", task.getId());
cmmnTaskService.deleteTask(task.getId(), true);
}
@Test
@CmmnDeployment
public void testMilestoneReached() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("caseWithOneMilestone").start();
assertEquals(1, cmmnRuntimeService.createMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
assertEquals(0, cmmnHistoryService.createHistoricMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricMilestoneInstanceQuery().milestoneInstanceCaseInstanceId(caseInstance.getId()).count());
HistoricMilestoneInstance historicMilestoneInstance = cmmnHistoryService.createHistoricMilestoneInstanceQuery()
.milestoneInstanceCaseInstanceId(caseInstance.getId())
.singleResult();
assertEquals("xyzMilestone", historicMilestoneInstance.getName());
assertEquals("milestonePlanItem1", historicMilestoneInstance.getElementId());
assertEquals(caseInstance.getId(), historicMilestoneInstance.getCaseInstanceId());
assertEquals(caseInstance.getCaseDefinitionId(), historicMilestoneInstance.getCaseDefinitionId());
assertNotNull(historicMilestoneInstance.getTimeStamp());
}
@Test
@CmmnDeployment
public void testIdentityLinks() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("caseWithOneMilestone").start();
cmmnRuntimeService.addUserIdentityLink(caseInstance.getId(), "someUser", IdentityLinkType.PARTICIPANT);
assertEquals(0, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
cmmnRuntimeService.deleteUserIdentityLink(caseInstance.getId(), "someUser", IdentityLinkType.PARTICIPANT);
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnHistoryService.getHistoricIdentityLinksForCaseInstance(caseInstance.getId()).size());
}
@Test
@CmmnDeployment
public void testVariables() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
assertEquals(0, cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).count());
cmmnRuntimeService.setVariable(caseInstance.getId(), "test", "hello world");
cmmnRuntimeService.setVariable(caseInstance.getId(), "test2", 2);
// Create
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(2, cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).count());
HistoricVariableInstance historicVariableInstance = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult();
assertEquals("test", historicVariableInstance.getVariableName());
assertEquals(caseInstance.getId(), historicVariableInstance.getScopeId());
assertEquals(ScopeTypes.CMMN, historicVariableInstance.getScopeType());
assertEquals("hello world", historicVariableInstance.getValue());
assertNotNull(historicVariableInstance.getCreateTime());
assertNotNull(historicVariableInstance.getLastUpdatedTime());
historicVariableInstance = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test2").singleResult();
assertEquals("test2", historicVariableInstance.getVariableName());
assertEquals(caseInstance.getId(), historicVariableInstance.getScopeId());
assertNull(historicVariableInstance.getSubScopeId());
assertEquals(ScopeTypes.CMMN, historicVariableInstance.getScopeType());
assertEquals(2, historicVariableInstance.getValue());
assertNotNull(historicVariableInstance.getCreateTime());
assertNotNull(historicVariableInstance.getLastUpdatedTime());
// Update
try {
Thread.sleep(16); // wait time for diff in last updated time
} catch (InterruptedException e) {
e.printStackTrace();
}
cmmnRuntimeService.setVariable(caseInstance.getId(), "test", "hello test");
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricVariableInstance updatedHistoricVariable = cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult();
assertEquals("test", updatedHistoricVariable.getVariableName());
assertEquals(caseInstance.getId(), updatedHistoricVariable.getScopeId());
assertNull(updatedHistoricVariable.getSubScopeId());
assertEquals(ScopeTypes.CMMN, updatedHistoricVariable.getScopeType());
assertEquals("hello test", updatedHistoricVariable.getValue());
assertNotNull(updatedHistoricVariable.getCreateTime());
assertNotNull(updatedHistoricVariable.getLastUpdatedTime());
assertNotEquals(updatedHistoricVariable.getLastUpdatedTime(), historicVariableInstance.getLastUpdatedTime());
// Delete
cmmnRuntimeService.removeVariable(caseInstance.getId(), "test");
waitForAsyncHistoryExecutorToProcessAllJobs();
assertNull(cmmnHistoryService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstance.getId()).variableName("test").singleResult());
}
@Test
@CmmnDeployment
public void testHumanTask() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
assertEquals(1, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
assertEquals(0, cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).count());
// Create
HistoricTaskInstance historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals("The Task", historicTaskInstance.getName());
assertEquals("johnDoe", historicTaskInstance.getAssignee());
assertEquals(caseInstance.getId(), historicTaskInstance.getScopeId());
assertEquals(caseInstance.getCaseDefinitionId(), historicTaskInstance.getScopeDefinitionId());
assertEquals(ScopeTypes.CMMN, historicTaskInstance.getScopeType());
assertNotNull(historicTaskInstance.getCreateTime());
// Update
cmmnTaskService.setAssignee(historicTaskInstance.getId(), "janeDoe");
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals("The Task", historicTaskInstance.getName());
assertEquals("janeDoe", historicTaskInstance.getAssignee());
cmmnTaskService.setPriority(historicTaskInstance.getId(), 99);
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals(99, historicTaskInstance.getPriority());
assertNull(historicTaskInstance.getEndTime());
List<PlanItemInstance> planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery()
.planItemDefinitionType(PlanItemDefinitionType.HUMAN_TASK)
.orderByName().asc()
.list();
assertThat(planItemInstances).extracting(PlanItemInstance::getName).containsExactly("The Task");
assertThat(planItemInstances).extracting(PlanItemInstance::getCreateTime).isNotNull();
// Complete
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
assertEquals(0, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertNotNull(historicTaskInstance.getEndTime());
List<HistoricPlanItemInstance> historicPlanItemInstances = cmmnHistoryService.createHistoricPlanItemInstanceQuery()
.planItemInstanceDefinitionType(PlanItemDefinitionType.HUMAN_TASK)
.list();
assertThat(historicPlanItemInstances).extracting(HistoricPlanItemInstance::getName).containsExactly("The Task");
assertThat(historicPlanItemInstances).extracting(HistoricPlanItemInstance::getCreateTime).isNotNull();
}
@Test
@CmmnDeployment
public void testHumanTaskWithCandidateUsersAndGroups() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(task).isNotNull();
assertThat(cmmnTaskService.getIdentityLinksForTask(task.getId()))
.extracting(IdentityLink::getType, IdentityLink::getUserId, IdentityLink::getGroupId)
.containsExactlyInAnyOrder(
tuple("assignee", "johnDoe", null),
tuple("candidate", "user1", null),
tuple("candidate", null, "group1"),
tuple("candidate", null, "group2")
);
assertThatThrownBy(() -> cmmnHistoryService.getHistoricIdentityLinksForTask(task.getId()))
.isInstanceOf(FlowableObjectNotFoundException.class)
.hasMessageContaining("No historic task exists");
waitForAsyncHistoryExecutorToProcessAllJobs();
assertThat(cmmnHistoryService.getHistoricIdentityLinksForTask(task.getId()))
.extracting(HistoricIdentityLink::getType, HistoricIdentityLink::getUserId, HistoricIdentityLink::getGroupId)
.containsExactlyInAnyOrder(
tuple("assignee", "johnDoe", null),
tuple("candidate", "user1", null),
tuple("candidate", null, "group1"),
tuple("candidate", null, "group2")
);
}
@Test
@CmmnDeployment(resources = "org/flowable/cmmn/test/async/AsyncCmmnHistoryTest.testHumanTask.cmmn")
public void testHumanTaskWithNameDueDateAndDescription() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").start();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(task).isNotNull();
task.setName("Test name");
task.setDescription("Test description");
cmmnTaskService.saveTask(task);
waitForAsyncHistoryExecutorToProcessAllJobs();
// Create
HistoricTaskInstance historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance).isNotNull();
assertThat(historicTaskInstance.getName()).isEqualTo("Test name");
assertThat(historicTaskInstance.getDescription()).isEqualTo("Test description");
assertThat(historicTaskInstance.getDueDate()).isNull();
// Set due date
Date dueDate = new Date();
cmmnTaskService.setDueDate(task.getId(), dueDate);
waitForAsyncHistoryExecutorToProcessAllJobs();
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance.getDueDate()).isEqualTo(dueDate);
// Update name and description to null
task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
task.setName(null);
task.setDescription(null);
cmmnTaskService.saveTask(task);
// Before the history jobs it has the old data
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance.getName()).isEqualTo("Test name");
assertThat(historicTaskInstance.getDescription()).isEqualTo("Test description");
waitForAsyncHistoryExecutorToProcessAllJobs();
// After the history jobs it has the new data
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance.getName()).isNull();
assertThat(historicTaskInstance.getDescription()).isNull();
// Update dueDate to null
cmmnTaskService.setDueDate(task.getId(), null);
// Before the history jobs it has the old data
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance.getDueDate()).isEqualTo(dueDate);
waitForAsyncHistoryExecutorToProcessAllJobs();
// After the history jobs it has the new data
historicTaskInstance = cmmnHistoryService.createHistoricTaskInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(historicTaskInstance.getDueDate()).isNull();
}
@Test
@CmmnDeployment
public void testPlanItemInstances() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testSimpleCaseFlow").start();
List<PlanItemInstance> currentPlanItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).list();
assertEquals(3, currentPlanItemInstances.size());
assertEquals(0, cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(3, cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).count());
List<HistoricPlanItemInstance> historicPlanItemInstances = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceCaseInstanceId(caseInstance.getId()).list();
assertTrue(historicPlanItemInstances.stream().map(HistoricPlanItemInstance::getPlanItemDefinitionType).anyMatch(PlanItemDefinitionType.STAGE::equalsIgnoreCase));
assertTrue(historicPlanItemInstances.stream().map(HistoricPlanItemInstance::getPlanItemDefinitionType).anyMatch(PlanItemDefinitionType.MILESTONE::equalsIgnoreCase));
assertTrue(historicPlanItemInstances.stream().anyMatch(h -> "task".equalsIgnoreCase(h.getPlanItemDefinitionType()) && "planItemTaskA".equalsIgnoreCase(h.getElementId())));
for (HistoricPlanItemInstance historicPlanItemInstance : historicPlanItemInstances) {
assertEquals(caseInstance.getId(), historicPlanItemInstance.getCaseInstanceId());
assertEquals(caseInstance.getCaseDefinitionId(), historicPlanItemInstance.getCaseDefinitionId());
assertNotNull(historicPlanItemInstance.getElementId());
assertNotNull(historicPlanItemInstance.getCreateTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastDisabledTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNull(historicPlanItemInstance.getEntryCriterionId());
assertNull(historicPlanItemInstance.getExitCriterionId());
if (historicPlanItemInstance.getElementId().equals("planItemTaskA")) {
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
} else {
assertNull(historicPlanItemInstance.getLastEnabledTime());
}
}
// Disable task
PlanItemInstance task = cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceElementId("planItemTaskA").singleResult();
assertNotNull(task);
cmmnRuntimeService.disablePlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0, cmmnManagementService.createHistoryJobQuery().scopeType(ScopeTypes.CMMN).count());
assertEquals(0, cmmnManagementService.createDeadLetterJobQuery().scopeType(ScopeTypes.CMMN).count());
HistoricPlanItemInstance historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertEquals(PlanItemInstanceState.DISABLED, historicPlanItemInstance.getState());
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
assertNotNull(historicPlanItemInstance.getLastDisabledTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNotNull(historicPlanItemInstance.getLastUpdatedTime());
// Enable task
cmmnRuntimeService.enablePlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertEquals(PlanItemInstanceState.ENABLED, historicPlanItemInstance.getState());
assertNotNull(historicPlanItemInstance.getLastEnabledTime());
assertNotNull(historicPlanItemInstance.getLastAvailableTime());
assertNotNull(historicPlanItemInstance.getLastDisabledTime());
assertNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
assertNull(historicPlanItemInstance.getLastSuspendedTime());
assertNull(historicPlanItemInstance.getExitTime());
assertNull(historicPlanItemInstance.getTerminatedTime());
assertNotNull(historicPlanItemInstance.getLastUpdatedTime());
// Manually enable
cmmnRuntimeService.startPlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
historicPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertNotNull(historicPlanItemInstance.getLastStartedTime());
assertNull(historicPlanItemInstance.getEndedTime());
// Complete task
Calendar clockCal = cmmnEngineConfiguration.getClock().getCurrentCalendar();
clockCal.add(Calendar.HOUR, 1);
setClockTo(clockCal.getTime());
cmmnRuntimeService.triggerPlanItemInstance(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricPlanItemInstance completedHistoricPlanItemInstance = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceId(task.getId()).singleResult();
assertNotNull(completedHistoricPlanItemInstance.getEndedTime());
assertNotNull(completedHistoricPlanItemInstance.getLastEnabledTime());
assertNotNull(completedHistoricPlanItemInstance.getLastDisabledTime());
assertNotNull(completedHistoricPlanItemInstance.getLastAvailableTime());
assertNotNull(completedHistoricPlanItemInstance.getLastStartedTime());
assertNull(completedHistoricPlanItemInstance.getLastSuspendedTime());
assertNull(completedHistoricPlanItemInstance.getExitTime());
assertNull(completedHistoricPlanItemInstance.getTerminatedTime());
assertNotNull(completedHistoricPlanItemInstance.getLastUpdatedTime());
assertTrue(historicPlanItemInstance.getLastUpdatedTime().before(completedHistoricPlanItemInstance.getLastUpdatedTime()));
cmmnEngineConfiguration.getClock().reset();
}
@Test
@CmmnDeployment
public void testCriterionStoredOnPlanItemInstance() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testCriterions").start();
// Executing the tasks triggers the entry criterion
Task taskB = cmmnTaskService.createTaskQuery().taskName("B").singleResult();
cmmnTaskService.complete(taskB.getId());
assertEquals("entryA2", cmmnRuntimeService.createPlanItemInstanceQuery().planItemInstanceName("C").singleResult().getEntryCriterionId());
waitForAsyncHistoryExecutorToProcessAllJobs();
HistoricPlanItemInstance planItemInstanceC = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceName("C").singleResult();
assertEquals("entryA2", planItemInstanceC.getEntryCriterionId());
assertNull(planItemInstanceC.getExitCriterionId());
// Completing will set the exit criterion
UserEventListenerInstance userEventListenerInstance = cmmnRuntimeService.createUserEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnRuntimeService.completeUserEventListenerInstance(userEventListenerInstance.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
planItemInstanceC = cmmnHistoryService.createHistoricPlanItemInstanceQuery().planItemInstanceName("C").singleResult();
assertEquals("entryA2", planItemInstanceC.getEntryCriterionId());
assertEquals("stop", planItemInstanceC.getExitCriterionId());
}
@Test
public void createUserTaskLogEntity() {
HistoricTaskLogEntryBuilder historicTaskLogEntryBuilder = cmmnHistoryService.createHistoricTaskLogEntryBuilder();
Date todayDate = new Date();
historicTaskLogEntryBuilder.taskId("1");
historicTaskLogEntryBuilder.type("testType");
historicTaskLogEntryBuilder.userId("testUserId");
historicTaskLogEntryBuilder.data("testData");
historicTaskLogEntryBuilder.scopeId("testScopeId");
historicTaskLogEntryBuilder.scopeType("testScopeType");
historicTaskLogEntryBuilder.scopeDefinitionId("testDefinitionId");
historicTaskLogEntryBuilder.subScopeId("testSubScopeId");
historicTaskLogEntryBuilder.timeStamp(todayDate);
historicTaskLogEntryBuilder.tenantId("testTenant");
historicTaskLogEntryBuilder.create();
HistoricTaskLogEntry historicTaskLogEntry = null;
try {
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").count());
historicTaskLogEntry = cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId("1").singleResult();
assertTrue(historicTaskLogEntry.getLogNumber() > 0);
assertEquals("1", historicTaskLogEntry.getTaskId());
assertEquals("testType", historicTaskLogEntry.getType());
assertEquals("testUserId", historicTaskLogEntry.getUserId());
assertEquals("testScopeId", historicTaskLogEntry.getScopeId());
assertEquals("testScopeType", historicTaskLogEntry.getScopeType());
assertEquals("testDefinitionId", historicTaskLogEntry.getScopeDefinitionId());
assertEquals("testSubScopeId", historicTaskLogEntry.getSubScopeId());
assertEquals("testData", historicTaskLogEntry.getData());
assertTrue(historicTaskLogEntry.getLogNumber() > 0l);
assertNotNull(historicTaskLogEntry.getTimeStamp());
assertEquals("testTenant", historicTaskLogEntry.getTenantId());
} finally {
if (historicTaskLogEntry != null) {
cmmnHistoryService.deleteHistoricTaskLogEntry(historicTaskLogEntry.getLogNumber());
waitForAsyncHistoryExecutorToProcessAllJobs();
}
}
}
@Test
public void createCmmnAsynchUserTaskLogEntries() {
CaseInstance caseInstance = deployAndStartOneHumanTaskCaseModel();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
task.setName("newName");
task.setPriority(0);
cmmnTaskService.saveTask(task);
cmmnTaskService.setAssignee(task.getId(), "newAssignee");
cmmnTaskService.setOwner(task.getId(), "newOwner");
cmmnTaskService.setDueDate(task.getId(), new Date());
cmmnTaskService.addUserIdentityLink(task.getId(), "testUser", IdentityLinkType.PARTICIPANT);
cmmnTaskService.addGroupIdentityLink(task.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
cmmnTaskService.deleteUserIdentityLink(task.getId(), "testUser", IdentityLinkType.PARTICIPANT);
cmmnTaskService.deleteGroupIdentityLink(task.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
cmmnTaskService.complete(task.getId());
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().count());
assertEquals(10l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(11l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).count());
assertEquals(1l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_CREATED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_NAME_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_PRIORITY_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_ASSIGNEE_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_OWNER_CHANGED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_DUEDATE_CHANGED.name()).count());
assertEquals(2l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_IDENTITY_LINK_ADDED.name()).count());
assertEquals(2l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_IDENTITY_LINK_REMOVED.name()).count());
assertEquals(1l,
cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).type(HistoricTaskLogEntryType.USER_TASK_COMPLETED.name()).count());
}
@Test
public void deleteAsynchUserTaskLogEntries() {
CaseInstance caseInstance = deployAndStartOneHumanTaskCaseModel();
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().count());
assertEquals(1l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
List<HistoricTaskLogEntry> historicTaskLogEntries = cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).list();
assertEquals(1l, historicTaskLogEntries.size());
cmmnHistoryService.deleteHistoricTaskLogEntry(historicTaskLogEntries.get(0).getLogNumber());
assertEquals(1l, cmmnManagementService.createHistoryJobQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(0l, cmmnHistoryService.createHistoricTaskLogEntryQuery().taskId(task.getId()).count());
}
@Test
@CmmnDeployment
public void createRootEntityLink() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey("oneHumanTaskCase")
.name("someName")
.businessKey("someBusinessKey")
.start();
assertEquals(0, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertEquals(1, cmmnHistoryService.createHistoricCaseInstanceQuery().count());
Task task = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
cmmnTaskService.complete(task.getId());
waitForAsyncHistoryExecutorToProcessAllJobs();
assertCaseInstanceEnded(caseInstance);
CommandExecutor commandExecutor = cmmnEngine.getCmmnEngineConfiguration().getCommandExecutor();
List<HistoricEntityLink> entityLinksByScopeIdAndType = commandExecutor.execute(commandContext -> {
HistoricEntityLinkService historicEntityLinkService = CommandContextUtil.getHistoricEntityLinkService(commandContext);
return historicEntityLinkService.findHistoricEntityLinksByReferenceScopeIdAndType(task.getId(), ScopeTypes.TASK, EntityLinkType.CHILD);
});
assertEquals(1, entityLinksByScopeIdAndType.size());
assertEquals("root", entityLinksByScopeIdAndType.get(0).getHierarchyType());
}
}
|
package com.addusername.pmddmm_eval2.interfaces;
public interface ModelOps {
void getLastComic();
void getComic(int num);
void getHistory();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.