text
stringlengths
7
1.01M
class Test { String foo() { return null; } void bar() { if (foo() != null) { foo().toLowerCase()<caret> } } }
package havis.tools.jibx; import havis.tools.jibx.AST.Pair; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.jibx.binding.model.ElementBase; import org.jibx.schema.codegen.IClassHolder; import org.jibx.schema.codegen.extend.NameMatchDecoratorBase; /** * <p> * Decorates the class by adding an additional constructor to set the initial * value of fields. Value of <b>params</b> should be a comma separated list of * <i>type</i> and <i>name</i> pairs. <br /> * </p> * <p> * i.e. set <b>params</b> to <br /> * <br /> * <code> * <i>int</i> id, {@link String} name * </code> <br /> * <br /> * to add a constructor which set the initial value of <i>id</i> and <i>name</i> * for a new instance.<br /> * The implementation will add the default constructor, too. Set <b>empty</b> to * <i>false</i> avoid the behavior. * </p> */ public class ConstructorDecorator extends NameMatchDecoratorBase { private final AST ast = new AST(); private boolean empty = true; private String params; public void setEmpty(boolean empty) { this.empty = empty; } public void setParams(String params) { this.params = params; } public void finish(ElementBase binding, IClassHolder holder) { } private void addEmptyConstructor(IClassHolder holder) { holder.addMethod(ast.newConstructorDeclaration(holder.getName(), Modifier.PUBLIC, ast.newBlock())); } @SuppressWarnings("unchecked") private void addConstructor(IClassHolder holder) { MethodDeclaration method = ast.newConstructorDeclaration( holder.getName(), Modifier.PUBLIC, ast.newBlock()); Block block = ast.newBlock(); if (params != null) { for (String param : params.trim().split(",")) { Pair pair = ast.new Pair(param); method.parameters().add( ast.newSingleVariableDeclaration(pair.getType(), pair.getName())); block.statements().add( ast.newExpressionStatement(ast.newAssignment(ast .newFieldAccess(ast.newThisExpression(), pair.getName()), ast.newSimpleName(pair .getName())))); } } method.setBody(block); holder.addMethod(method); } public void start(IClassHolder holder) { if (matchName(holder.getName())) { if (empty) addEmptyConstructor(holder); addConstructor(holder); } } public void valueAdded(String basename, boolean collect, String type, FieldDeclaration field, MethodDeclaration getmeth, MethodDeclaration setmeth, String descript, IClassHolder holder) { } }
package net.praaly.habitats.setup.items.equipments; import net.minecraft.item.IItemTier; import net.minecraft.item.PickaxeItem; public class customPickaxe extends PickaxeItem { public customPickaxe(IItemTier tier, int attackDamage, float attackSpeedIn, Properties builder) { super(tier, attackDamage, attackSpeedIn, builder); } }
package com.pearadmin.modules.sys.mapper; import com.pearadmin.modules.sys.domain.SysPower; import com.pearadmin.modules.sys.domain.SysMenu; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Describe: 系统权限接口 * Author: 就 眠 仪 式 * CreateTime: 2019/10/23 * */ @Mapper public interface SysPowerMapper { /** * Describe: 根据 SysPower 条件查询权限 * Param: SysPower * Return: SysPower * */ List<SysPower> selectList(SysPower sysPower); /** * Describe: 保存 SysPower 权限数据 * Param: SysPower * Return: SysPower * */ Integer insert(SysPower sysPower); /** * Describe: 根据 Id 查询权限 * Param: id * Return: SysPower * */ SysPower selectById(@Param("id") String id); /** * Describe: 根据 username 查询用户权限 * Param: username * Return: SysPower * */ List<SysPower> selectByUsername(String username); /** * Describe: 根据 username 查询用户菜单 * Param: username * Return: ResuMenu * */ List<SysMenu> selectMenuByUsername(String username); /** * Describe: 修改权限信息 * Param: SysPower * Return: int * */ int updateById(SysPower sysPower); /** * Describe: 删除权限信息 * Param: id * Return: int * */ int deleteById(String id); }
package javision; import java.awt.image.BufferedImage; public class EdgeDetection { private int getGreyScale(int rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = (rgb) & 0xff; // from https://en.wikipedia.org/wiki/Grayscale, calculating luminance int grey = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b); return grey; } public BufferedImage sobel(BufferedImage base) { int imWidth = base.getWidth(); int imHeight = base.getHeight(); int maxGrad = -1; int[][] edgeColors = new int[imWidth][imHeight]; for (int x = 1; x < imWidth - 1; x++) { for (int y = 1; y < imHeight - 1; y++) { int m00 = getGreyScale(base.getRGB(x - 1, y - 1)); int m01 = getGreyScale(base.getRGB(x - 1, y)); int m02 = getGreyScale(base.getRGB(x - 1, y + 1)); int m10 = getGreyScale(base.getRGB(x, y - 1)); int m11 = getGreyScale(base.getRGB(x, y)); int m12 = getGreyScale(base.getRGB(x, y + 1)); int m20 = getGreyScale(base.getRGB(x + 1, y - 1)); int m21 = getGreyScale(base.getRGB(x + 1, y)); int m22 = getGreyScale(base.getRGB(x + 1, y + 1)); // sobel's kernel int s1 = ((-1 * m00) + (0 * m01) + (1 * m02)) + ((-2 * m10) + (0 * m11) + (2 * m12)) + ((-1 * m20) + (0 * m21) + (1 * m22)); int s2 = ((-1 * m00) + (-2 * m01) + (-1 * m02)) + ((0 * m10) + (0 * m11) + (0 * m12)) + ((1 * m20) + (2 * m21) + (1 * m22)); double mag = Math.sqrt((s1 * s1) + (s2 * s2)); if (maxGrad < (int) mag) { maxGrad = (int) mag; } edgeColors[x][y] = (int) mag; } } double scale = 255.0 / maxGrad; BufferedImage output = base; for (int x = 1; x < imWidth - 1; x++) { for (int y = 1; y < imHeight - 1; y++) { int edgeColor = edgeColors[x][y]; edgeColor = (int) (edgeColor * scale); edgeColor = 0xff000000 | (edgeColor << 16) | (edgeColor << 8) | edgeColor; output.setRGB(x, y, edgeColor); } } return output; } }
/* * Copyright 2020 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.gaffer.controller.handler; import com.google.gson.reflect.TypeToken; import io.kubernetes.client.openapi.ApiCallback; import io.kubernetes.client.openapi.ApiClient; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.ApiResponse; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodSpec; import io.kubernetes.client.openapi.models.V1PodStatus; import io.kubernetes.client.openapi.models.V1Secret; import io.kubernetes.client.openapi.models.V1SecretVolumeSource; import io.kubernetes.client.openapi.models.V1Status; import io.kubernetes.client.openapi.models.V1Volume; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.env.Environment; import uk.gov.gchq.gaffer.controller.HelmCommand; import uk.gov.gchq.gaffer.controller.factory.KubernetesObjectFactory; import uk.gov.gchq.gaffer.controller.model.v1.Gaffer; import java.lang.reflect.Type; import java.util.HashMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static uk.gov.gchq.gaffer.controller.util.Constants.GAAS_LABEL_VALUE; import static uk.gov.gchq.gaffer.controller.util.Constants.GAFFER_NAMESPACE_LABEL; import static uk.gov.gchq.gaffer.controller.util.Constants.GAFFER_NAME_LABEL; import static uk.gov.gchq.gaffer.controller.util.Constants.K8S_INSTANCE_LABEL; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_HELM_REPO; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_IMAGE; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_IMAGE_PULL_POLICY; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_NAMESPACE; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_RESTART_POLICY; import static uk.gov.gchq.gaffer.controller.util.Constants.WORKER_SERVICE_ACCOUNT_NAME; class DeploymentHandlerTest { private Environment environment; @BeforeEach public void beforeEach() { environment = mock(Environment.class); // default values when(environment.getProperty(WORKER_NAMESPACE)).thenReturn("gaffer-workers"); when(environment.getProperty(WORKER_IMAGE)).thenReturn("tzar/helm-kubectl:latest"); when(environment.getProperty(WORKER_IMAGE_PULL_POLICY)).thenReturn("IfNotPresent"); when(environment.getProperty(WORKER_RESTART_POLICY)).thenReturn("Never"); when(environment.getProperty(WORKER_SERVICE_ACCOUNT_NAME)).thenReturn("gaffer-workers"); when(environment.getProperty(WORKER_HELM_REPO)).thenReturn("https://gchq.github.io/gaffer-workers"); } @Test public void shouldCreateHelmDeploymentOnAdd() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); // Mimicking successful secret creation call when(client.buildCall(anyString(), anyString(), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); callback.onSuccess(invocationOnMock.getArgument(4), 200, null); return null; }); Type podType = new TypeToken<V1Pod>() { }.getType(); when(client.execute(null, podType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new V1Pod())); KubernetesObjectFactory kubernetesObjectFactory = new KubernetesObjectFactory(environment); DeploymentHandler handler = new DeploymentHandler(environment, kubernetesObjectFactory, client); // When Gaffer gaffer = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") ); handler.onGafferCreate(gaffer); // Then // should create pod verify(client, times(1)).execute(null, podType); // should create the right pod V1Pod expected = kubernetesObjectFactory.createHelmPod(gaffer, HelmCommand.INSTALL, "name"); verify(client, times(1)).execute(null, podType); verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods"), eq("POST"), anyList(), anyList(), eq(expected), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldUpgradeHelmDeploymentOnSpecUpdate() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); // Mimicking successful secret creation call when(client.buildCall(anyString(), anyString(), anyList(), anyList(), any(V1Secret.class), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); callback.onSuccess(invocationOnMock.getArgument(4), 200, null); return null; }); Type podType = new TypeToken<V1Pod>() { }.getType(); when(client.execute(null, podType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new V1Pod())); KubernetesObjectFactory kubernetesObjectFactory = new KubernetesObjectFactory(environment); DeploymentHandler handler = new DeploymentHandler(environment, kubernetesObjectFactory, client); // When Gaffer gaffer = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") .generation(1L) ); Gaffer gaffer2 = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") .generation(2L) ); handler.onGafferUpdate(gaffer, gaffer2); // Then V1Pod expected = kubernetesObjectFactory.createHelmPod(gaffer2, HelmCommand.UPGRADE, "name"); verify(client, times(1)).execute(null, podType); verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods"), eq("POST"), anyList(), anyList(), eq(expected), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldNotUpgradeHelmDeploymentIfGenerationIsUnchanged() throws ApiException { // Given ApiClient client = mock(ApiClient.class); KubernetesObjectFactory kubernetesObjectFactory = new KubernetesObjectFactory(environment); DeploymentHandler handler = new DeploymentHandler(environment, kubernetesObjectFactory, client); // When Gaffer gaffer = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") .generation(1L) ); Gaffer gaffer2 = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") .generation(1L) ); handler.onGafferUpdate(gaffer, gaffer2); // Then verifyZeroInteractions(client); } @Test public void shouldUninstallTheHelmDeploymentOnDelete() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); KubernetesObjectFactory kubernetesObjectFactory = new KubernetesObjectFactory(environment); DeploymentHandler handler = new DeploymentHandler(environment, kubernetesObjectFactory, client); // When Gaffer gaffer = new Gaffer() .metaData(new V1ObjectMeta() .namespace("gaffer-namespace") .name("name") .generation(1L) ); Type podType = new TypeToken<V1Pod>() { }.getType(); when(client.execute(null, podType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new V1Pod())); handler.onGafferDelete(gaffer, false); // Then V1Pod expected = kubernetesObjectFactory.createHelmPod(gaffer, HelmCommand.UNINSTALL, null); verify(client, times(1)).executeAsync(any(), eq(podType), any()); verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods"), eq("POST"), anyList(), anyList(), eq(expected), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldClearUpRemainingResourcesLeftAfterSuccessfulUninstall() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); DeploymentHandler handler = new DeploymentHandler(environment, mock(KubernetesObjectFactory.class), client); // When V1Pod uninstallWorker = new V1Pod() .status( new V1PodStatus() .phase("Succeeded") ) .metadata( new V1ObjectMeta() .name("my-uninstall-worker") .namespace("gaffer-workers") .putLabelsItem("goal", "uninstall") // <---- This will be checked .putLabelsItem(GAFFER_NAME_LABEL, "my-gaffer") .putLabelsItem(GAFFER_NAMESPACE_LABEL, "my-gaffer-namespace") .putLabelsItem(K8S_INSTANCE_LABEL, GAAS_LABEL_VALUE) ); handler.onPodUpdate(null, uninstallWorker); // Then // Clear workers verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); // Clear dangling pods verify(client, times(1)).buildCall(eq("/api/v1/namespaces/my-gaffer-namespace/pods"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); // Clear pvcs - one for hdfs and one for zookeeper verify(client, times(2)).buildCall(eq("/api/v1/namespaces/my-gaffer-namespace/persistentvolumeclaims"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldClearUpWorkersAfterTheyAreCompleted() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); DeploymentHandler handler = new DeploymentHandler(environment, mock(KubernetesObjectFactory.class), client); V1Pod installWorker = new V1Pod() .status( new V1PodStatus() .phase("Succeeded") ) .spec(new V1PodSpec() .addVolumesItem(new V1Volume() .name("values") .secret(new V1SecretVolumeSource() .secretName("my-values-secret-name") ) ) ) .metadata( new V1ObjectMeta() .name("my-install-worker") .namespace("gaffer-workers") .putLabelsItem("goal", "install") .putLabelsItem(GAFFER_NAME_LABEL, "my-gaffer") .putLabelsItem(GAFFER_NAMESPACE_LABEL, "my-gaffer-namespace") .putLabelsItem(K8S_INSTANCE_LABEL, GAAS_LABEL_VALUE) ); // Mimicking successful pod deletion call when(client.buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); if (callback != null) { callback.onSuccess(installWorker, 200, null); } return null; }); Type statusType = new TypeToken<V1Status>() { }.getType(); when(client.execute(null, statusType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new V1Status())); // When handler.onPodUpdate(null, installWorker); // Then // worker pod verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); // verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/secrets/my-values-secret-name"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldAttemptToClearUpWorkersIfTheyFail() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); DeploymentHandler handler = new DeploymentHandler(environment, mock(KubernetesObjectFactory.class), client); V1Pod installWorker = new V1Pod() .status( new V1PodStatus() .phase("Failed") ) .spec(new V1PodSpec() .addVolumesItem(new V1Volume() .name("values") .secret(new V1SecretVolumeSource() .secretName("my-values-secret-name") ) ) ) .metadata( new V1ObjectMeta() .name("my-install-worker") .namespace("gaffer-workers") .putLabelsItem("goal", "install") .putLabelsItem(GAFFER_NAME_LABEL, "my-gaffer") .putLabelsItem(GAFFER_NAMESPACE_LABEL, "my-gaffer-namespace") .putLabelsItem(K8S_INSTANCE_LABEL, GAAS_LABEL_VALUE) ); // Mimicking successful pod deletion call when(client.buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); if (callback != null) { callback.onSuccess(installWorker, 200, null); } return null; }); // Mimicking successful logs retrieval call when(client.buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker/log"), eq("GET"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); if (callback != null) { callback.onSuccess("here are the logs", 200, null); } return null; }); Type objectType = new TypeToken<Object>() { }.getType(); when(client.execute(null, objectType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new Gaffer())); Type statusType = new TypeToken<V1Status>() { }.getType(); when(client.execute(null, statusType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new V1Status())); // When handler.onPodUpdate(null, installWorker); // Then // worker pod verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); // verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/secrets/my-values-secret-name"), eq("DELETE"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } @Test public void shouldAppendLogsToGafferStatusIfTheyFail() throws ApiException { // Given ApiClient client = mock(ApiClient.class); when(client.escapeString(anyString())).thenCallRealMethod(); DeploymentHandler handler = new DeploymentHandler(environment, mock(KubernetesObjectFactory.class), client); V1Pod installWorker = new V1Pod() .status( new V1PodStatus() .phase("Failed") ) .spec(new V1PodSpec() .addVolumesItem(new V1Volume() .name("values") .secret(new V1SecretVolumeSource() .secretName("my-values-secret-name") ) ) ) .metadata( new V1ObjectMeta() .name("my-install-worker") .namespace("gaffer-workers") .putLabelsItem("goal", "install") .putLabelsItem(GAFFER_NAME_LABEL, "my-gaffer") .putLabelsItem(GAFFER_NAMESPACE_LABEL, "my-gaffer-namespace") .putLabelsItem(K8S_INSTANCE_LABEL, GAAS_LABEL_VALUE) ); when(client.buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker/log"), anyString(), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class))).then(invocationOnMock -> { ApiCallback callback = invocationOnMock.getArgument(9); if (callback != null) { callback.onSuccess("here are the logs", 200, null); } return null; }); Type objectType = new TypeToken<Object>() { }.getType(); when(client.execute(null, objectType)).thenReturn(new ApiResponse<>(200, new HashMap<>(), new Gaffer())); // When handler.onPodUpdate(null, installWorker); // Then verify(client, times(1)).buildCall(eq("/api/v1/namespaces/gaffer-workers/pods/my-install-worker/log"), eq("GET"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any(ApiCallback.class)); verify(client, times(1)).buildCall(eq("/apis/gchq.gov.uk/v1/namespaces/my-gaffer-namespace/gaffers/my-gaffer/status"), eq("GET"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); verify(client, times(1)).buildCall(eq("/apis/gchq.gov.uk/v1/namespaces/my-gaffer-namespace/gaffers/my-gaffer/status"), eq("PUT"), anyList(), anyList(), any(), anyMap(), anyMap(), anyMap(), any(String[].class), any()); } }
package com.zorro.kotlin.baselibs.widget.decoration; /** * Created by Zorro * Created date 2019/10/18 */ public interface GroupListener { String getGroupName(int position); }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jetty.jettyproducer; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.RuntimeCamelException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jetty.BaseJettyTest; import org.apache.camel.http.common.HttpOperationFailedException; import org.junit.Test; /** * @version */ public class JettyHttpProducerRedirectTest extends BaseJettyTest { @Test public void testHttpRedirect() throws Exception { try { template.requestBody("jetty:http://localhost:{{port}}/test", "Hello World", String.class); fail("Should have thrown an exception"); } catch (RuntimeCamelException e) { HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause()); assertEquals(301, cause.getStatusCode()); assertEquals(true, cause.isRedirectError()); assertEquals(true, cause.hasRedirectLocation()); assertEquals("http://localhost:" + getPort() + "/test", cause.getUri()); assertEquals("http://localhost:" + getPort() + "/newtest", cause.getRedirectLocation()); } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("jetty://http://localhost:{{port}}/test") .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 301); exchange.getOut().setHeader("Location", "http://localhost:" + getPort() + "/newtest"); } }); } }; } }
package nam.model.namespace; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Named; import org.aries.runtime.BeanContext; import org.aries.ui.AbstractPageManager; import org.aries.ui.AbstractWizardPage; import org.aries.ui.Breadcrumb; import org.aries.ui.event.Selected; import org.aries.ui.event.Unselected; import nam.model.Namespace; import nam.model.util.NamespaceUtil; import nam.ui.design.SelectionContext; @SessionScoped @Named("namespacePageManager") public class NamespacePageManager extends AbstractPageManager<Namespace> implements Serializable { @Inject private NamespaceWizard namespaceWizard; @Inject private NamespaceDataManager namespaceDataManager; @Inject private NamespaceInfoManager namespaceInfoManager; @Inject private NamespaceListManager namespaceListManager; @Inject private NamespaceRecord_OverviewSection namespaceOverviewSection; @Inject private NamespaceRecord_IdentificationSection namespaceIdentificationSection; @Inject private NamespaceRecord_ConfigurationSection namespaceConfigurationSection; @Inject private NamespaceRecord_DocumentationSection namespaceDocumentationSection; @Inject private SelectionContext selectionContext; public NamespacePageManager() { initializeSections(); } public void refresh() { refresh("namespace"); } public void refreshLocal() { refreshLocal("namespace"); } public void refreshMembers() { refreshMembers("namespace"); } public void refresh(String scope) { refreshLocal(scope); //refreshMembers(scope); } public void refreshLocal(String scope) { namespaceDataManager.setScope(scope); namespaceListManager.refresh(); } public void refreshMembers(String scope) { //nothing for now } public String getNamespaceListPage() { return "/nam/model/namespace/namespaceListPage.xhtml"; } public String getNamespaceTreePage() { return "/nam/model/namespace/namespaceTreePage.xhtml"; } public String getNamespaceSummaryPage() { return "/nam/model/namespace/namespaceSummaryPage.xhtml"; } public String getNamespaceRecordPage() { return "/nam/model/namespace/namespaceRecordPage.xhtml"; } public String getNamespaceWizardPage() { return "/nam/model/namespace/namespaceWizardPage.xhtml"; } public String getNamespaceManagementPage() { return "/nam/model/namespace/namespaceManagementPage.xhtml"; } public void handleNamespaceSelected(@Observes @Selected Namespace namespace) { selectionContext.setSelection("namespace", namespace); namespaceInfoManager.setRecord(namespace); } public void handleNamespaceUnselected(@Observes @Unselected Namespace namespace) { selectionContext.unsetSelection("namespace", namespace); namespaceInfoManager.unsetRecord(namespace); } public void handleNamespaceChecked() { String scope = "namespaceSelection"; NamespaceListObject listObject = namespaceListManager.getSelection(); Namespace namespace = selectionContext.getSelection("namespace"); boolean checked = namespaceListManager.getCheckedState(); listObject.setChecked(checked); if (checked) { namespaceInfoManager.setRecord(namespace); selectionContext.setSelection(scope, namespace); } else { namespaceInfoManager.unsetRecord(namespace); selectionContext.unsetSelection(scope, namespace); } refreshLocal(scope); } public String initializeNamespaceListPage() { String pageLevelKey = "namespaceList"; clearBreadcrumbs(pageLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceManagementPage()"); String url = getNamespaceListPage(); selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); selectionContext.resetOrigin(); selectionContext.setUrl(url); sections.clear(); return url; } public String initializeNamespaceTreePage() { String pageLevelKey = "namespaceTree"; clearBreadcrumbs(pageLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceTreePage()"); String url = getNamespaceTreePage(); selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); selectionContext.resetOrigin(); selectionContext.setUrl(url); sections.clear(); return url; } public String initializeNamespaceSummaryPage(Namespace namespace) { String pageLevelKey = "namespaceSummary"; clearBreadcrumbs(pageLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceSummaryPage()"); String url = getNamespaceSummaryPage(); selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); selectionContext.resetOrigin(); selectionContext.setUrl(url); sections.clear(); return url; } public String initializeNamespaceRecordPage() { Namespace namespace = selectionContext.getSelection("namespace"); String namespaceName = NamespaceUtil.getLabel(namespace); String pageLevelKey = "namespaceRecord"; clearBreadcrumbs(pageLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceManagementPage()"); addBreadcrumb(pageLevelKey, namespaceName, "showNamespaceRecordPage()"); String url = getNamespaceRecordPage(); selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); selectionContext.resetOrigin(); selectionContext.setUrl(url); initializeDefaultView(); sections.clear(); return url; } public String initializeNamespaceCreationPage(Namespace namespace) { setPageTitle("New "+getNamespaceLabel(namespace)); setPageIcon("/icons/nam/NewNamespace16.gif"); setSectionTitle("Namespace Identification"); namespaceWizard.setNewMode(true); String pageLevelKey = "namespace"; String wizardLevelKey = "namespaceWizard"; clearBreadcrumbs(pageLevelKey); clearBreadcrumbs(wizardLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceManagementPage()"); addBreadcrumb(pageLevelKey, new Breadcrumb("New Namespace", "showNamespaceWizardPage()")); namespaceIdentificationSection.setOwner("namespaceWizard"); namespaceConfigurationSection.setOwner("namespaceWizard"); namespaceDocumentationSection.setOwner("namespaceWizard"); sections.clear(); sections.add(namespaceIdentificationSection); sections.add(namespaceConfigurationSection); sections.add(namespaceDocumentationSection); String url = getNamespaceWizardPage() + "?section=Identification"; selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); //selectionContext.resetOrigin(); selectionContext.setUrl(url); refreshLocal(); return url; } public String initializeNamespaceUpdatePage(Namespace namespace) { setPageTitle(getNamespaceLabel(namespace)); setPageIcon("/icons/nam/Namespace16.gif"); setSectionTitle("Namespace Overview"); String namespaceName = NamespaceUtil.getLabel(namespace); namespaceWizard.setNewMode(false); String pageLevelKey = "namespace"; String wizardLevelKey = "namespaceWizard"; clearBreadcrumbs(pageLevelKey); clearBreadcrumbs(wizardLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceManagementPage()"); addBreadcrumb(pageLevelKey, new Breadcrumb(namespaceName, "showNamespaceWizardPage()")); namespaceOverviewSection.setOwner("namespaceWizard"); namespaceIdentificationSection.setOwner("namespaceWizard"); namespaceConfigurationSection.setOwner("namespaceWizard"); namespaceDocumentationSection.setOwner("namespaceWizard"); sections.clear(); sections.add(namespaceOverviewSection); sections.add(namespaceIdentificationSection); sections.add(namespaceConfigurationSection); sections.add(namespaceDocumentationSection); String url = getNamespaceWizardPage() + "?section=Overview"; selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); //selectionContext.resetOrigin(); selectionContext.setUrl(url); refreshLocal(); return url; } public String initializeNamespaceManagementPage() { setPageTitle("Namespaces"); setPageIcon("/icons/nam/Namespace16.gif"); String pageLevelKey = "namespaceManagement"; clearBreadcrumbs(pageLevelKey); addBreadcrumb(pageLevelKey, "Top", "showMainPage()"); addBreadcrumb(pageLevelKey, "Namespaces", "showNamespaceManagementPage()"); String url = getNamespaceManagementPage(); selectionContext.setCurrentArea("namespace"); selectionContext.setSelectedArea(pageLevelKey); selectionContext.setMessageDomain(pageLevelKey); selectionContext.resetOrigin(); selectionContext.setUrl(url); initializeDefaultView(); sections.clear(); return url; } public void initializeDefaultView() { setPageTitle("Namespaces"); setPageIcon("/icons/nam/Namespace16.gif"); setSectionType("namespace"); setSectionName("Overview"); setSectionTitle("Overview of Namespaces"); setSectionIcon("/icons/nam/Overview16.gif"); String viewLevelKey = "namespaceOverview"; clearBreadcrumbs(viewLevelKey); addBreadcrumb(viewLevelKey, "Top", "showMainPage()"); addBreadcrumb(viewLevelKey, "Namespaces", "showNamespaceManagementPage()"); String scope = "projectList"; refreshLocal(scope); sections.clear(); } public String initializeNamespaceSummaryView(Namespace namespace) { //String viewTitle = getNamespaceLabel(namespace); //String currentArea = selectionContext.getCurrentArea(); setSectionType("namespace"); setSectionName("Summary"); setSectionTitle("Summary of Namespace Records"); setSectionIcon("/icons/nam/Namespace16.gif"); String viewLevelKey = "namespaceSummary"; clearBreadcrumbs(viewLevelKey); addBreadcrumb(viewLevelKey, "Top", "showMainPage()"); addBreadcrumb(viewLevelKey, "Namespaces", "showNamespaceManagementPage()"); selectionContext.setMessageDomain(viewLevelKey); sections.clear(); return null; } protected String getNamespaceLabel(Namespace namespace) { String label = "Namespace"; String name = NamespaceUtil.getLabel(namespace); if (name == null && namespace.getName() != null) name = NamespaceUtil.getLabel(namespace); if (name != null && !name.isEmpty()) label = name + " " + label; return label; } protected void updateState() { AbstractWizardPage<Namespace> page = namespaceWizard.getPage(); if (page != null) setSectionTitle("Namespace " + page.getName()); } protected void updateState(Namespace namespace) { String namespaceName = NamespaceUtil.getLabel(namespace); setSectionTitle(namespaceName + " Namespace"); } }
package uk.gov.hmcts.reform.em.orchestrator.automatedbundling; public class DocumentSelectorException extends RuntimeException { public DocumentSelectorException(String message) { super(message); } }
package com.siemens.mindsphere.security; import com.siemens.mindsphere.config.Constants; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; /** * Implementation of AuditorAware based on Spring Security. */ @Component public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override public String getCurrentAuditor() { return SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT); } }
/* * SSHTools - Java SSH2 API * * Copyright (C) 2002-2003 Lee David Painter and Contributors. * * Contributions made by: * * Brett Smith * Richard Pernavas * Erwin Bolwidt * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.sshtools.j2ssh.connection; import com.sshtools.j2ssh.transport.MessageNotAvailableException; import com.sshtools.j2ssh.transport.MessageStoreEOFException; import com.sshtools.j2ssh.transport.SshMessageStore; import general.Version; //import org.apache.commons.logging.Log; //import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; /** * * * @author $author$ * @version $Revision: 1.35 $ */ public class ChannelInputStream extends InputStream { //private static Log log = LogFactory.getLog(ChannelInputStream.class); int[] filter; byte[] msgdata; int currentPos = 0; private SshMessageStore messageStore; private Integer type = null; private int interrupt = 5000; private boolean isBlocking = false; private Object lock = new Object(); private Thread blockingThread = null; private Version v; /** * Creates a new ChannelInputStream object. * * @param messageStore * @param type */ public ChannelInputStream(SshMessageStore messageStore, Integer type) { this.messageStore = messageStore; filter = new int[1]; this.type = type; this.v.o=this; if (type != null) { filter[0] = SshMsgChannelExtendedData.SSH_MSG_CHANNEL_EXTENDED_DATA; } else { filter[0] = SshMsgChannelData.SSH_MSG_CHANNEL_DATA; } } /** * Creates a new ChannelInputStream object. * * @param messageStore */ public ChannelInputStream(SshMessageStore messageStore) { this(messageStore, null); } /** * * * @return */ public int available() { final String func = v.getFunc(); int available = 0; if (msgdata != null) { available = msgdata.length - currentPos; if (v.log.isDebugEnabled() && (available > 0)) { v.printf(func,2,String.valueOf(available) + " bytes of channel data available"); } available = (available >= 0) ? available : 0; } if (available == 0) { try { if (type != null) { SshMsgChannelExtendedData msg = (SshMsgChannelExtendedData) messageStore.peekMessage(filter); available = msg.getChannelData().length; } else { SshMsgChannelData msg = (SshMsgChannelData) messageStore.peekMessage(filter); available = msg.getChannelData().length; } if (v.log.isDebugEnabled()) { v.printf(func,2,String.valueOf(available) + " bytes of channel data available"); } } catch (MessageStoreEOFException mse) { v.printf(func,2,"No bytes available since the MessageStore is EOF"); available = -1; } catch (MessageNotAvailableException mna) { available = 0; } catch (InterruptedException ex) { v.printf(func,3,"peekMessage was interrupted, no data available!"); available = 0; } } return available; } /** * * * @throws IOException */ public void close() throws IOException { final String func = v.getFunc(); v.printf(func,3,"Closing ChannelInputStream"); messageStore.close(); } /** * * * @return */ public boolean isClosed() { return messageStore.isClosed(); } /** * * * @param interrupt */ public void setBlockInterrupt(int interrupt) { this.interrupt = (interrupt < 1000) ? 1000 : interrupt; } /** * */ public void interrupt() { messageStore.breakWaiting(); } /** * * * @return * * @throws java.io.IOException * @throws InterruptedIOException */ public int read() throws java.io.IOException { try { block(); return msgdata[currentPos++] & 0xFF; } catch (MessageStoreEOFException mse) { return -1; } catch (InterruptedException ex) { throw new InterruptedIOException( "The thread was interrupted whilst waiting for channel data"); } } /** * * * @param b * @param off * @param len * * @return * * @throws IOException * @throws IOException */ public int read(byte[] b, int off, int len) throws IOException { try { block(); int actual = available(); if (actual > len) { actual = len; } if (actual > 0) { System.arraycopy(msgdata, currentPos, b, off, actual); currentPos += actual; } return actual; } catch (MessageStoreEOFException mse) { return -1; } catch (InterruptedException ex) { throw new InterruptedIOException( "The thread was interrupted whilst waiting for channel data"); } } private void block() throws MessageStoreEOFException, InterruptedException, IOException { if (msgdata == null) { collectNextMessage(); } if (currentPos >= msgdata.length) { collectNextMessage(); } } private void startBlockingOperation() throws IOException { final String func=v.getFunc(); synchronized (lock) { if (isBlocking) { throw new IOException((("Cannot read from InputStream! " + blockingThread) == null) ? "**NULL THREAD**" : (blockingThread.getName() + " is currently performing a blocking operation")); } v.printf(func,2,"Starting blocking operation"); blockingThread = Thread.currentThread(); isBlocking = true; } } private void stopBlockingOperation() throws IOException { final String func = v.getFunc(); synchronized (lock) { v.printf(func,2,"Completed blocking operation"); blockingThread = null; isBlocking = false; } } private void collectNextMessage() throws MessageStoreEOFException, InterruptedException, IOException { final String func=v.getFunc(); // Collect the next message startBlockingOperation(); try { if (type != null) { SshMsgChannelExtendedData msg = null; while ((msg == null) && !isClosed()) { try { v.printf(func,2,"Waiting for extended channel data"); msg = (SshMsgChannelExtendedData) messageStore.getMessage(filter, interrupt); } catch (MessageNotAvailableException ex) { // Ignore the timeout but this allows us to review the // InputStreams state once in a while } } if (msg != null) { msgdata = msg.getChannelData(); currentPos = 0; } else { throw new MessageStoreEOFException(); } } else { SshMsgChannelData msg = null; while ((msg == null) && !isClosed()) { try { v.printf(func,2,"Waiting for channel data"); msg = (SshMsgChannelData) messageStore.getMessage(filter, interrupt); } catch (MessageNotAvailableException ex1) { // Ignore the timeout but this allows us to review the // InputStreams state once in a while } } if (msg != null) { msgdata = msg.getChannelData(); currentPos = 0; } else { throw new MessageStoreEOFException(); } } } finally { stopBlockingOperation(); } } }
/* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.ibatis; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; import javax.sql.DataSource; import com.ibatis.common.util.PaginatedList; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapExecutor; import com.ibatis.sqlmap.client.SqlMapSession; import com.ibatis.sqlmap.client.event.RowHandler; import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient; import org.springframework.dao.DataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.support.JdbcAccessor; /** * Helper class that simplifies data access via the SqlMapClient API of the * iBATIS Database Layer, and converts checked SQLExceptions into unchecked * DataAccessExceptions, compatible to the org.springframework.dao exception * hierarchy. Uses the same SQLExceptionTranslator mechanism as JdbcTemplate. * * <p>The main method of this class executes a callback that implements a * data access action. Furthermore, this class provides numerous convenience * methods that mirror SqlMapSession's execution methods. See the SqlMapClient * javadocs for details on those methods. * * <p>Needs a SqlMapClient to work on, passed in via the "sqlMapClient" property. * Can additionally be configured with a DataSource for fetching Connections, * although this is not necessary if a DataSource is specified for the SqlMapClient. * * <p>NOTE: The SqlMapClient/SqlMapSession API is the API of iBATIS SQL Maps 2. * With SQL Maps 1.x, the SqlMap/MappedStatement API has to be used. * * @author Juergen Hoeller * @since 24.02.2004 * @see #execute * @see #setSqlMapClient * @see #setDataSource * @see #setExceptionTranslator * @see SqlMapClientFactoryBean#setDataSource * @see com.ibatis.sqlmap.client.SqlMapClient#getDataSource * @see com.ibatis.sqlmap.client.SqlMapExecutor */ public class SqlMapClientTemplate extends JdbcAccessor implements SqlMapClientOperations { private SqlMapClient sqlMapClient; /** * Create a new SqlMapClientTemplate. */ public SqlMapClientTemplate() { } /** * Create a new SqlMapTemplate. * @param sqlMapClient iBATIS SqlMapClient that defines the mapped statements */ public SqlMapClientTemplate(SqlMapClient sqlMapClient) { setSqlMapClient(sqlMapClient); afterPropertiesSet(); } /** * Create a new SqlMapTemplate. * @param dataSource JDBC DataSource to obtain connections from * @param sqlMapClient iBATIS SqlMapClient that defines the mapped statements */ public SqlMapClientTemplate(DataSource dataSource, SqlMapClient sqlMapClient) { setDataSource(dataSource); setSqlMapClient(sqlMapClient); afterPropertiesSet(); } /** * Set the iBATIS Database Layer SqlMapClient that defines the mapped statements. */ public void setSqlMapClient(SqlMapClient sqlMapClient) { this.sqlMapClient = sqlMapClient; } /** * Return the iBATIS Database Layer SqlMapClient that this template works with. */ public SqlMapClient getSqlMapClient() { return sqlMapClient; } /** * If no DataSource specified, use SqlMapClient's DataSource. * @see com.ibatis.sqlmap.client.SqlMapClient#getDataSource */ public DataSource getDataSource() { DataSource ds = super.getDataSource(); return (ds != null ? ds : this.sqlMapClient.getDataSource()); } public void afterPropertiesSet() { if (this.sqlMapClient == null) { throw new IllegalArgumentException("sqlMapClient is required"); } super.afterPropertiesSet(); } /** * Execute the given data access action on a SqlMapSession. * @param action callback object that specifies the data access action * @return a result object returned by the action, or null * @throws DataAccessException in case of SQL Maps errors */ public Object execute(SqlMapClientCallback action) throws DataAccessException { SqlMapSession session = this.sqlMapClient.openSession(); try { Connection con = DataSourceUtils.getConnection(getDataSource()); try { session.setUserConnection(con); return action.doInSqlMapClient(session); } catch (SQLException ex) { throw getExceptionTranslator().translate("SqlMapClientTemplate", "(mapped statement)", ex); } finally { DataSourceUtils.closeConnectionIfNecessary(con, getDataSource()); } } finally { session.close(); } } /** * Execute the given data access action on a SqlMapSession, * expecting a List result. * @param action callback object that specifies the data access action * @return the List result * @throws DataAccessException in case of SQL Maps errors */ public List executeWithListResult(SqlMapClientCallback action) throws DataAccessException { return (List) execute(action); } /** * Execute the given data access action on a SqlMapSession, * expecting a Map result. * @param action callback object that specifies the data access action * @return the Map result * @throws DataAccessException in case of SQL Maps errors */ public Map executeWithMapResult(SqlMapClientCallback action) throws DataAccessException { return (Map) execute(action); } public Object queryForObject(final String statementName, final Object parameterObject) throws DataAccessException { return execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForObject(statementName, parameterObject); } }); } public Object queryForObject(final String statementName, final Object parameterObject, final Object resultObject) throws DataAccessException { return execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForObject(statementName, parameterObject, resultObject); } }); } public List queryForList(final String statementName, final Object parameterObject) throws DataAccessException { return executeWithListResult(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForList(statementName, parameterObject); } }); } public List queryForList(final String statementName, final Object parameterObject, final int skipResults, final int maxResults) throws DataAccessException { return executeWithListResult(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForList(statementName, parameterObject, skipResults, maxResults); } }); } public void queryWithRowHandler(final String statementName, final Object parameterObject, final RowHandler rowHandler) { execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { executor.queryWithRowHandler(statementName, parameterObject, rowHandler); return null; } }); } public List queryForList(final String statementName, final Object parameterObject, final RowHandler rowHandler) throws DataAccessException { return executeWithListResult(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForList(statementName, parameterObject, rowHandler); } }); } public PaginatedList queryForPaginatedList(final String statementName, final Object parameterObject, final int pageSize) throws DataAccessException { // throw exception if lazy loading will not work if (this.sqlMapClient instanceof ExtendedSqlMapClient && ((ExtendedSqlMapClient) this.sqlMapClient).getDelegate().getTxManager() == null) { throw new InvalidDataAccessApiUsageException("SqlMapClient needs to have DataSource to allow for lazy loading" + " - specify SqlMapClientFactoryBean's 'dataSource' property"); } return (PaginatedList) execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForPaginatedList(statementName, parameterObject, pageSize); } }); } public Map queryForMap(final String statementName, final Object parameterObject, final String keyProperty) throws DataAccessException { return executeWithMapResult(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForMap(statementName, parameterObject, keyProperty); } }); } public Map queryForMap(final String statementName, final Object parameterObject, final String keyProperty, final String valueProperty) throws DataAccessException { return executeWithMapResult(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.queryForMap(statementName, parameterObject, keyProperty, valueProperty); } }); } public Object insert(final String statementName, final Object parameterObject) throws DataAccessException { return execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return executor.insert(statementName, parameterObject); } }); } public int update(final String statementName, final Object parameterObject) throws DataAccessException { Integer result = (Integer) execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return new Integer(executor.update(statementName, parameterObject)); } }); return result.intValue(); } public int delete(final String statementName, final Object parameterObject) throws DataAccessException { Integer result = (Integer) execute(new SqlMapClientCallback() { public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException { return new Integer(executor.delete(statementName, parameterObject)); } }); return result.intValue(); } }
/* * Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.core.Jvm; import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; /** * Interface to parseOne arbitrary field-value data. */ public interface WireParser extends Consumer<WireIn> { FieldNumberParselet SKIP_READABLE_BYTES = WireParser::skipReadable; @NotNull static WireParser wireParser(WireParselet defaultConsumer) { return new VanillaWireParser(defaultConsumer, SKIP_READABLE_BYTES); } @NotNull static WireParser wireParser(@NotNull WireParselet defaultConsumer, @NotNull FieldNumberParselet fieldNumberParselet) { return new VanillaWireParser(defaultConsumer, fieldNumberParselet); } static void skipReadable(long ignoreMethodId, WireIn wire) { Bytes<?> bytes = wire.bytes(); bytes.readPosition(bytes.readLimit()); } WireParselet getDefaultConsumer(); void parseOne(@NotNull WireIn wireIn); @Override default void accept(@NotNull WireIn wireIn) { Bytes<?> bytes = wireIn.bytes(); while (bytes.readRemaining() > 0) { long start = bytes.readPosition(); parseOne(wireIn); wireIn.consumePadding(); if (bytes.readPosition() == start) { Jvm.warn().on(getClass(), "Failed to progress reading " + bytes.readRemaining() + " bytes left."); break; } } } WireParselet lookup(CharSequence name); @NotNull default VanillaWireParser registerOnce(WireKey key, WireParselet valueInConsumer) { CharSequence name = key.name(); if (lookup(name) != null) { Jvm.warn().on(getClass(), "Unable to register multiple methods for " + name + " ignoring one."); } else { register(key, valueInConsumer); } return (VanillaWireParser) this; } @NotNull VanillaWireParser register(WireKey key, WireParselet valueInConsumer); }
package devcrema.spring_jpa_rest_board_example.post.query; import devcrema.spring_jpa_rest_board_example.post.domain.Post; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface GetPostRepository extends JpaRepository<Post, Long> { List<GetPostResponse> findAllByEnabledTrue(); Optional<GetPostResponse> getById(long id); Optional<GetPostDto> getDtoById(long id); }
/* * 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.processors.query.calcite.planner; import static org.apache.ignite.internal.util.CollectionUtils.first; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.sql.fun.SqlAvgAggFunction; import org.apache.calcite.sql.fun.SqlCountAggFunction; import org.apache.calcite.util.ImmutableIntList; import org.apache.ignite.internal.processors.query.calcite.rel.IgniteRel; import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteMapHashAggregate; import org.apache.ignite.internal.processors.query.calcite.rel.agg.IgniteReduceHashAggregate; import org.apache.ignite.internal.processors.query.calcite.schema.IgniteSchema; import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistribution; import org.apache.ignite.internal.processors.query.calcite.trait.IgniteDistributions; import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeFactory; import org.apache.ignite.internal.processors.query.calcite.type.IgniteTypeSystem; import org.hamcrest.core.IsInstanceOf; import org.junit.jupiter.api.Test; /** * HashAggregatePlannerTest. * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859 */ public class HashAggregatePlannerTest extends AbstractAggregatePlannerTest { /** * SubqueryWithAggregate. * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859 * * @throws Exception If failed. */ @Test public void subqueryWithAggregate() throws Exception { IgniteTypeFactory f = new IgniteTypeFactory(IgniteTypeSystem.INSTANCE); TestTable employer = new TestTable( new RelDataTypeFactory.Builder(f) .add("ID", f.createJavaType(Integer.class)) .add("NAME", f.createJavaType(String.class)) .add("SALARY", f.createJavaType(Double.class)) .build()) { @Override public IgniteDistribution distribution() { return IgniteDistributions.affinity(0, "Employers", "hash"); } }; IgniteSchema publicSchema = new IgniteSchema("PUBLIC"); publicSchema.addTable("EMPS", employer); String sql = "SELECT * FROM emps WHERE emps.salary = (SELECT AVG(emps.salary) FROM emps)"; IgniteRel phys = physicalPlan( sql, publicSchema ); assertNotNull(phys); IgniteReduceHashAggregate rdcAgg = findFirstNode(phys, byClass(IgniteReduceHashAggregate.class)); IgniteMapHashAggregate mapAgg = findFirstNode(phys, byClass(IgniteMapHashAggregate.class)); assertNotNull(rdcAgg, "Invalid plan\n" + RelOptUtil.toString(phys)); assertNotNull(mapAgg, "Invalid plan\n" + RelOptUtil.toString(phys)); assertThat( "Invalid plan\n" + RelOptUtil.toString(phys), first(rdcAgg.getAggregateCalls()).getAggregation(), IsInstanceOf.instanceOf(SqlAvgAggFunction.class)); assertThat( "Invalid plan\n" + RelOptUtil.toString(phys), first(mapAgg.getAggCallList()).getAggregation(), IsInstanceOf.instanceOf(SqlAvgAggFunction.class)); } /** * NoGroupByAggregate. * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859 */ @Test public void noGroupByAggregate() throws Exception { TestTable tbl = createAffinityTable().addIndex(RelCollations.of(ImmutableIntList.of(1, 2)), "val0_val1"); IgniteSchema publicSchema = new IgniteSchema("PUBLIC"); publicSchema.addTable("TEST", tbl); String sqlCount = "SELECT COUNT(*) FROM test"; IgniteRel phys = physicalPlan( sqlCount, publicSchema ); IgniteMapHashAggregate mapAgg = findFirstNode(phys, byClass(IgniteMapHashAggregate.class)); IgniteReduceHashAggregate rdcAgg = findFirstNode(phys, byClass(IgniteReduceHashAggregate.class)); assertNotNull(rdcAgg, "Invalid plan\n" + RelOptUtil.toString(phys)); assertNotNull(mapAgg, "Invalid plan\n" + RelOptUtil.toString(phys)); assertThat( "Invalid plan\n" + RelOptUtil.toString(phys), first(rdcAgg.getAggregateCalls()).getAggregation(), IsInstanceOf.instanceOf(SqlCountAggFunction.class)); assertThat( "Invalid plan\n" + RelOptUtil.toString(phys), first(mapAgg.getAggCallList()).getAggregation(), IsInstanceOf.instanceOf(SqlCountAggFunction.class)); } }
package com.eduworks.rollup.coprocessor; import cass.rollup.InquiryPacket; import cass.rollup.processors.PessimisticQuadnaryAssertionProcessor; import org.cass.competency.EcCompetency; import org.cass.competency.EcFramework; import org.credentialengine.Credential; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.schema.AchieveAction; import org.schema.CreativeWork; import org.stjs.javascript.Global; import org.stjs.javascript.functions.Callback1; import org.stjs.testing.annotation.ScriptsBefore; import org.stjs.testing.driver.STJSTestDriverRunner; /** * Created by fray on 5/30/17. */ @RunWith(STJSTestDriverRunner.class) @ScriptsBefore({"lib/require.js", "rollupInit.js", "base64toArrayBuffer.js", "base64toArrayBuffer.js"}) public class MilCredCoprocessorTest extends EvidenceProcessingTestBase { @Test public void basicTrueTest() { final EcFramework f = newFramework("Billy's Framework"); final EcCompetency c = newCompetency("Add"); f.addCompetency(c.shortId()); f.save(null, failure,repo); final Credential cr = newCredential("Adding Credential"); final CreativeWork w = newCreativeRelation(cr, c, "http://schema.cassproject.org/0.2/vocab/asserts"); final AchieveAction a = newAchieveAction(cr); PessimisticQuadnaryAssertionProcessor processor = getTestProcessor(); processor.coprocessors.push(new MilCredCoprocessor()); performTest(processor, f, c, new Callback1<InquiryPacket>() { @Override public void $invoke(InquiryPacket p1) { Global.console.log(p1.result.name()); Global.console.log(p1); deleteById(f.shortId()); deleteById(cr.shortId()); deleteById(w.shortId()); deleteById(c.shortId()); deleteById(a.shortId()); Assert.assertSame(InquiryPacket.ResultType.TRUE, p1.result); } }); deleteById(f.shortId()); deleteById(cr.shortId()); deleteById(w.shortId()); deleteById(c.shortId()); deleteById(a.shortId()); } @Test public void basicUnknownTest() { // final EcFramework f = newFramework("Billy's Framework"); // // final EcCompetency c = newCompetency("Add"); // // f.addCompetency(c.shortId()); // // f.save(null, failure,repo); // // final Credential cr = newCredential("Adding Credential"); // // //final CreativeWork w = newCreativeRelation(cr,c,"http://schema.cassproject.org/0.2/vocab/asserts"); // // final AchieveAction a = newAchieveAction(cr); // // PessimisticQuadnaryAssertionProcessor processor = getTestProcessor(); // processor.coprocessors.push(new MilCredCoprocessor()); // // performTest(processor, f, c, new Callback1<InquiryPacket>() { // @Override // public void $invoke(InquiryPacket p1) { // Global.console.log(p1.result.name()); // Global.console.log(p1); // deleteById(f.shortId()); // deleteById(cr.shortId()); // deleteById(c.shortId()); // deleteById(a.shortId()); // Assert.assertSame(InquiryPacket.ResultType.TRUE, p1.result); // } // }); // // deleteById(f.shortId()); // deleteById(cr.shortId()); // deleteById(c.shortId()); // deleteById(a.shortId()); Assert.assertTrue(true); } }
package cn.taroco.rbac.admin.controller; import cn.taroco.common.constants.CommonConstant; import cn.taroco.common.entity.SysZuulRoute; import cn.taroco.common.utils.Query; import cn.taroco.common.web.BaseController; import cn.taroco.common.web.Response; import cn.taroco.rbac.admin.service.SysZuulRouteService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.Map; /** * <p> * 动态路由配置表 前端控制器 * </p> * * @author liuht * @since 2018-05-15 */ @RestController @RequestMapping("/route") public class ZuulRouteController extends BaseController { @Autowired private SysZuulRouteService sysZuulRouteService; /** * 通过ID查询 * * @param id ID * @return SysZuulRoute */ @GetMapping("/{id}") public SysZuulRoute get(@PathVariable Integer id) { return sysZuulRouteService.getById(id); } /** * 分页查询信息 * * @param params 分页对象 * @return 分页对象 */ @GetMapping("/page") public IPage page(@RequestParam Map<String, Object> params) { params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL); return sysZuulRouteService.page(new Query<>(params,SysZuulRoute.class), new QueryWrapper<>()); } /** * 添加 * * @param sysZuulRoute 实体 * @return success/false */ @PostMapping public Response add(@RequestBody SysZuulRoute sysZuulRoute) { return Response.success(sysZuulRouteService.save(sysZuulRoute)); } /** * 删除 * * @param id ID * @return success/false */ @DeleteMapping("/{id}") public Response delete(@PathVariable Integer id) { SysZuulRoute sysZuulRoute = new SysZuulRoute(); sysZuulRoute.setId(id); sysZuulRoute.setUpdateTime(new Date()); sysZuulRoute.setDelFlag(CommonConstant.STATUS_DEL); return Response.success(sysZuulRouteService.updateById(sysZuulRoute)); } /** * 编辑 * * @param sysZuulRoute 实体 * @return success/false */ @PutMapping public Response edit(@RequestBody SysZuulRoute sysZuulRoute) { sysZuulRoute.setUpdateTime(new Date()); return Response.success(sysZuulRouteService.updateById(sysZuulRoute)); } /** * 刷新配置 * * @return success/fasle */ @GetMapping("/apply") public Response apply() { return Response.success(sysZuulRouteService.applyZuulRoute()); } }
package ru.job4j.threads; import java.util.*; public class SaveDynamicList<E> implements Iterable<E> { Object[] container = new Object[10]; int index = 0; @Override public synchronized Iterator<E> iterator() { return new Iterator<E>() { int indexIter = 0; @Override public boolean hasNext() { return indexIter < index; } @Override public E next() { if (this.hasNext()) { return (E) container[indexIter++]; } throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public synchronized void add(E value) { if (container[container.length - 1] != null) { container = Arrays.copyOf(container, container.length * 2); } container[index++] = value; } public synchronized E get(int index) { return (E) container[index]; } }
/* * Copyright 2019-2020 Zheng Jie * * 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.yzw.modules.quartz.utils; import lombok.extern.slf4j.Slf4j; import com.yzw.exception.BadRequestException; import com.yzw.modules.quartz.domain.QuartzJob; import org.quartz.*; import org.quartz.impl.triggers.CronTriggerImpl; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Date; import static org.quartz.TriggerBuilder.newTrigger; /** * @author Zheng Jie * @date 2019-01-07 */ @Slf4j @Component public class QuartzManage { private static final String JOB_NAME = "TASK_"; @Resource(name = "scheduler") private Scheduler scheduler; public void addJob(QuartzJob quartzJob){ try { // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class). withIdentity(JOB_NAME + quartzJob.getId()).build(); //通过触发器名和cron 表达式创建 Trigger Trigger cronTrigger = newTrigger() .withIdentity(JOB_NAME + quartzJob.getId()) .startNow() .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression())) .build(); cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob); //重置启动时间 ((CronTriggerImpl)cronTrigger).setStartTime(new Date()); //执行定时任务 scheduler.scheduleJob(jobDetail,cronTrigger); // 暂停任务 if (quartzJob.getIsPause()) { pauseJob(quartzJob); } } catch (Exception e){ log.error("创建定时任务失败", e); throw new BadRequestException("创建定时任务失败"); } } /** * 更新job cron表达式 * @param quartzJob / */ public void updateJobCron(QuartzJob quartzJob){ try { TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null){ addJob(quartzJob); trigger = (CronTrigger) scheduler.getTrigger(triggerKey); } CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()); trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); //重置启动时间 ((CronTriggerImpl)trigger).setStartTime(new Date()); trigger.getJobDataMap().put(QuartzJob.JOB_KEY,quartzJob); scheduler.rescheduleJob(triggerKey, trigger); // 暂停任务 if (quartzJob.getIsPause()) { pauseJob(quartzJob); } } catch (Exception e){ log.error("更新定时任务失败", e); throw new BadRequestException("更新定时任务失败"); } } /** * 删除一个job * @param quartzJob / */ public void deleteJob(QuartzJob quartzJob){ try { JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.pauseJob(jobKey); scheduler.deleteJob(jobKey); } catch (Exception e){ log.error("删除定时任务失败", e); throw new BadRequestException("删除定时任务失败"); } } /** * 恢复一个job * @param quartzJob / */ public void resumeJob(QuartzJob quartzJob){ try { TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null) { addJob(quartzJob); } JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.resumeJob(jobKey); } catch (Exception e){ log.error("恢复定时任务失败", e); throw new BadRequestException("恢复定时任务失败"); } } /** * 立即执行job * @param quartzJob / */ public void runJobNow(QuartzJob quartzJob){ try { TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null) { addJob(quartzJob); } JobDataMap dataMap = new JobDataMap(); dataMap.put(QuartzJob.JOB_KEY, quartzJob); JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.triggerJob(jobKey,dataMap); } catch (Exception e){ log.error("定时任务执行失败", e); throw new BadRequestException("定时任务执行失败"); } } /** * 暂停一个job * @param quartzJob / */ public void pauseJob(QuartzJob quartzJob){ try { JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.pauseJob(jobKey); } catch (Exception e){ log.error("定时任务暂停失败", e); throw new BadRequestException("定时任务暂停失败"); } } }
package seedu.address.storage; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.schedule.ReadOnlyScheduleTracker; /** * Represents a storage for {@link seedu.address.model.schedule.ScheduleTracker} */ public interface ScheduleTrackerStorage { /** * @return File path of Schedule Tracker data file */ Path getScheduleTrackerFilePath(); /** * Returns Schedule Tracker as a {@link seedu.address.model.schedule.ReadOnlyScheduleTracker} * @return {@code Optional.empty()} if storage file is not found. * @throws DataConversionException * @throws IOException */ Optional<ReadOnlyScheduleTracker> readScheduleTracker() throws DataConversionException, IOException; /** * @param filePath File path of Schedule Tracker * @return {@code Optional.empty()} if filePath is an empty Schedule Tracker * @throws DataConversionException * @throws IOException */ Optional<ReadOnlyScheduleTracker> readScheduleTracker(Path filePath) throws DataConversionException, IOException; /** * Saves the given {@link ReadOnlyScheduleTracker} to the storage. * @param scheduleTracker cannot be null. * @throws IOException if there was any problem writing to the file. */ void saveScheduleTracker(ReadOnlyScheduleTracker scheduleTracker) throws IOException; /** * @see #saveScheduleTracker(ReadOnlyScheduleTracker) */ void saveScheduleTracker(ReadOnlyScheduleTracker scheduleTracker, Path filePath) throws IOException; }
package me.jrkr.jsf.gravatar.component; import com.google.common.base.Joiner; import com.google.common.hash.Hashing; import me.jrkr.jsf.gravatar.common.GravatarImageType; import me.jrkr.jsf.gravatar.common.GravatarRating; import org.apache.commons.lang.StringUtils; import javax.el.ELContext; import javax.el.ValueExpression; import javax.faces.component.FacesComponent; import javax.faces.component.html.HtmlGraphicImage; import javax.faces.context.FacesContext; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @FacesComponent(value = UIGravatar.GRAVATAR_COMPONENT) public class UIGravatar extends HtmlGraphicImage { public static final String GRAVATAR_COMPONENT = "me.jrkr.uigravatar"; public static final String DEFAULT_RENDERER_TYPE = "me.jrkr.uigravatar.renderer"; public static final String GRAVATAR_URL = "http://www.gravatar.com/avatar/"; public static final String CHAR_TYPE = "UTF-8"; public static final int GRAVATAR_MAX_SIZE = 512; public static final int GRAVATAR_MIN_SIZE = 1; public static final int GRAVATAR_DEFAULT_SIZE = 80; private String email; private String size; private String rating; private String defaultImg; public UIGravatar() { setRendererType(DEFAULT_RENDERER_TYPE); } public String getGravUrl() { String emailHash = Hashing.md5().hashString(email.toLowerCase().trim(), Charset.forName(CHAR_TYPE)).toString(); String params = formatUrlParameters(); return (new StringBuilder()).append(GRAVATAR_URL).append(emailHash).append(".jpg").append(params).toString(); } private String formatUrlParameters() { List params = new ArrayList(); if (checkFixSizeCheck()) params.add((new StringBuilder()).append("s=").append(size).toString()); if (GravatarRating.fromCode(rating) != null) params.add((new StringBuilder()).append("r=").append(rating).toString()); if (StringUtils.isNotBlank(defaultImg)) params.add((new StringBuilder()).append("d=").append(defaultImg).toString()); if (params.isEmpty()) return ""; else return (new StringBuilder()).append("?").append(Joiner.on("&").join(params.iterator())).toString(); } private boolean checkFixSizeCheck() { boolean sizeOk = false; if (size == null) return sizeOk; Integer sizeInt; try { sizeInt = Integer.parseInt(size); } catch (NumberFormatException nfe) { return sizeOk; } if (sizeInt.intValue() < GRAVATAR_MIN_SIZE || sizeInt.intValue() > GRAVATAR_MAX_SIZE) return false; return true; } public String getEmail() { return email != null ? email : returnVeValue(getValueExpression("email")); } public void setEmail(String email) { this.email = email; } public String getRating() { return rating != null ? rating : returnVeValue(getValueExpression("rating")); } public void setRating(String rating) { this.rating = rating; } public String getDefaultImg() { return defaultImg != null ? defaultImg : returnVeValue(getValueExpression("defaultImg")); } public void setDefaultImg(String defaultImg) { this.defaultImg = defaultImg; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } private String returnVeValue(ValueExpression ve) { return ve != null ? (String) ve.getValue(getELContext()) : null; } private ELContext getELContext() { return FacesContext.getCurrentInstance().getELContext(); } }
package de.ellpeck.naturesaura.blocks.tiles; import de.ellpeck.naturesaura.api.NaturesAuraAPI; import de.ellpeck.naturesaura.api.aura.chunk.IAuraChunk; import de.ellpeck.naturesaura.api.aura.container.BasicAuraContainer; import de.ellpeck.naturesaura.api.aura.container.IAuraContainer; import de.ellpeck.naturesaura.api.aura.type.IAuraType; import de.ellpeck.naturesaura.blocks.multi.Multiblocks; import de.ellpeck.naturesaura.packet.PacketHandler; import de.ellpeck.naturesaura.packet.PacketParticleStream; import de.ellpeck.naturesaura.packet.PacketParticles; import de.ellpeck.naturesaura.recipes.AltarRecipe; import de.ellpeck.naturesaura.recipes.ModRecipes; import net.minecraft.block.BlockState; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemStackHandler; import java.util.Random; public class TileEntityNatureAltar extends TileEntityImpl implements ITickableTileEntity { private final BasicAuraContainer container = new BasicAuraContainer(null, 500000) { @Override public int getAuraColor() { return IAuraType.forWorld(TileEntityNatureAltar.this.world).getColor(); } }; private final ItemStack[] catalysts = new ItemStack[4]; public final ItemStackHandler items = new ItemStackHandlerNA(1, this, true) { @Override public int getSlotLimit(int slot) { return 1; } @Override protected boolean canInsert(ItemStack stack, int slot) { return TileEntityNatureAltar.this.getRecipeForInput(stack) != null || stack.getCapability(NaturesAuraAPI.capAuraContainer, null).isPresent(); } @Override protected boolean canExtract(ItemStack stack, int slot, int amount) { IAuraContainer cap = stack.getCapability(NaturesAuraAPI.capAuraContainer, null).orElse(null); if (cap != null) return cap.storeAura(1, true) <= 0; else return TileEntityNatureAltar.this.getRecipeForInput(stack) == null; } }; @OnlyIn(Dist.CLIENT) public int bobTimer; public StructureState structureState = StructureState.INVALID; private AltarRecipe currentRecipe; private int timer; private int lastAura; private boolean firstTick = true; public TileEntityNatureAltar() { super(ModTileEntities.NATURE_ALTAR); } @Override public void tick() { Random rand = this.world.rand; if (this.world.getGameTime() % 40 == 0) { int index = 0; for (int x = -2; x <= 2; x += 4) { for (int z = -2; z <= 2; z += 4) { BlockPos offset = this.pos.add(x, 1, z); BlockState state = this.world.getBlockState(offset); this.catalysts[index] = state.getBlock().getItem(this.world, offset, state); index++; } } } if (!this.world.isRemote) { if (this.world.getGameTime() % 40 == 0 || this.firstTick) { StructureState newState = this.getNewState(); if (newState != this.structureState) { this.structureState = newState; this.sendToClients(); } this.firstTick = false; } if (this.structureState != StructureState.INVALID) { int space = this.container.storeAura(300, true); IAuraType expectedType = this.structureState == StructureState.NETHER ? NaturesAuraAPI.TYPE_NETHER : NaturesAuraAPI.TYPE_OVERWORLD; if (space > 0 && IAuraType.forWorld(this.world).isSimilar(expectedType)) { int toStore = Math.min(IAuraChunk.getAuraInArea(this.world, this.pos, 20), space); if (toStore > 0) { BlockPos spot = IAuraChunk.getHighestSpot(this.world, this.pos, 20, this.pos); IAuraChunk chunk = IAuraChunk.getAuraChunk(this.world, spot); chunk.drainAura(spot, toStore); this.container.storeAura(toStore, false); if (this.world.getGameTime() % 3 == 0) PacketHandler.sendToAllAround(this.world, this.pos, 32, new PacketParticleStream( this.pos.getX() + (float) rand.nextGaussian() * 10F, this.pos.getY() + rand.nextFloat() * 10F, this.pos.getZ() + (float) rand.nextGaussian() * 10F, this.pos.getX() + 0.5F, this.pos.getY() + 0.5F, this.pos.getZ() + 0.5F, rand.nextFloat() * 0.1F + 0.1F, this.container.getAuraColor(), rand.nextFloat() * 1F + 1F )); } } ItemStack stack = this.items.getStackInSlot(0); IAuraContainer container = stack.getCapability(NaturesAuraAPI.capAuraContainer, null).orElse(null); if (!stack.isEmpty() && container != null) { int theoreticalDrain = this.container.drainAura(1000, true); if (theoreticalDrain > 0) { int stored = container.storeAura(theoreticalDrain, false); if (stored > 0) { this.container.drainAura(stored, false); if (this.world.getGameTime() % 4 == 0) PacketHandler.sendToAllAround(this.world, this.pos, 32, new PacketParticles(this.pos.getX(), this.pos.getY(), this.pos.getZ(), PacketParticles.Type.ALTAR_CONVERSION, this.container.getAuraColor())); } } } else { if (this.currentRecipe == null) { if (!stack.isEmpty()) { this.currentRecipe = this.getRecipeForInput(stack); } } else { if (stack.isEmpty() || !this.currentRecipe.input.test(stack)) { this.currentRecipe = null; this.timer = 0; } else { int req = MathHelper.ceil(this.currentRecipe.aura / (double) this.currentRecipe.time); if (this.container.getStoredAura() >= req) { this.container.drainAura(req, false); if (this.timer % 4 == 0) PacketHandler.sendToAllAround(this.world, this.pos, 32, new PacketParticles(this.pos.getX(), this.pos.getY(), this.pos.getZ(), PacketParticles.Type.ALTAR_CONVERSION, this.container.getAuraColor())); this.timer++; if (this.timer >= this.currentRecipe.time) { this.items.setStackInSlot(0, this.currentRecipe.output.copy()); this.currentRecipe = null; this.timer = 0; this.world.playSound(null, this.pos.getX() + 0.5, this.pos.getY() + 0.5, this.pos.getZ() + 0.5, SoundEvents.ENTITY_ARROW_HIT_PLAYER, SoundCategory.BLOCKS, 0.65F, 1F); } } } } } } if (this.world.getGameTime() % 10 == 0 && this.lastAura != this.container.getStoredAura()) { this.lastAura = this.container.getStoredAura(); this.sendToClients(); } } else { if (this.structureState != StructureState.INVALID) { if (rand.nextFloat() >= 0.7F) { int fourths = this.container.getMaxAura() / 4; if (this.container.getStoredAura() > 0) { NaturesAuraAPI.instance().spawnMagicParticle( this.pos.getX() - 4F + rand.nextFloat(), this.pos.getY() + 3F, this.pos.getZ() + rand.nextFloat(), 0F, 0F, 0F, this.container.getAuraColor(), rand.nextFloat() * 3F + 1F, rand.nextInt(100) + 50, -0.05F, true, true); } if (this.container.getStoredAura() >= fourths) { NaturesAuraAPI.instance().spawnMagicParticle( this.pos.getX() + 4F + rand.nextFloat(), this.pos.getY() + 3F, this.pos.getZ() + rand.nextFloat(), 0F, 0F, 0F, this.container.getAuraColor(), rand.nextFloat() * 3F + 1F, rand.nextInt(100) + 50, -0.05F, true, true); } if (this.container.getStoredAura() >= fourths * 2) { NaturesAuraAPI.instance().spawnMagicParticle( this.pos.getX() + rand.nextFloat(), this.pos.getY() + 3F, this.pos.getZ() - 4F + rand.nextFloat(), 0F, 0F, 0F, this.container.getAuraColor(), rand.nextFloat() * 3F + 1F, rand.nextInt(100) + 50, -0.05F, true, true); } if (this.container.getStoredAura() >= fourths * 3) { NaturesAuraAPI.instance().spawnMagicParticle( this.pos.getX() + rand.nextFloat(), this.pos.getY() + 3F, this.pos.getZ() + 4F + rand.nextFloat(), 0F, 0F, 0F, this.container.getAuraColor(), rand.nextFloat() * 3F + 1F, rand.nextInt(100) + 50, -0.05F, true, true); } } } this.bobTimer++; } } private AltarRecipe getRecipeForInput(ItemStack input) { IAuraType type = IAuraType.forWorld(this.world); for (AltarRecipe recipe : this.world.getRecipeManager().getRecipes(ModRecipes.ALTAR_TYPE, null, null)) { if (recipe.input.test(input) && (recipe.requiredType == null || type.isSimilar(recipe.requiredType))) { if (recipe.catalyst == Ingredient.EMPTY) return recipe; for (ItemStack stack : this.catalysts) if (recipe.catalyst.test(stack)) return recipe; } } return null; } private StructureState getNewState() { if (Multiblocks.ALTAR.isComplete(this.world, this.pos)) return StructureState.OVERWORLD; if (Multiblocks.NETHER_ALTAR.isComplete(this.world, this.pos)) return StructureState.NETHER; return StructureState.INVALID; } @Override public void writeNBT(CompoundNBT compound, SaveType type) { super.writeNBT(compound, type); if (type != SaveType.BLOCK) { compound.put("items", this.items.serializeNBT()); compound.putString("state", this.structureState.name()); this.container.writeNBT(compound); } if (type == SaveType.TILE) { if (this.currentRecipe != null) { compound.putString("recipe", this.currentRecipe.name.toString()); compound.putInt("timer", this.timer); } } } @Override public void readNBT(CompoundNBT compound, SaveType type) { super.readNBT(compound, type); if (type != SaveType.BLOCK) { this.items.deserializeNBT(compound.getCompound("items")); if (compound.contains("state")) this.structureState = StructureState.valueOf(compound.getString("state")); this.container.readNBT(compound); } if (type == SaveType.TILE) { if (compound.contains("recipe")) { if (this.hasWorld()) this.currentRecipe = (AltarRecipe) this.world.getRecipeManager().getRecipe(new ResourceLocation(compound.getString("recipe"))).orElse(null); this.timer = compound.getInt("timer"); } } } @Override public IAuraContainer getAuraContainer() { return this.container; } @Override public IItemHandlerModifiable getItemHandler() { return this.items; } public enum StructureState { INVALID, NETHER, OVERWORLD } }
/* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.joshuatacoma.bluesky; import java.util.Date; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { static final String TAG = "BlueSkyActivity"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onResume() { super.onResume(); try { // Gather values from incoming data. long agenda_need_seconds = 24*60*60; long agenda_capacity_bytes = 1024; long pebble_now_unix_time = new Date().getTime()/1000; // Convert to local data types and add fudge factor for end // time. long extra_time_multiplier = 4; long end_unix_time = pebble_now_unix_time + (agenda_need_seconds * extra_time_multiplier); // Create an intent that can cause MainService to send a // response. Intent sendAgendaIntent = new Intent(this, MainService.class) .setAction(BlueSkyConstants.ACTION_SEND_AGENDA) .putExtra( BlueSkyConstants.EXTRA_START_TIME, (long)pebble_now_unix_time*1000L) .putExtra( BlueSkyConstants.EXTRA_END_TIME, (long)end_unix_time*1000L) .putExtra( BlueSkyConstants.EXTRA_CAPACITY_BYTES, (int)agenda_capacity_bytes); if (startService(sendAgendaIntent)==null) { Log.e(TAG, "failed to send intent to service"); } } catch(Exception e) { Log.e(TAG, e.toString()); } } }
import java.util.Scanner; public class PythagoreanTriples { public static void main (String args []) { //Declare Variables int side1; int side2; int hyp; //Write loop for side 1 to try values from 1 - 500 for (side1 = 1; side1 <= 500; side1 ++) //Write loop for side 2 to try values from 1 - 500 for (side2 = 1; side2 <= 500; side2 ++) //Write loop for side 3 to try values 1 - 500 for (hyp = 1; hyp <= 500; hyp ++) //Determine if the the sides form a triangle and output results if (Math.pow(side1, 2) + Math.pow(side2, 2) == Math.pow(hyp, 2)) System.out.printf("s1: %d, s2: %d, hyp: %d\n" , side1 , side2 , hyp); }//end of main method }//end of class
/* * 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.baeldung.spring.cloud.helloworld; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class HelloWorldApplication { public static void main(String[] args) { SpringApplication.run(HelloWorldApplication.class, args); } }
package me.joeleoli.fairfight.check.impl.killaura; import me.joeleoli.fairfight.check.checks.PacketCheck; import me.joeleoli.fairfight.player.PlayerData; import me.joeleoli.fairfight.event.player.AlertType; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayInBlockDig; import net.minecraft.server.v1_8_R3.PacketPlayInFlying; import net.minecraft.server.v1_8_R3.PacketPlayInUseEntity; import org.bukkit.entity.Player; public class KillAuraH extends PacketCheck { private boolean sent; public KillAuraH(PlayerData playerData) { super(playerData, "Kill-Aura (Check 8)"); } @Override public void handleCheck(Player player, Packet packet) { if (packet instanceof PacketPlayInBlockDig) { final PacketPlayInBlockDig.EnumPlayerDigType digType = ((PacketPlayInBlockDig) packet).c(); if ((digType == PacketPlayInBlockDig.EnumPlayerDigType.START_DESTROY_BLOCK || digType == PacketPlayInBlockDig.EnumPlayerDigType.RELEASE_USE_ITEM) && this.sent && this.alert(AlertType .RELEASE, player, "", true)) { final int violations = this.playerData.getViolations(this, 60000L); if (!this.playerData.isBanning() && violations > 2) { this.ban(player); } } } else if (packet instanceof PacketPlayInUseEntity) { this.sent = true; } else if (packet instanceof PacketPlayInFlying) { this.sent = false; } } }
package org.avaje.resteasy; import org.jboss.resteasy.plugins.server.servlet.FilterDispatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Extends the Resteasy filter to support excluding configured urls * for serving static content extra with built-in default container servlets. * * <pre>{@code * * <filter> * <description>Extended Resteasy filter</description * <filter-name>RestFilter</filter-name> * <filter-class>org.avaje.resteasy.RestFilter</filter-class> * <init-param> * <param-name>ignore</param-name> * <param-value>(/favicon.ico|/(assets|images|fonts|css|js|res)/.*)</param-value> * </init-param> * </filter> * * <filter-mapping> * <filter-name>RestFilter</filter-name> * <url-pattern>/*</url-pattern> * </filter-mapping> * * }</pre> */ public class RestFilter extends FilterDispatcher { protected final Logger log = LoggerFactory.getLogger(RestFilter.class); protected Pattern ignorePattern; @Override public void init(FilterConfig config) throws ServletException { log.debug("init"); super.init(config); String regex = config.getInitParameter("ignore"); if (regex != null && regex.length() > 0) { try { ignorePattern = Pattern.compile(regex); } catch (PatternSyntaxException ex) { throw new ServletException("Invalid regular expression [" + regex + "] for parameter ignore", ex); } } } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest)) { chain.doFilter(req, res); } else { HttpServletRequest hreq = (HttpServletRequest) req; HttpServletResponse hres = (HttpServletResponse) res; String servletPath = hreq.getServletPath(); if (ignorePattern != null && ignorePattern.matcher(servletPath).matches()) { // ignore for css, javascript and images etc chain.doFilter(req, res); return; } preHttpRequest(hreq, hres); super.doFilter(req, res, chain); postHttpRequest(hreq, hres); } } /** * To override as desired. */ protected void preHttpRequest(HttpServletRequest hreq, HttpServletResponse hres) { // do nothing } /** * To override as desired. */ protected void postHttpRequest(HttpServletRequest hreq, HttpServletResponse hres) { // Clear the MDC Context MDC.clear(); } }
/* * 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.seaborne.delta.systemtest; import java.io.IOException; import java.util.Properties; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException; import org.apache.zookeeper.server.quorum.QuorumPeerMain; import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier; import org.seaborne.delta.zk.ZkS; public class ZkM { /** * Run an ensemble. * Untested. * * @param basePort * @param dataDir * @see ZkS#runZookeeperServer(String) */ public static void runZookeeperEnsemble(int basePort, String dataDir) { // Servers are: zk1, zk2, zk3. server(1, basePort, dataDir); server(2, basePort, dataDir); server(3, basePort, dataDir); } /** ZooKeeper server {@code i} */ private static void server(int i, int basePort, String rootDir) { /* tickTime=2000 initLimit=5 syncLimit=2 dataDir=/home/afs/ASF/rdf-delta-dev/zk/zk1/ZkData clientPort=2181 adminPort=2191 admin.enableServer=false server.1=localhost:2281:3381 server.2=localhost:2282:3382 server.3=localhost:2283:3383 */ /* The complete list of static properties: // dataDir // dataLogDir // clientPort // localSessionsEnabled // localSessionsUpgradingEnabled // clientPortAddress // secureClientPort // secureClientPortAddress // tickTime // maxClientCnxns // minSessionTimeout // maxSessionTimeout // initLimit // syncLimit // electionAlg // quorumListenOnAllIPs // peerType: "observer", "participant" // syncEnabled // dynamicConfigFile // autopurge.snapRetainCount // autopurge.purgeInterval // standaloneEnabled // reconfigEnabled */ int clientPort = 2180 + i; int baseSysPort = 2280; int baseElectionPort = 2380; String dir = "zk/zk"+i; if ( rootDir != null ) dir = rootDir+"/"+dir; Properties staticProperties = new Properties(); Properties dynamicProperties = new Properties(); staticProperties.setProperty("tickTime", "2000"); staticProperties.setProperty("dataDir", dir); staticProperties.setProperty("initLimit", "5") ; staticProperties.setProperty("syncLimit", "2") ; staticProperties.setProperty("clientPort", Integer.toString(clientPort)); for ( int j = 1 ; i <=3 ; i++ ) dynamicProperties.setProperty("server."+j, "localhost:"+(baseSysPort+j)+":"+(baseElectionPort+j) ); try { QuorumPeerConfig c = new QuorumPeerConfig(); c.parseProperties(staticProperties); QuorumVerifier qv = QuorumPeerConfig.parseDynamicConfig(dynamicProperties, 3, true, false); QuorumPeerMain quorumPeer = new QuorumPeerMain(); new Thread(()-> { try { quorumPeer.runFromConfig(c); } catch (Exception e) { e.printStackTrace(); } }); } catch (IOException e1) { e1.printStackTrace(); } catch (ConfigException e1) { e1.printStackTrace(); } } }
package io.collap.bryg.compiler.ast.expression.arithmetic; import bryg.org.objectweb.asm.Opcodes; import io.collap.bryg.compiler.ast.expression.Expression; import io.collap.bryg.compiler.context.Context; import io.collap.bryg.parser.BrygParser; public class BinaryDivisionExpression extends BinaryArithmeticExpression { public BinaryDivisionExpression (Context context, BrygParser.ExpressionContext leftCtx, BrygParser.ExpressionContext rightCtx) { super (context, leftCtx, rightCtx); } public BinaryDivisionExpression (Context context, Expression left, Expression right, int line) { super (context, left, right, line); } @Override protected int getOpcode () { return Opcodes.IDIV; } }
package com.kn.diagrams.generator.settings; import com.intellij.openapi.options.Configurable; import com.kn.diagrams.generator.graph.ProjectClassification; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import static com.kn.diagrams.generator.config.SerializationKt.getSerializer; import static com.kn.diagrams.generator.config.SerializationKt.toJsonWithComments; public class DiagramGeneratorSettingsPage implements Configurable { private JPanel panel; private JTextArea projectClassification; private JTextArea callDiagramDefaults; private JTextArea structureDiagramDefaults; private JTextArea flowDiagramDefaults; private JButton resetStructureDiagramDefaults; private JButton resetFlowDiagramDefaults; private JButton resetCallDiagramDefaults; private JButton resetClassification; public DiagramGeneratorSettingsPage() { resetClassification.addActionListener(e -> projectClassification.setText(toJsonWithComments(new ProjectClassification()))); resetCallDiagramDefaults.addActionListener(e -> callDiagramDefaults.setText(toJsonWithComments(new CallConfigurationDefaults().defaulted()))); resetStructureDiagramDefaults.addActionListener(e -> structureDiagramDefaults.setText(toJsonWithComments(new StructureConfigurationDefaults().defaulted()))); resetFlowDiagramDefaults.addActionListener(e -> flowDiagramDefaults.setText(toJsonWithComments(new FlowConfigurationDefaults().defaulted()))); } @Nls @Override public String getDisplayName() { return "Diagram Generation"; } @Nullable @Override public String getHelpTopic() { return null; } @Nullable @Override public JComponent createComponent() { return panel; } @Override public boolean isModified() { return isModified(DiagramGenerationSettings.getInstance()); } @Override public void apply() { DiagramGenerationSettings instance = DiagramGenerationSettings.getInstance(); getData(instance); } @Override public void reset() { DiagramGenerationSettings newInstance = DiagramGenerationSettings.getInstance(); setData(newInstance); } @Override public void disposeUIResources() { } public void setData(DiagramGenerationSettings data) { projectClassification.setText(data.getProjectClassification()); callDiagramDefaults.setText(data.getCallDiagramDefaults()); structureDiagramDefaults.setText(data.getStructureDiagramDefaults()); flowDiagramDefaults.setText(data.getFlowDiagramDefaults()); } public void getData(DiagramGenerationSettings data) { data.setProjectClassification(roundTripSerialization(projectClassification.getText(), ProjectClassification.class)); data.setCallDiagramDefaults(roundTripSerialization(callDiagramDefaults.getText(), CallConfigurationDefaults.class)); data.setStructureDiagramDefaults(roundTripSerialization(structureDiagramDefaults.getText(), StructureConfigurationDefaults.class)); data.setFlowDiagramDefaults(roundTripSerialization(flowDiagramDefaults.getText(), FlowConfigurationDefaults.class)); } private String roundTripSerialization(String text, Class<?> clazz){ return toJsonWithComments(getSerializer().fromJson(text, clazz)); } public boolean isModified(DiagramGenerationSettings data) { return !projectClassification.getText().equals(data.getProjectClassification()) || !callDiagramDefaults.getText().equals(data.getProjectClassification()) || !structureDiagramDefaults.getText().equals(data.getProjectClassification()) || !flowDiagramDefaults.getText().equals(data.getProjectClassification()); } }
package cn.licoy.wdog.core.dto.appot; import org.hibernate.validator.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; /** * @author mc * @version Tue Dec 15 19:38:18 2020 */ @Data public class WechatUserAddDTO{ @NotBlank(message = "id") private String id; @NotBlank(message = "country") private String country; @NotBlank(message = "province") private String province; @NotBlank(message = "city") private String city; @NotBlank(message = "openid") private String openid; @NotBlank(message = "mobile") private String mobile; @NotBlank(message = "sex") private String sex; @NotBlank(message = "nickname") private String nickname; @NotBlank(message = "headimgurl") private String headimgurl; @NotBlank(message = "language") private String language; @NotBlank(message = "privilege") private String privilege; @NotBlank(message = "createDate") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date createDate; @NotBlank(message = "fromVenueId") private String fromVenueId; @NotBlank(message = "venueName") private String venueName; @NotBlank(message = "idcard") private String idcard; @NotBlank(message = "intro") private String intro; }
package com.morristaedt.mirror; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewStub; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import com.morristaedt.mirror.configuration.ConfigurationSettings; import com.morristaedt.mirror.modules.CalendarModule; import com.morristaedt.mirror.modules.DayModule; import com.morristaedt.mirror.modules.ForecastModule; import com.morristaedt.mirror.modules.SeptaTravelAlertModule; import com.morristaedt.mirror.receiver.AlarmReceiver; import java.util.List; import io.flic.lib.FlicBroadcastReceiverFlags; import io.flic.lib.FlicButton; import io.flic.lib.FlicButtonCallback; import io.flic.lib.FlicButtonCallbackFlags; import io.flic.lib.FlicManager; import io.flic.lib.FlicManagerInitializedCallback; /** * Created by Lee on 4/24/2016. */ public class MirrorSeptaTravelAlert extends AppCompatActivity { private static final String TAG = "MirrorSeptaTravelAlert"; private FlicManager manager; @NonNull private ConfigurationSettings mConfigSettings; private TextView mSeptaAlert; private VerticalTextView mDayText; private VerticalTextView mWeatherSummary; private VerticalTextView mCalendarTitleText; private VerticalTextView mCalendarDetailsText; /* Updates the Septa travel Alert Module */ private SeptaTravelAlertModule.SeptaListener mSeptaListener = new SeptaTravelAlertModule.SeptaListener() { @Override public void onNewAlert(String alert) { if (TextUtils.isEmpty(alert)) { mSeptaAlert.setVisibility(View.GONE); } else { mSeptaAlert.setVisibility(View.VISIBLE); mSeptaAlert.setText(alert); mSeptaAlert.setSelected(true); } } }; /* Updates the calender module view */ private CalendarModule.CalendarListener mCalendarListener = new CalendarModule.CalendarListener() { @Override public void onCalendarUpdate(String title, String details) { mCalendarTitleText.setVisibility(title != null ? View.VISIBLE : View.GONE); mCalendarTitleText.setText(title); mCalendarDetailsText.setVisibility(details != null ? View.VISIBLE : View.GONE); mCalendarDetailsText.setText(details); //Make marquee effect work for long text mCalendarTitleText.setSelected(true); mCalendarDetailsText.setSelected(true); } }; /* Updates the forecast module view */ private ForecastModule.ForecastListener mForecastListener = new ForecastModule.ForecastListener() { @Override public void onWeatherToday(String weatherToday) { if (!TextUtils.isEmpty(weatherToday)) { mWeatherSummary.setVisibility(View.VISIBLE); mWeatherSummary.setText(weatherToday); } } }; /** * The onCreate method runs as soon as the activity is called * @param savedInstanceState */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mirror); mConfigSettings = new ConfigurationSettings(this); AlarmReceiver.startMirrorUpdates(this); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_IMMERSIVE; decorView.setSystemUiVisibility(uiOptions); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); } //Flic Button FlicManager.setAppCredentials(getString(R.string.flic_appID), getString(R.string.flic_appSecret), getString(R.string.flic_appName)); FlicManager.getInstance(this, new FlicManagerInitializedCallback() { @Override public void onInitialized(FlicManager manager) { Log.d(TAG, "Ready to use manager"); MirrorSeptaTravelAlert.this.manager = manager; // Restore buttons grabbed in a previous run of the activity List<FlicButton> buttons = manager.getKnownButtons(); for (FlicButton button : buttons) { String status = null; switch (button.getConnectionStatus()) { case FlicButton.BUTTON_DISCONNECTED: status = "disconnected"; break; case FlicButton.BUTTON_CONNECTION_STARTED: status = "connection started"; break; case FlicButton.BUTTON_CONNECTION_COMPLETED: status = "connection completed"; break; } Log.d(TAG, "Found an existing button: " + button + ", status: " + status); setButtonCallback(button); } } }); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); ViewStub stubSepta = (ViewStub) findViewById(R.id.layout_stub); stubSepta.setLayoutResource(R.layout.screen_septa_travel_alert); stubSepta.inflate(); mSeptaAlert = (com.morristaedt.mirror.VerticalTextView) findViewById(R.id.septa_alert); mDayText = (com.morristaedt.mirror.VerticalTextView) findViewById(R.id.day_text); mWeatherSummary = (com.morristaedt.mirror.VerticalTextView) findViewById(R.id.weather_summary); mCalendarTitleText = (com.morristaedt.mirror.VerticalTextView) findViewById(R.id.calendar_title); mCalendarDetailsText = (com.morristaedt.mirror.VerticalTextView) findViewById(R.id.calendar_details); setViewState(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setViewState(); } private void setViewState() { mDayText.setText(DayModule.getDay()); int forecastApiKeyRes = getResources().getIdentifier("dark_sky_api_key", "string", getPackageName()); int openWeatherApiKeyRes = getResources().getIdentifier("open_weather_api_key", "string", getPackageName()); if (forecastApiKeyRes != 0) { ForecastModule.getForecastIOHourlyForecast(getString(forecastApiKeyRes), mConfigSettings.getForecastUnits(), mConfigSettings.getLatitude(), mConfigSettings.getLongitude(), mForecastListener); } else if (openWeatherApiKeyRes != 0) { ForecastModule.getOpenWeatherForecast(getString(openWeatherApiKeyRes), mConfigSettings.getForecastUnits(), mConfigSettings.getLatitude(), mConfigSettings.getLongitude(), mForecastListener); } if (mConfigSettings.showNextCalendarEvent()) { CalendarModule.getCalendarEvents(this, mCalendarListener); } else { mCalendarTitleText.setVisibility(View.GONE); mCalendarDetailsText.setVisibility(View.GONE); } SeptaTravelAlertModule.getTravelAlert(mSeptaListener); } private void setButtonCallback(FlicButton button) { button.removeAllFlicButtonCallbacks(); button.addFlicButtonCallback(buttonCallback); button.setFlicButtonCallbackFlags(FlicButtonCallbackFlags.UP_OR_DOWN); button.setActiveMode(true); } private FlicButtonCallback buttonCallback = new FlicButtonCallback() { @Override public void onButtonUpOrDown(FlicButton button, boolean wasQueued, int timeDiff, boolean isUp, boolean isDown) { final String text = button + " was " + (isDown ? "pressed" : "released"); Log.d(TAG, text); if (!isDown) { Intent intent = new Intent(MirrorSeptaTravelAlert.this, MirrorSeptaStationStatus.class); startActivity(intent); return; } } }; public void grabButton(View v) { if (manager != null) { manager.initiateGrabButton(this); } } @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { Log.d("OnActivity", "True"); FlicManager.getInstance(this, new FlicManagerInitializedCallback() { @Override public void onInitialized(FlicManager manager) { FlicButton button = manager.completeGrabButton(requestCode, resultCode, data); if (button != null) { button.registerListenForBroadcast(FlicBroadcastReceiverFlags.UP_OR_DOWN | FlicBroadcastReceiverFlags.REMOVED); Toast.makeText(MirrorSeptaTravelAlert.this, "Grabbed a button", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MirrorSeptaTravelAlert.this, "Did not grab any button", Toast.LENGTH_SHORT).show(); } } }); } }
package two.buttons.prove.mastermind.service; import two.buttons.prove.mastermind.beans.ColorEnum; import two.buttons.prove.mastermind.model.DTO.GuessResponse; import two.buttons.prove.mastermind.model.Game; import two.buttons.prove.mastermind.model.Guess; import java.util.List; public interface GuessService { GuessResponse builGuessResponse(Game game, Guess guess); Guess buildGuess(List<ColorEnum> guessCode, List<ColorEnum> code); }
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual 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.jboss.pnc.datastore.repositories.internal; import org.jboss.pnc.model.License; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface LicenseSpringRepository extends JpaRepository<License, Integer>, JpaSpecificationExecutor<License> { }
package com.wufan.vueblog; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class VueblogApplicationTests { @Test void contextLoads() { } }
/* * Copyright 2019 Web3 Labs LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.storm3j.exceptions; /** Encoding exception. */ public class MessageEncodingException extends RuntimeException { public MessageEncodingException(String message) { super(message); } public MessageEncodingException(String message, Throwable cause) { super(message, cause); } }
/* * Copyright (c) 2013-2018, Bingo.Chen (finesoft@gmail.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 org.corant.suites.ddd.annotation.stereotype; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.enterprise.inject.Stereotype; import org.corant.suites.ddd.message.Message.MessageHandling; /** * @author bingo 下午6:51:41 * */ @Documented @Retention(RUNTIME) @Target({TYPE, FIELD, METHOD}) @Inherited @Stereotype public @interface MessageHandlings { Class<? extends MessageHandling> handling(); }
/** * Copyright (C) 2014 android10.org. All rights reserved. * * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.order.presentation.view.fragment; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.fernandocejas.android10.R; import com.fernandocejas.android10.order.presentation.internal.di.components.OrderComponent; import com.fernandocejas.android10.order.presentation.model.CountryModel; import com.fernandocejas.android10.order.presentation.presenter.PhoneCodeListPresenter; import com.fernandocejas.android10.order.presentation.utils.DialogFactory; import com.fernandocejas.android10.order.presentation.view.PhoneCodeListView; import com.fernandocejas.android10.order.presentation.view.adapter.CountryAdapter; import com.fernandocejas.android10.sample.presentation.view.fragment.BaseFragment; import java.util.Collection; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * * */ public class PhoneCodeListFragment extends BaseFragment implements PhoneCodeListView { @Inject PhoneCodeListPresenter phoneCodeListPresenter; @Inject CountryAdapter countryAdapter; @Bind(R.id.rv_phone) RecyclerView rv_phone; private ProgressDialog progressDialog; public PhoneCodeListFragment() { setRetainInstance(true); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getComponent(OrderComponent.class).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View fragmentView = inflater.inflate(R.layout.fragment_phone_code_list, container, false); ButterKnife.bind(this, fragmentView); setupRecyclerView(); return fragmentView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.phoneCodeListPresenter.setView(this); if (savedInstanceState == null) { loadCountryList(); } } @Override public void onResume() { super.onResume(); this.phoneCodeListPresenter.resume(); } @Override public void onPause() { super.onPause(); this.phoneCodeListPresenter.pause(); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onDestroy() { super.onDestroy(); this.phoneCodeListPresenter.destroy(); } @Override public void onDetach() { super.onDetach(); this.phoneCodeListPresenter = null; } @Override public void showLoading() { if (progressDialog == null) { progressDialog = DialogFactory.createProgressDialog(activity(), R.string.processing); } progressDialog.show(); } @Override public void hideLoading() { if (progressDialog != null) { progressDialog.dismiss(); } } @Override public void showRetry() { } @Override public void hideRetry() { } @Override public void showError(String message) { Toast.makeText(activity(), message, Toast.LENGTH_SHORT).show(); } @Override public Context context() { return getActivity().getApplicationContext(); } @Override public Activity activity() { return getActivity(); } private void setupRecyclerView() { this.countryAdapter.setOnItemClickListener(countryModel -> { this.phoneCodeListPresenter.onCountryClicked(countryModel); }); this.rv_phone.setLayoutManager(new LinearLayoutManager(context())); this.rv_phone.setAdapter(this.countryAdapter); } private void loadCountryList() { this.phoneCodeListPresenter.initialize(); } @Override @OnClick(R.id.btn_back) public void onBackClicked() { this.phoneCodeListPresenter.navigationVerifyPhone(); } @Override public void renderPhoneCodeList(Collection<CountryModel> countryModelCollection) { if (countryModelCollection != null) { this.countryAdapter.setCountriesCollection(countryModelCollection); } } }
package cn.edu.hzau.tmall.entity; import java.util.List; /** * 类型实体类 * @author llc */ public class Category { private Integer category_id/*类型ID*/; private String category_name/*类型名称*/; private String category_image_src/*类型图片路径*/; private List<Property> propertyList/*属性列表*/; private List<Product> productList/*产品集合*/; private List<List<Product>> complexProductList/*产品二维集合*/; @Override public String toString() { return "Category{" + "category_id=" + category_id + ", category_name='" + category_name + '\'' + ", category_image_src='" + category_image_src + '\'' + '}'; } public Category(){ } public Category(Integer category_id, String category_name, String category_image_src) { this.category_id = category_id; this.category_name = category_name; this.category_image_src = category_image_src; } public Integer getCategory_id() { return category_id; } public Category setCategory_id(Integer category_id) { this.category_id = category_id; return this; } public String getCategory_name() { return category_name; } public Category setCategory_name(String category_name) { this.category_name = category_name; return this; } public String getCategory_image_src() { return category_image_src; } public Category setCategory_image_src(String category_image_src) { this.category_image_src = category_image_src; return this; } public List<List<Product>> getComplexProductList() { return complexProductList; } public Category setComplexProductList(List<List<Product>> productList) { this.complexProductList = productList; return this; } public List<Property> getPropertyList() { return propertyList; } public Category setPropertyList(List<Property> propertyList) { this.propertyList = propertyList; return this; } public List<Product> getProductList() { return productList; } public Category setProductList(List<Product> productList) { this.productList = productList; return this; } }
package com.besscroft.lfs; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @Slf4j @SpringBootApplication public class LfsAdminApplication { public static void main(String[] args) { SpringApplication.run(LfsAdminApplication.class, args); log.info("(♥◠‿◠)ノ゙ LFS服务启动成功 ლ(´ڡ`ლ)゙ \n"); } }
package com.bkhech.home.practice.distributed.基本限流算法及思想.滑动窗口; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * 限流方法(滑动时间算法/时间窗口算法) * @author guowm * @date 2021/6/29 */ @Slf4j public class WindowLimiter { /** * 一个时间窗口,单位是毫秒 */ private final long timeWindow; /** * 每个slot的时间段,单位是毫秒 */ private final long slotTime; /** * 一个时间窗口分割多少块(slot数量) */ private final long slot; /** * 一个时间窗口限制的次数(在一个完整窗口期内允许通过的最大阈值) */ private final long threshold; private final LoadingCache<Long, AtomicLong> counter; public WindowLimiter(int timeWindowSecond, int slotTime, int threshold) { // JVM 单线程初始化构造方法,保证绝对线程安全 // if (counter == null) { // synchronized (this) { // if (counter == null) { this.timeWindow = TimeUnit.SECONDS.toMillis(timeWindowSecond); this.slotTime = slotTime; this.slot = this.timeWindow / this.slotTime + (this.timeWindow % this.slotTime == 0 ? 0 : 1); this.threshold = threshold; counter = CacheBuilder.newBuilder() .expireAfterWrite(slotTime, TimeUnit.MILLISECONDS) .build(new CacheLoader<Long, AtomicLong>() { @Override public AtomicLong load(Long millis) throws Exception { return new AtomicLong(0L); } }); // } // } // } } /** * @param currentTime 当前时间戳, 单位是毫秒 * @return 是否限流, true 是 */ public boolean tryAcquire(long currentTime) { long key = currentTime / this.slotTime; try { long nums = 0; // slot windows timeWindowSecond for (long i = 0; i < slot; i = i+slotTime) { nums += counter.get(key - i).get(); } log.info("key=" + key + ",nums=" + nums); if (nums > threshold) { // log.info("限流了,nums=" + nums); return false; } // 没达到阈值,则访问次数加1 counter.get(key).incrementAndGet(); return true; } catch (Exception e) { log.error("slideWindow error", e); return false; } } public static void main(String[] args) { final WindowLimiter windowLimiter = new WindowLimiter(4, 2000, 15); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5); scheduledExecutorService.scheduleWithFixedDelay(() -> { try { //每秒发送随机数量的请求 int reqs = (int) (Math.random() * 5) + 1; final ConcurrentMap<Long, AtomicLong> longAtomicLongConcurrentMap = windowLimiter.counter.asMap(); longAtomicLongConcurrentMap.forEach((key,value) -> { System.out.println(String.join(":", "key", String.valueOf(key), ", value", value.toString())); }); for (int i = 0; i < reqs; i++) { windowLimiter.tryAcquire(System.currentTimeMillis()); } } catch (Exception e) { log.error("slideWindow error", e); } }, 1000, 100, TimeUnit.MILLISECONDS); } }
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* Primitive-type-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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.unimi.dsi.fastutil.longs; import it.unimi.dsi.fastutil.shorts.ShortCollection; import it.unimi.dsi.fastutil.shorts.AbstractShortCollection; import it.unimi.dsi.fastutil.shorts.ShortIterator; import it.unimi.dsi.fastutil.shorts.AbstractShortIterator; import it.unimi.dsi.fastutil.objects.ObjectSet; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.util.Iterator; import java.util.Map; /** An abstract class providing basic methods for maps implementing a type-specific interface. * * <P>Optional operations just throw an {@link * UnsupportedOperationException}. Generic versions of accessors delegate to * the corresponding type-specific counterparts following the interface rules * (they take care of returning <code>null</code> on a missing key). * * <P>As a further help, this class provides a {@link BasicEntry BasicEntry} inner class * that implements a type-specific version of {@link java.util.Map.Entry}; it * is particularly useful for those classes that do not implement their own * entries (e.g., most immutable maps). */ public abstract class AbstractLong2ShortMap extends AbstractLong2ShortFunction implements Long2ShortMap , java.io.Serializable { private static final long serialVersionUID = -4940583368468432370L; protected AbstractLong2ShortMap() {} public boolean containsValue( Object ov ) { return containsValue( ((((Short)(ov)).shortValue())) ); } /** Checks whether the given value is contained in {@link #values()}. */ public boolean containsValue( short v ) { return values().contains( v ); } /** Checks whether the given value is contained in {@link #keySet()}. */ public boolean containsKey( long k ) { return keySet().contains( k ); } /** Puts all pairs in the given map. * If the map implements the interface of this map, * it uses the faster iterators. * * @param m a map. */ @SuppressWarnings("unchecked") public void putAll(Map<? extends Long,? extends Short> m) { int n = m.size(); final Iterator<? extends Map.Entry<? extends Long,? extends Short>> i = m.entrySet().iterator(); if (m instanceof Long2ShortMap) { Long2ShortMap.Entry e; while(n-- != 0) { e = (Long2ShortMap.Entry )i.next(); put(e.getLongKey(), e.getShortValue()); } } else { Map.Entry<? extends Long,? extends Short> e; while(n-- != 0) { e = i.next(); put(e.getKey(), e.getValue()); } } } public boolean isEmpty() { return size() == 0; } /** This class provides a basic but complete type-specific entry class for all those maps implementations * that do not have entries on their own (e.g., most immutable maps). * * <P>This class does not implement {@link java.util.Map.Entry#setValue(Object) setValue()}, as the modification * would not be reflected in the base map. */ public static class BasicEntry implements Long2ShortMap.Entry { protected long key; protected short value; public BasicEntry( final Long key, final Short value ) { this.key = ((key).longValue()); this.value = ((value).shortValue()); } public BasicEntry( final long key, final short value ) { this.key = key; this.value = value; } public Long getKey() { return (Long.valueOf(key)); } public long getLongKey() { return key; } public Short getValue() { return (Short.valueOf(value)); } public short getShortValue() { return value; } public short setValue( final short value ) { throw new UnsupportedOperationException(); } public Short setValue( final Short value ) { return Short.valueOf(setValue(value.shortValue())); } public boolean equals( final Object o ) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ( (key) == (((((Long)(e.getKey())).longValue()))) ) && ( (value) == (((((Short)(e.getValue())).shortValue()))) ); } public int hashCode() { return it.unimi.dsi.fastutil.HashCommon.long2int(key) ^ (value); } public String toString() { return key + "->" + value; } } /** Returns a type-specific-set view of the keys of this map. * * <P>The view is backed by the set returned by {@link #entrySet()}. Note that * <em>no attempt is made at caching the result of this method</em>, as this would * require adding some attributes that lightweight implementations would * not need. Subclasses may easily override this policy by calling * this method and caching the result, but implementors are encouraged to * write more efficient ad-hoc implementations. * * @return a set view of the keys of this map; it may be safely cast to a type-specific interface. */ public LongSet keySet() { return new AbstractLongSet () { public boolean contains( final long k ) { return containsKey( k ); } public int size() { return AbstractLong2ShortMap.this.size(); } public void clear() { AbstractLong2ShortMap.this.clear(); } public LongIterator iterator() { return new AbstractLongIterator () { final ObjectIterator<Map.Entry<Long,Short>> i = entrySet().iterator(); public long nextLong() { return ((Long2ShortMap.Entry )i.next()).getLongKey(); }; public boolean hasNext() { return i.hasNext(); } }; } }; } /** Returns a type-specific-set view of the values of this map. * * <P>The view is backed by the set returned by {@link #entrySet()}. Note that * <em>no attempt is made at caching the result of this method</em>, as this would * require adding some attributes that lightweight implementations would * not need. Subclasses may easily override this policy by calling * this method and caching the result, but implementors are encouraged to * write more efficient ad-hoc implementations. * * @return a set view of the values of this map; it may be safely cast to a type-specific interface. */ public ShortCollection values() { return new AbstractShortCollection () { public boolean contains( final short k ) { return containsValue( k ); } public int size() { return AbstractLong2ShortMap.this.size(); } public void clear() { AbstractLong2ShortMap.this.clear(); } public ShortIterator iterator() { return new AbstractShortIterator () { final ObjectIterator<Map.Entry<Long,Short>> i = entrySet().iterator(); public short nextShort() { return ((Long2ShortMap.Entry )i.next()).getShortValue(); }; public boolean hasNext() { return i.hasNext(); } }; } }; } @SuppressWarnings({ "unchecked", "rawtypes" }) public ObjectSet<Map.Entry<Long, Short>> entrySet() { return (ObjectSet)long2ShortEntrySet(); } /** Returns a hash code for this map. * * The hash code of a map is computed by summing the hash codes of its entries. * * @return a hash code for this map. */ public int hashCode() { int h = 0, n = size(); final ObjectIterator<? extends Map.Entry<Long,Short>> i = entrySet().iterator(); while( n-- != 0 ) h += i.next().hashCode(); return h; } public boolean equals(Object o) { if ( o == this ) return true; if ( ! ( o instanceof Map ) ) return false; Map<?,?> m = (Map<?,?>)o; if ( m.size() != size() ) return false; return entrySet().containsAll( m.entrySet() ); } public String toString() { final StringBuilder s = new StringBuilder(); final ObjectIterator<? extends Map.Entry<Long,Short>> i = entrySet().iterator(); int n = size(); Long2ShortMap.Entry e; boolean first = true; s.append("{"); while(n-- != 0) { if (first) first = false; else s.append(", "); e = (Long2ShortMap.Entry )i.next(); s.append(String.valueOf(e.getLongKey())); s.append("=>"); s.append(String.valueOf(e.getShortValue())); } s.append("}"); return s.toString(); } }
package Model; import java.util.Arrays; /** * * @author luiz */ public class Aluno { private int[] idade; public Aluno() { this.idade = new int[20]; } public int[] getIdade() { return idade; } public void setIdade(int[] idade) { this.idade = idade; } @Override public String toString() { return "Idades dos alunos: " +Arrays.toString(idade); } public void cadastrarIdade(int i,int idade){ this.idade[i] = idade; } public double calcularMedia(){ double acum = 0; for(int i=0; i<this.idade.length; i++){ acum = acum + this.idade[i]; } return acum/this.idade.length; } public double acharMaior(){ double maior = this.idade[0]; for(int i=0; i<this.idade.length; i++){ if(this.idade[i]>maior){ maior = this.idade[i]; } } return maior; } public int maiorDeIdade(){ int maiorIdade = 0; for(int i=0; i<this.idade.length; i++){ if(this.idade[i]>=18){ maiorIdade++; } } return maiorIdade; } }
/* Copyright 2007-2009 Selenium committers 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.openqa.selenium; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.InProject; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.JavascriptEnabled; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Ignore.Driver.*; public class ExecutingJavascriptTest extends JUnit4TestBase { @Before public void setUp() throws Exception { assumeTrue(driver instanceof JavascriptExecutor); } private Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAString() { driver.get(pages.xhtmlTestPage); Object result = executeScript("return document.title;"); assertTrue(result instanceof String); assertEquals("XHTML Test Page", result); } @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnALong() { driver.get(pages.nestedPage); Object result = executeScript("return document.getElementsByName('checky').length;"); assertTrue(result.getClass().getName(), result instanceof Long); assertTrue((Long) result > 1); } @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAWebElement() { driver.get(pages.xhtmlTestPage); Object result = executeScript("return document.getElementById('id1');"); assertNotNull(result); assertThat(result, instanceOf(WebElement.class)); assertEquals("a", ((WebElement) result).getTagName().toLowerCase()); } @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnABoolean() { driver.get(pages.xhtmlTestPage); Object result = executeScript("return true;"); assertNotNull(result); assertTrue(result instanceof Boolean); assertTrue((Boolean) result); } @SuppressWarnings("unchecked") @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAStringsArray() { driver.get(pages.javascriptPage); List<Object> expectedResult = new ArrayList<Object>(); expectedResult.add("zero"); expectedResult.add("one"); expectedResult.add("two"); Object result = ((JavascriptExecutor) driver).executeScript( "return ['zero', 'one', 'two'];"); ExecutingJavascriptTest.compareLists(expectedResult, (List<Object>) result); } @SuppressWarnings("unchecked") @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnArray() { driver.get(pages.javascriptPage); List<Object> expectedResult = new ArrayList<Object>(); expectedResult.add("zero"); List<Object> subList = new ArrayList<Object>(); subList.add(true); subList.add(false); expectedResult.add(subList); Object result = executeScript("return ['zero', [true, false]];"); assertNotNull(result); assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof List); List<Object> list = (List<Object>) result; assertTrue(compareLists(expectedResult, list)); } @SuppressWarnings("unchecked") @JavascriptEnabled @Test public void testShouldBeAbleToExecuteJavascriptAndReturnABasicObjectLiteral() { driver.get(pages.javascriptPage); Object result = executeScript("return {abc: '123', tired: false};"); assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); Map<String, Object> map = (Map<String, Object>) result; Map<String, Object> expected = new HashMap<String, Object>(); expected.put("abc", "123"); expected.put("tired", false); // Cannot do an exact match; Firefox 4 inserts a few extra keys in our object; this is OK, as // long as the expected keys are there. assertThat("Expected:<" + expected + ">, but was:<" + map + ">", map.size(), greaterThanOrEqualTo(expected.size())); for (Map.Entry<String, Object> entry : expected.entrySet()) { assertEquals("Difference at key:<" + entry.getKey() + ">", entry.getValue(), map.get(entry.getKey())); } } @SuppressWarnings("unchecked") @JavascriptEnabled @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnObjectLiteral() { driver.get(pages.javascriptPage); Map<String, Object> expectedResult = new HashMap<String, Object>() { { put("foo", "bar"); put("baz", Arrays.asList("a", "b", "c")); put("person", new HashMap<String, String>() { { put("first", "John"); put("last", "Doe"); } }); } }; Object result = executeScript( "return {foo:'bar', baz: ['a', 'b', 'c'], " + "person: {first: 'John',last: 'Doe'}};"); assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); Map<String, Object> map = (Map<String, Object>) result; assertThat("Expected:<" + expectedResult + ">, but was:<" + map + ">", map.size(), greaterThanOrEqualTo(3)); assertEquals("bar", map.get("foo")); assertTrue(compareLists((List<?>) expectedResult.get("baz"), (List<?>) map.get("baz"))); Map<String, String> person = (Map<String, String>) map.get("person"); assertThat("Expected:<{first:John, last:Doe}>, but was:<" + person + ">", person.size(), greaterThanOrEqualTo(2)); assertEquals("John", person.get("first")); assertEquals("Doe", person.get("last")); } @SuppressWarnings("unchecked") @JavascriptEnabled @Ignore({IE, OPERA, OPERA_MOBILE}) @Test public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAComplexObject() { driver.get(pages.javascriptPage); Object result = executeScript("return window.location;"); assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); Map<String, Object> map = (Map<String, Object>) result; assertEquals("http:", map.get("protocol")); assertEquals(pages.javascriptPage, map.get("href")); } private static boolean compareLists(List<?> first, List<?> second) { if (first.size() != second.size()) { return false; } for (int i = 0; i < first.size(); ++i) { if (first.get(i) instanceof List<?>) { if (!compareLists((List<?>) first.get(i), (List<?>) second.get(i))) { return false; } } else { if (!first.get(i).equals(second.get(i))) { return false; } } } return true; } @JavascriptEnabled @Test public void testPassingAndReturningALongShouldReturnAWholeNumber() { driver.get(pages.javascriptPage); Long expectedResult = 1L; Object result = executeScript("return arguments[0];", expectedResult); assertTrue("Expected result to be an Integer or Long but was a " + result.getClass(), result instanceof Integer || result instanceof Long); assertEquals(expectedResult, result); } @JavascriptEnabled @Test public void testPassingAndReturningADoubleShouldReturnADecimal() { driver.get(pages.javascriptPage); Double expectedResult = 1.2; Object result = executeScript("return arguments[0];", expectedResult); assertTrue("Expected result to be a Double or Float but was a " + result.getClass(), result instanceof Float || result instanceof Double); assertEquals(expectedResult, result); } @JavascriptEnabled @Test public void testShouldThrowAnExceptionWhenTheJavascriptIsBad() { driver.get(pages.xhtmlTestPage); try { executeScript("return squiggle();"); fail("Expected an exception"); } catch (WebDriverException e) { // This is expected assertFalse(e.getMessage(), e.getMessage().startsWith("null ")); } } @JavascriptEnabled @Test @Ignore(value = {ANDROID, CHROME, HTMLUNIT, IE, IPHONE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI, MARIONETTE, QTWEBKIT}) public void testShouldThrowAnExceptionWithMessageAndStacktraceWhenTheJavascriptIsBad() { driver.get(pages.xhtmlTestPage); String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; try { executeScript(js); fail("Expected an exception"); } catch (WebDriverException e) { assertThat(e.getMessage(), containsString("errormessage")); Throwable rootCause = Throwables.getRootCause(e); assertThat(rootCause.getMessage(), containsString("errormessage")); StackTraceElement [] st = rootCause.getStackTrace(); boolean seen = false; for (StackTraceElement s: st) { if (s.getMethodName().equals("functionB")) { seen = true; } } assertTrue("Stacktrace has not js method info", seen); } } @JavascriptEnabled @Test @Ignore(MARIONETTE) public void testShouldBeAbleToCallFunctionsDefinedOnThePage() { driver.get(pages.javascriptPage); executeScript("displayMessage('I like cheese');"); String text = driver.findElement(By.id("result")).getText(); assertEquals("I like cheese", text.trim()); } @JavascriptEnabled @Test public void testShouldBeAbleToPassAStringAnAsArgument() { driver.get(pages.javascriptPage); String value = (String) executeScript("return arguments[0] == 'fish' ? 'fish' : 'not fish';", "fish"); assertEquals("fish", value); } @JavascriptEnabled @Test public void testShouldBeAbleToPassABooleanAsArgument() { driver.get(pages.javascriptPage); boolean value = (Boolean) executeScript("return arguments[0] == true;", true); assertTrue(value); } @JavascriptEnabled @Test public void testShouldBeAbleToPassANumberAnAsArgument() { driver.get(pages.javascriptPage); boolean value = (Boolean) executeScript("return arguments[0] == 1 ? true : false;", 1); assertTrue(value); } @JavascriptEnabled @Test public void testShouldBeAbleToPassAWebElementAsArgument() { driver.get(pages.javascriptPage); WebElement button = driver.findElement(By.id("plainButton")); String value = (String) executeScript( "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble'];", button); assertEquals("plainButton", value); } @JavascriptEnabled @Test public void testPassingArrayAsOnlyArgumentFlattensArray() { driver.get(pages.javascriptPage); Object[] array = new Object[]{"zero", 1, true, 3.14159, false}; String value = (String) executeScript("return arguments[0]", array); assertEquals(array[0], value); } @JavascriptEnabled @Ignore({OPERA, OPERA_MOBILE}) @Test public void testShouldBeAbleToPassAnArrayAsAdditionalArgument() { driver.get(pages.javascriptPage); Object[] array = new Object[]{"zero", 1, true, 3.14159, false}; long length = (Long) executeScript("return arguments[1].length", "string", array); assertEquals(array.length, length); } @JavascriptEnabled @Test public void testShouldBeAbleToPassACollectionAsArgument() { driver.get(pages.javascriptPage); Collection<Object> collection = new ArrayList<Object>(); collection.add("Cheddar"); collection.add("Brie"); collection.add(7); long length = (Long) executeScript("return arguments[0].length", collection); assertEquals(collection.size(), length); collection = new HashSet<Object>(); collection.add("Gouda"); collection.add("Stilton"); collection.add("Stilton"); collection.add(true); length = (Long) executeScript("return arguments[0].length", collection); assertEquals(collection.size(), length); } @JavascriptEnabled @Test public void testShouldThrowAnExceptionIfAnArgumentIsNotValid() { driver.get(pages.javascriptPage); try { executeScript("return arguments[0];", driver); fail("Exception should have been thrown"); } catch (IllegalArgumentException e) { // this is expected } } @JavascriptEnabled @Test public void testShouldBeAbleToPassInMoreThanOneArgument() { driver.get(pages.javascriptPage); String result = (String) executeScript("return arguments[0] + arguments[1];", "one", "two"); assertEquals("onetwo", result); } @JavascriptEnabled @Test @Ignore({MARIONETTE, OPERA, OPERA_MOBILE}) public void testShouldBeAbleToGrabTheBodyOfFrameOnceSwitchedTo() { driver.get(pages.richTextPage); driver.switchTo().frame("editFrame"); WebElement body = (WebElement) executeScript("return document.body"); String text = body.getText(); driver.switchTo().defaultContent(); assertEquals("", text); } @SuppressWarnings("unchecked") @JavascriptEnabled @Test @Ignore(MARIONETTE) public void testShouldBeAbleToReturnAnArrayOfWebElements() { driver.get(pages.formPage); List<WebElement> items = (List<WebElement>) executeScript( "return document.getElementsByName('snack');"); assertFalse(items.isEmpty()); } @JavascriptEnabled @Test public void testJavascriptStringHandlingShouldWorkAsExpected() { driver.get(pages.javascriptPage); String value = (String) executeScript("return '';"); assertEquals("", value); value = (String) executeScript("return undefined;"); assertNull(value); value = (String) executeScript("return ' '"); assertEquals(" ", value); } @JavascriptEnabled @Ignore(OPERA) @Test public void testShouldBeAbleToExecuteABigChunkOfJavascriptCode() throws IOException { driver.get(pages.javascriptPage); File jqueryFile = InProject.locate("common/src/web/jquery-1.3.2.js"); String jquery = Files.toString(jqueryFile, Charset.forName("US-ASCII")); assertTrue("The javascript code should be at least 50 KB.", jquery.length() > 50000); // This should not throw an exception ... executeScript(jquery); } @SuppressWarnings("unchecked") @JavascriptEnabled @Test @Ignore(MARIONETTE) public void testShouldBeAbleToExecuteScriptAndReturnElementsList() { driver.get(pages.formPage); String scriptToExec = "return document.getElementsByName('snack');"; List<WebElement> resultsList = (List<WebElement>) executeScript(scriptToExec); assertFalse(resultsList.isEmpty()); } @JavascriptEnabled @NeedsFreshDriver @NoDriverAfterTest @Ignore(reason = "Failure indicates hang condition, which would break the" + " test suite. Really needs a timeout set.") @Test public void testShouldThrowExceptionIfExecutingOnNoPage() { try { executeScript("return 1;"); } catch (WebDriverException e) { // Expected return; } fail("Expected exception to be thrown"); } @JavascriptEnabled @Ignore({OPERA, MARIONETTE}) @Test public void testShouldBeAbleToCreateAPersistentValue() { driver.get(pages.formPage); executeScript("document.alerts = []"); executeScript("document.alerts.push('hello world');"); String text = (String) executeScript("return document.alerts.shift()"); assertEquals("hello world", text); } @JavascriptEnabled @Ignore(OPERA) @Test public void testCanHandleAnArrayOfElementsAsAnObjectArray() { driver.get(pages.formPage); List<WebElement> forms = driver.findElements(By.tagName("form")); Object[] args = new Object[]{forms}; String name = (String) ((JavascriptExecutor) driver).executeScript( "return arguments[0][0].tagName", args); assertEquals("form", name.toLowerCase()); } @JavascriptEnabled @Ignore(value = {ANDROID, OPERA, OPERA_MOBILE, MARIONETTE}, reason = "Opera obeys the method contract. Android not tested") @Test public void testCanPassAMapAsAParameter() { driver.get(pages.simpleTestPage); List<Integer> nums = ImmutableList.of(1, 2); Map<String, Object> args = ImmutableMap.of("bar", "test", "foo", nums); Object res = ((JavascriptExecutor) driver).executeScript("return arguments[0]['foo'][1]", args); assertEquals(2, ((Number) res).intValue()); } @JavascriptEnabled @Test @Ignore(value = {OPERA, OPERA_MOBILE}, reason = "Opera: failed") public void testShouldThrowAnExceptionWhenArgumentsWithStaleElementPassed() { driver.get(pages.simpleTestPage); final WebElement el = driver.findElement(By.id("oneline")); driver.get(pages.simpleTestPage); Map<String, Object> args = new HashMap<String, Object>() { { put("key", Arrays.asList("a", new Object[]{"zero", 1, true, 3.14159, false, el}, "c")); } }; try { executeScript("return undefined;", args); fail("Expected an exception"); } catch (StaleElementReferenceException e) { // This is expected } catch (Exception ex) { fail("Expected an StaleElementReferenceException exception, got " + ex); } } @JavascriptEnabled @Test @Ignore(value = {ANDROID, CHROME, HTMLUNIT, IE, IPHONE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI, MARIONETTE, QTWEBKIT}) public void testShouldBeAbleToReturnADateObject() { driver.get(pages.simpleTestPage); String date = (String) executeScript("return new Date();"); try { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(date); } catch (ParseException e) { fail(); } } @JavascriptEnabled @Test(timeout = 10000) @Ignore(value = {ANDROID, CHROME, IE, IPHONE, OPERA, OPERA_MOBILE, PHANTOMJS, QTWEBKIT, SAFARI, MARIONETTE}) public void shouldReturnDocumentElementIfDocumentIsReturned() { driver.get(pages.simpleTestPage); Object value = executeScript("return document"); assertTrue(value instanceof WebElement); assertTrue(((WebElement) value).getText().contains("A single line of text")); } }
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.spring.autoconfigure.agent.inspectors; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.impl.BlacklistedVersionAgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.impl.MinimumVersionAgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.impl.RejectAllJobsAgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.impl.WhitelistedVersionAgentMetadataInspector; import com.netflix.genie.web.properties.AgentFilterProperties; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; /** * Tests for {@link AgentInspectorsAutoConfiguration}. * * @author mprimi * @since 4.0.0 */ class AgentInspectorsAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( AgentInspectorsAutoConfiguration.class ) ); /** * Test expected context when configuration is enabled. */ @Test void testContextIfEnabled() { this.contextRunner .withPropertyValues( "genie.agent.filter.enabled=true" ) .run( (context) -> { Assertions.assertThat(context).hasSingleBean(AgentFilterProperties.class); Assertions.assertThat(context).getBeans(AgentMetadataInspector.class).hasSize(4); Assertions.assertThat(context).hasSingleBean(WhitelistedVersionAgentMetadataInspector.class); Assertions.assertThat(context).hasSingleBean(BlacklistedVersionAgentMetadataInspector.class); Assertions.assertThat(context).hasSingleBean(MinimumVersionAgentMetadataInspector.class); Assertions.assertThat(context).hasSingleBean(RejectAllJobsAgentMetadataInspector.class); } ); } /** * Test expected context when configuration is disabled. */ @Test void testContextIfDisabled() { this.contextRunner .withPropertyValues( "genie.agent.filter.enabled=nope" ) .run( (context) -> { Assertions.assertThat(context).doesNotHaveBean(AgentFilterProperties.class); Assertions.assertThat(context).doesNotHaveBean(AgentMetadataInspector.class); } ); } /** * Test expected context when configuration is not explicitly enabled or disabled. */ @Test void testContextIfUnspecified() { this.contextRunner .withPropertyValues( "genie.some.other.property=true" ) .run( (context) -> { Assertions.assertThat(context).doesNotHaveBean(AgentFilterProperties.class); Assertions.assertThat(context).doesNotHaveBean(AgentMetadataInspector.class); } ); } }
package co.ghast.safeguardac.mechanics; import co.ghast.safeguardac.SafeGuard; import lombok.Getter; import lombok.Setter; public class WaveSystem { private SafeGuard sg; public WaveSystem(SafeGuard sg){ this.sg = sg; } @Getter @Setter public boolean WaveActive; public void activateWave(){ this.WaveActive = true; } public void disableWave(){ this.WaveActive = false; } }
/* * Copyright 2014 Texas A&M Engineering Experiment Station * * 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 edu.tamu.tcat.crypto; public class EncodingException extends Exception { public EncodingException() { } public EncodingException(String message) { super(message); } public EncodingException(Throwable cause) { super(cause); } public EncodingException(String message, Throwable cause) { super(message, cause); } public EncodingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
/* * 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.config; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.concurrent.TimeUnit; /** * @author mawerss1@gmail.com * @date 2019/03/7 */ public class ConfigFutureTest { private static final String DATA_ID = "dataId"; private static final String CONTENT = "content"; private static final String RESULT = "result"; private static final long TIME_MILLS = 10L; private static final ConfigFuture.ConfigOperation GET_OPERATION = ConfigFuture.ConfigOperation.GET; private ConfigFuture configFuture; @Before public void initConfigFutureBeforeTest() { configFuture = new ConfigFuture(DATA_ID, CONTENT, GET_OPERATION, TIME_MILLS); } /** * Test get with get operation. */ @Test public void testConfigGetWithGetOperation() { // return content value when future not set result Assert.assertEquals(CONTENT, configFuture.get()); configFuture.setResult(RESULT); Assert.assertEquals(RESULT, configFuture.get()); } /** * Test get with timeout argument */ @Test public void testConfigGetCustomeOutTime() { Assert.assertEquals(CONTENT, configFuture.get(10L, TimeUnit.MILLISECONDS)); configFuture.setResult(RESULT); Assert.assertEquals(RESULT, configFuture.get()); } /** * Test get with put operation. */ @Test public void testConfigGetWithPutOperation() { configFuture.setOperation(ConfigFuture.ConfigOperation.PUT); Assert.assertEquals(false, configFuture.get()); configFuture.setResult(RESULT); Assert.assertEquals(RESULT, configFuture.get()); } @Test public void testSetContent() { configFuture.setContent(CONTENT); Assert.assertEquals(CONTENT, configFuture.getContent()); } @Test public void testGetContent() { configFuture.setContent(CONTENT); Assert.assertEquals(CONTENT, configFuture.getContent()); } @Test public void testSetDataId() { configFuture.setDataId(DATA_ID); Assert.assertEquals(DATA_ID, configFuture.getDataId()); } @Test public void testGetDataId() { configFuture.setDataId(DATA_ID); Assert.assertEquals(DATA_ID, configFuture.getDataId()); } @Test public void testSetResult() { configFuture.setResult(RESULT); Assert.assertEquals(RESULT, configFuture.get()); } @Test public void testGetOperation() { configFuture.setOperation(ConfigFuture.ConfigOperation.GET); Assert.assertEquals(ConfigFuture.ConfigOperation.GET, configFuture.getOperation()); } @Test public void testSetOperation() { configFuture.setOperation(ConfigFuture.ConfigOperation.GET); Assert.assertEquals(ConfigFuture.ConfigOperation.GET, configFuture.getOperation()); } @Test public void testIsTimeout() { Assert.assertFalse(configFuture.isTimeout()); //TIME_MILLS + 1 ensure timeout occur configFuture.get(TIME_MILLS + 1, TimeUnit.MILLISECONDS); Assert.assertTrue(configFuture.isTimeout()); } }
package org.medlog.validation; import org.medlog.models.Doctors; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class DoctorValidation implements Validator { @Override public boolean supports(Class<?> aClass) { return Doctors.class.isAssignableFrom(aClass); } @Override public void validate(Object o, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "name", "field.required"); ValidationUtils.rejectIfEmpty(errors, "description", "field.required"); } }
package com.baiyi.opscloud.controller.http; import com.baiyi.opscloud.common.HttpResult; import com.baiyi.opscloud.domain.DataTable; import com.baiyi.opscloud.domain.param.ansible.AnsiblePlaybookParam; import com.baiyi.opscloud.domain.vo.ansible.AnsiblePlaybookVO; import com.baiyi.opscloud.facade.task.AnsiblePlaybookFacade; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * @Author baiyi * @Date 2021/9/1 11:05 上午 * @Version 1.0 */ @RestController @RequestMapping("/api/task") @Api(tags = "任务管理") @RequiredArgsConstructor public class TaskController { private final AnsiblePlaybookFacade ansiblePlaybookFacade; @ApiOperation(value = "分页查询剧本列表") @PostMapping(value = "/ansible/playbook/page/query", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public HttpResult<DataTable<AnsiblePlaybookVO.Playbook>> queryAnsiblePlaybookPage(@RequestBody @Valid AnsiblePlaybookParam.AnsiblePlaybookPageQuery pageQuery) { return new HttpResult<>(ansiblePlaybookFacade.queryAnsiblePlaybookPage(pageQuery)); } @ApiOperation(value = "新增剧本配置") @PostMapping(value = "/ansible/playbook/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public HttpResult<Boolean> addAnsiblePlaybook(@RequestBody @Valid AnsiblePlaybookVO.Playbook playbook) { ansiblePlaybookFacade.addAnsiblePlaybook(playbook); return HttpResult.SUCCESS; } @ApiOperation(value = "更新剧本配置") @PutMapping(value = "/ansible/playbook/update", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public HttpResult<Boolean> updateAnsiblePlaybook(@RequestBody @Valid AnsiblePlaybookVO.Playbook playbook) { ansiblePlaybookFacade.updateAnsiblePlaybook(playbook); return HttpResult.SUCCESS; } @ApiOperation(value = "删除指定的剧本配置") @DeleteMapping(value = "/ansible/playbook/del", produces = MediaType.APPLICATION_JSON_VALUE) public HttpResult<Boolean> deleteServerById(@RequestParam int id) { ansiblePlaybookFacade.deleteAnsiblePlaybookById(id); return HttpResult.SUCCESS; } }
package com.jrmd.benkyoshimasu; import android.content.Context; import android.util.DisplayMetrics; import com.jrmd.benkyoshimasu.object.Lessons; import com.jrmd.benkyoshimasu.object.Word; import java.util.ArrayList; import java.util.List; /** * Created by julian on 07/11/2016. */ public class Utils { public static Lessons loadAllWords(){ Lessons lessons = new Lessons(); List<Word> words1 = new ArrayList<Word>(); List<Word> words2 = new ArrayList<Word>(); List<Word> words3 = new ArrayList<Word>(); List<Word> words4 = new ArrayList<Word>(); List<Word> words5 = new ArrayList<Word>(); List<Word> words6 = new ArrayList<Word>(); words1.add(new Word("Maestro/Profesor","せんせい","先生",1)); words1.add(new Word("Maestro/Profesor","きょうし","",1)); words1.add(new Word("Estudíante","がくせい","学生",1)); words1.add(new Word("Empleado de empresa","かいしゃいん","",1)); words1.add(new Word("Médico","いしゃ","",1)); words1.add(new Word("Investigador","けんきゅうしゃ","",1)); words1.add(new Word("Ingeniero","エンジニア","",1)); words1.add(new Word("Universidad","だいがく","大学",1)); words1.add(new Word("Hospital","びょういん","",1)); words2.add(new Word("Libro","ほん","本",2)); words2.add(new Word("Diccionario","じしょ","",2)); words2.add(new Word("Revista","ざっし","",2)); words2.add(new Word("Periodico","しんぶん","",2)); words2.add(new Word("Cuaderno","ノート","",2)); words2.add(new Word("Agenda","てちょう","",2)); words2.add(new Word("Tarjeta de Negocio","めいし","",2)); words2.add(new Word("Tarjeta","カード","",2)); words2.add(new Word("Tarjeta de teléfono","テレホンカード","",2)); words2.add(new Word("Lápiz","えんぴつ","",2)); words2.add(new Word("Esfero","ボールペン","",2)); words2.add(new Word("Portaminas","シャープペンシル","",2)); words2.add(new Word("Llave","かぎ","",2)); words2.add(new Word("Reloj","とけい","",2)); words2.add(new Word("Sombrilla","かさ","",2)); words2.add(new Word("Maleta","かばん","",2)); words2.add(new Word("Cinta/Cassette","テープ。カセット","",2)); words2.add(new Word("Grabadora","テープレコーダー","",2)); words2.add(new Word("Televisión","テレビ","",2)); words2.add(new Word("Radio","ラジオ","",2)); words2.add(new Word("Cámara","カメラ","",2)); words2.add(new Word("Computador","コンピューター","",2)); words2.add(new Word("Automóvil","じどうしゃ","自動車",2)); words2.add(new Word("Escritorio","つくえ","",2)); words2.add(new Word("Silla","いす","",2)); words2.add(new Word("Chocolate","チョコレート","",2)); words2.add(new Word("Café","コーヒー","",2)); words3.add(new Word("Salón de clase","きょうしつ","",3)); words3.add(new Word("Comedor","しょくど","",3)); words3.add(new Word("Oficina","じむしょ","",3)); words3.add(new Word("Sala de reuniones","かいぎしつ","",3)); words3.add(new Word("Recepción","うけつけ","",3)); words3.add(new Word("Lóbi/Vestíbulo","ロビー","",3)); words3.add(new Word("Habitación","へや","",3)); words3.add(new Word("Baño","トイレ","",3)); words3.add(new Word("Baño","おてあらい","",3)); words3.add(new Word("Escalera","かいだん","",3)); words3.add(new Word("Ascensor","エレベーター","",3)); words3.add(new Word("Escalera Electrica","エスカレーター","",3)); words3.add(new Word("Empresa","かいしゃ","",3)); words3.add(new Word("Casa","うち","",3)); words3.add(new Word("Teléfono","でんわ","",3)); words3.add(new Word("Zapatos","くつ","",3)); words3.add(new Word("Corbata","ネクタイ","",3)); words3.add(new Word("Vino","ワイン","",3)); words3.add(new Word("Tabaco","たばこ","",3)); words3.add(new Word("Sección(almacenes)","うりば","",3)); words3.add(new Word("Sótano","ちか","",3)); words3.add(new Word("- Piso","かい","",3)); words3.add(new Word("- Yen","えん","",3)); words3.add(new Word("Cien","ひゃく","百",3)); words3.add(new Word("Mil","せん","千",3)); words3.add(new Word("Diez Mil","まん","万",3)); words4.add(new Word("Levantarse","おきます","",4)); words4.add(new Word("Acostarse","ねます","",4)); words4.add(new Word("Trabajar","はたらきます","",4)); words4.add(new Word("Descansar","やすみます","",4)); words4.add(new Word("Estudíar","べんきょします","",4)); words4.add(new Word("Terminar","おわります","",4)); words4.add(new Word("Supermercado","デパート","",4)); words4.add(new Word("Banco","ぎんこう","",4)); words4.add(new Word("Oficina de correos","ゆうびんきょく","",4)); words4.add(new Word("Biblioteca","としょかん","",4)); words4.add(new Word("Museo de arte","びじゅつかん","",4)); words4.add(new Word("Ahora","いま","今",4)); words4.add(new Word("De la mañana","ごぜん","",4)); words4.add(new Word("De la tarde","ごご","",4)); words4.add(new Word("La mañana","あさ","",4)); words4.add(new Word("Mediodía","ひる","",4)); words4.add(new Word("Noche","ばん","",4)); words4.add(new Word("Anteayer","おととい","",4)); words4.add(new Word("Ayer","きのう","",4)); words4.add(new Word("Hoy","きょう","",4)); words4.add(new Word("Mañana","あした","",4)); words4.add(new Word("Pasado Mañana","あさって","",4)); words4.add(new Word("Esta mañana","けさ","",4)); words4.add(new Word("Esta noche","こんばん","",4)); words4.add(new Word("Descanso/día libre","やすみ","",4)); words4.add(new Word("Descanso de mediodía","ひるやすみ","",4)); words4.add(new Word("Todas las mañanas","まいあさ","",4)); words4.add(new Word("Todas las noches","まいばn","",4)); words4.add(new Word("Todos los días","まいにち","",4)); words4.add(new Word("Lunes","げつようび","月曜日",4)); words4.add(new Word("Martes","かようび","火曜日",4)); words4.add(new Word("Miercoles","すいようび","水曜日",4)); words4.add(new Word("Jueves","もくようび","木曜日",4)); words4.add(new Word("Viernes","きんようび","金曜日",4)); words4.add(new Word("Sabado","どようび","土曜日",4)); words4.add(new Word("Domingo","にちようび","日曜日",4)); words4.add(new Word("Número","ばんごう","",4)); words4.add(new Word("Qué Número","なんばん","",4)); words4.add(new Word("Desde -"," - から","",4)); words4.add(new Word("Hasta -"," - まで","",4)); words5.add(new Word("Ir","いきます","",5)); words5.add(new Word("Venir","きます","",5)); words5.add(new Word("Volver","かえります","",5)); words5.add(new Word("Escuela","がっこう","",5)); words5.add(new Word("Estación de tren","えき","",5)); words5.add(new Word("Avión","ひこうき","",5)); words5.add(new Word("Barco","ふね","",5)); words5.add(new Word("Tren eléctrico","でんしゃ","",5)); words5.add(new Word("Metro","ちかてつ","",5)); words5.add(new Word("Tren bala","しんかんせん","",5)); words5.add(new Word("Bus","バス","",5)); words5.add(new Word("Taxi","タクシー","",5)); words5.add(new Word("Bicicleta","してんしゃ","",5)); words5.add(new Word("A pie","あるいて","",5)); words5.add(new Word("Persona","ひと","人",5)); words5.add(new Word("Amigo/a(s)","ともだち","",5)); words5.add(new Word("Novio","かれ","",5)); words5.add(new Word("Novia","かのじょ","",5)); words5.add(new Word("Familia","かぞく","",5)); words5.add(new Word("Solo/a","ひとりで","",5)); words5.add(new Word("La semana pasada","せんしょう","",5)); words5.add(new Word("Esta Semana","こんしょう","",5)); words5.add(new Word("La próxima semana","らいしょう","",5)); words5.add(new Word("El mes pasado","せんげつ","先月",5)); words5.add(new Word("Este mes","こんげつ","",5)); words5.add(new Word("El próximo mes","らいげつ","",5)); words5.add(new Word("El año pasado","きょねん","",5)); words5.add(new Word("Este año","ことし","",5)); words5.add(new Word("El proximo año","らいねん","",5)); words5.add(new Word("Primer día del mes","ついたち","1日",5)); words5.add(new Word("2do día del mes","ふつか","2日",5)); words5.add(new Word("3er día del mes","みっか","3日",5)); words5.add(new Word("4to día del mes","よっか","4日",5)); words5.add(new Word("5to día del mes","いつか","5日",5)); words5.add(new Word("6to día del mes","むいか","6日",5)); words5.add(new Word("7to día del mes","なのか","7日",5)); words5.add(new Word("8to día del mes","ようか","8日",5)); words5.add(new Word("9to día del mes","ここのか","9日",5)); words5.add(new Word("10mo día del mes","よおか","10日",5)); words5.add(new Word("14vo día del mes","じゅうよっか","14日",5)); words5.add(new Word("20vo día del mes","はつか","20日",5)); words5.add(new Word("24vo día del mes","にじゅうよっか","24日",5)); words5.add(new Word("Cúando","いつ","",5)); words5.add(new Word("Cumpleaños","たんじょうび","",5)); words6.add(new Word("Comer","たべます","",6)); words6.add(new Word("Beber/Tomar","のみます","",6)); words6.add(new Word("Fumar","すいます","",6)); words6.add(new Word("Ver/Mirar","みます","",6)); words6.add(new Word("Oír/Escuchar","ききまし","",6)); words6.add(new Word("Leer","よみます","",6)); words6.add(new Word("Escribir/Diibujar","かきます","",6)); words6.add(new Word("Comprar","かいます","",6)); words6.add(new Word("Tomar fotos","よります","",6)); words6.add(new Word("Hacer","します","",6)); words6.add(new Word("Encontrarse con","あいます","",6)); words6.add(new Word("Comida/Arroz cocido","ごはん","",6)); words6.add(new Word("Desayuno","あさごはん","",6)); words6.add(new Word("Almuerzo","ひるごはん","",6)); words6.add(new Word("Cena","ばんごはん","",6)); words6.add(new Word("Pan","パン","",6)); words6.add(new Word("Huevo","たまご","",6)); words6.add(new Word("Carne de ganado","にく","",6)); words6.add(new Word("Pescado","さかな","",6)); words6.add(new Word("Verduras","やさい","",6)); words6.add(new Word("Frutas","くだもの","",6)); words6.add(new Word("Agua","みず","",6)); words6.add(new Word("Té","おちゃ","",6)); words6.add(new Word("Té negro","のうちゃ","",6)); words6.add(new Word("Leche","ぎゅうにゅう","",6)); words6.add(new Word("Leche","ミルク","",6)); words6.add(new Word("Jugo","ジュース","",6)); words6.add(new Word("Cerveza","ビール","",6)); words6.add(new Word("Sake","さけ","",6)); words6.add(new Word("Video cinta","ビデオ","",6)); words6.add(new Word("Película","えうが","",6)); words6.add(new Word("Carta","てがみ","",6)); words6.add(new Word("Informe","レポート","",6)); words6.add(new Word("Fotografía","しゃしん","",6)); words6.add(new Word("Tienda","みせ","",6)); words6.add(new Word("Restaurante","レストラン","",6)); words6.add(new Word("Jardin","にわ","",6)); words6.add(new Word("Tarea","しゅくだい","",6)); words6.add(new Word("Ténis","テニス","",6)); words6.add(new Word("Fútbol","サッカー","",6)); lessons.setWordsLesson1(words1); lessons.setWordsLesson2(words2); lessons.setWordsLesson3(words3); lessons.setWordsLesson4(words4); lessons.setWordsLesson5(words5); lessons.setWordsLesson6(words6); return lessons; } public static int dpToPx(Context context, int dp) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); return px; } }
package io.onedev.server.web.component.build.authorization; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import io.onedev.server.model.support.build.actionauthorization.ActionAuthorization; import io.onedev.server.web.editable.annotation.Editable; @Editable public class ActionAuthorizationsBean implements Serializable { private static final long serialVersionUID = 1L; private List<ActionAuthorization> actionAuthorizations = new ArrayList<>(); @Editable public List<ActionAuthorization> getActionAuthorizations() { return actionAuthorizations; } public void setActionAuthorizations(List<ActionAuthorization> actionAuthorizations) { this.actionAuthorizations = actionAuthorizations; } }
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.cartera.presentation.swing.jinternalframes.auxiliar.report; import com.bydan.erp.seguridad.business.entity.Usuario; import com.bydan.erp.seguridad.business.entity.Opcion; import com.bydan.erp.seguridad.business.entity.PerfilOpcion; import com.bydan.erp.seguridad.business.entity.PerfilCampo; import com.bydan.erp.seguridad.business.entity.PerfilAccion; import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg; import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario; import com.bydan.erp.seguridad.business.entity.Modulo; import com.bydan.erp.seguridad.business.entity.Accion; //import com.bydan.erp.seguridad.business.entity.PerfilAccion; import com.bydan.erp.seguridad.util.SistemaConstantesFunciones; import com.bydan.erp.seguridad.util.SistemaConstantesFuncionesAdditional; import com.bydan.erp.seguridad.business.logic.SistemaLogicAdditional; //import com.bydan.erp.cartera.util.FacturasProveedoresConstantesFunciones; import com.bydan.erp.cartera.util.report.FacturasProveedoresParameterReturnGeneral; //import com.bydan.erp.cartera.util.report.FacturasProveedoresParameterGeneral; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.DatoGeneralMinimo; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.Mensajes; //import com.bydan.framework.erp.business.entity.MaintenanceType; import com.bydan.framework.erp.util.MaintenanceType; import com.bydan.framework.erp.util.FuncionesReporte; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.business.logic.Pagination; import com.bydan.erp.cartera.presentation.swing.jinternalframes.report.FacturasProveedoresBeanSwingJInternalFrame; import com.bydan.framework.erp.presentation.desktop.swing.TablaGeneralTotalModel; import com.bydan.framework.erp.presentation.desktop.swing.DateConverter; import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate; import com.bydan.framework.erp.presentation.desktop.swing.DateRenderer; import com.bydan.framework.erp.presentation.desktop.swing.DateEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.BooleanRenderer; import com.bydan.framework.erp.presentation.desktop.swing.BooleanEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.TextFieldRenderer; import com.bydan.framework.erp.presentation.desktop.swing.*; //import com.bydan.framework.erp.presentation.desktop.swing.TextFieldEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.HeaderRenderer; import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase; import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing; import com.bydan.framework.erp.presentation.desktop.swing.MainJFrame; import com.bydan.framework.erp.resources.imagenes.AuxiliarImagenes; import com.bydan.erp.cartera.resources.reportes.report.AuxiliarReportes; import com.bydan.erp.cartera.util.*; import com.bydan.erp.cartera.util.report.*; import com.bydan.erp.cartera.business.logic.*; import com.bydan.erp.seguridad.business.logic.*; import com.bydan.erp.cartera.business.logic.*; //EJB //PARAMETROS //EJB PARAMETROS import com.bydan.framework.erp.business.logic.*; import com.bydan.framework.erp.util.*; import com.bydan.erp.cartera.business.entity.*; import com.bydan.erp.cartera.business.entity.report.*; //import com.bydan.framework.erp.business.entity.ConexionBeanFace; //import com.bydan.framework.erp.business.entity.Mensajes; import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*; import com.bydan.erp.cartera.presentation.swing.jinternalframes.*; import java.net.NetworkInterface; import java.net.InterfaceAddress; import java.net.InetAddress; import javax.naming.InitialContext; import java.lang.Long; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.io.Serializable; import java.util.Hashtable; import java.io.File; import java.io.FileInputStream; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.FileOutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import java.io.PrintWriter; import java.sql.SQLException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; //import org.hibernate.collection.PersistentBag; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.data.JRBeanArrayDataSource; import net.sf.jasperreports.view.JasperViewer; import org.apache.log4j.Logger; import com.bydan.framework.erp.business.entity.Reporte; //VALIDACION import org.hibernate.validator.ClassValidator; import org.hibernate.validator.InvalidValue; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperPrintManager; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.JasperRunManager; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.util.JRSaver; import net.sf.jasperreports.engine.xml.JRXmlWriter; import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*; import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.report.*; import com.bydan.erp.cartera.presentation.swing.jinternalframes.report.FacturasProveedoresJInternalFrame; import com.bydan.erp.cartera.presentation.swing.jinternalframes.report.FacturasProveedoresDetalleFormJInternalFrame; import java.util.EventObject; import java.util.EventListener; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.*; import org.jdesktop.beansbinding.Binding.SyncFailure; import org.jdesktop.beansbinding.BindingListener; import org.jdesktop.beansbinding.Bindings; import org.jdesktop.beansbinding.BeanProperty; import org.jdesktop.beansbinding.ELProperty; import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy; import org.jdesktop.beansbinding.PropertyStateEvent; import org.jdesktop.swingbinding.JComboBoxBinding; import org.jdesktop.swingbinding.SwingBindings; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.cartera.business.entity.*; import com.bydan.erp.seguridad.util.*; import com.bydan.erp.cartera.util.*; import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*; import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*; @SuppressWarnings("unused") public class FacturasProveedoresTableCell extends DefaultCellEditor implements TableCellRenderer { private static final long serialVersionUID = 1L; //PARA TABLECELL_FK public JInternalFrameBase jInternalFrameBase; protected JLabel jLabelFacturasProveedores=new JLabelMe(); @SuppressWarnings("rawtypes") protected JComboBox jComboBoxFacturasProveedores=new JComboBoxMe(); protected Object valor=new Object(); protected List<FacturasProveedores> facturasproveedoressForeignKey=new ArrayList<FacturasProveedores>(); protected List<FacturasProveedores> facturasproveedoressForeignKeyActual=new ArrayList<FacturasProveedores>(); protected Border borderResaltarFacturasProveedores=null; protected Boolean conEnabled=true; protected Integer iTotalRow=0; protected Boolean conHotKeys=false; protected String sNombreHotKeyAbstractAction=""; protected String sTipoBusqueda="NINGUNO"; protected Integer rowActual=-1; protected ArrayList<Classe> classes; //PARA TABLECELL_FK_FIN //PARA TABLECELL public String sTipo="FK"; //"BOTON" protected JButton jButtonFacturasProveedores; //PARA TABLECELL FIN //PARA TABLECELL_FK public FacturasProveedoresTableCell() { super(new JCheckBoxMe()); } public FacturasProveedoresTableCell(JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(new JCheckBoxMe()); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } public FacturasProveedoresTableCell(JInternalFrameBase jInternalFrameBase) { this(jInternalFrameBase,true); } public FacturasProveedoresTableCell(JCheckBox checkBox,JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(checkBox); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } public FacturasProveedoresTableCell(JCheckBox checkBox,JInternalFrameBase jInternalFrameBase) { this(checkBox,jInternalFrameBase,true); } @SuppressWarnings("rawtypes") public FacturasProveedoresTableCell(JComboBox jcComboBox,JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(jcComboBox); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.jComboBoxFacturasProveedores=jcComboBox; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } @SuppressWarnings("rawtypes") public FacturasProveedoresTableCell(JComboBox jcComboBox,JInternalFrameBase jInternalFrameBase) { this(jcComboBox,jInternalFrameBase,true); } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(new JCheckBoxMe()); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.facturasproveedoressForeignKey=facturasproveedoressForeignKey; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,JInternalFrameBase jInternalFrameBase) { this(facturasproveedoressForeignKey,jInternalFrameBase,true); } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,Border borderResaltarFacturasProveedores,JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(new JCheckBoxMe()); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.facturasproveedoressForeignKey=facturasproveedoressForeignKey; this.borderResaltarFacturasProveedores=borderResaltarFacturasProveedores; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,Border borderResaltarFacturasProveedores,JInternalFrameBase jInternalFrameBase,Boolean conEnabled,Integer iTotalRow) { super(new JCheckBoxMe()); this.iTotalRow=iTotalRow; this.conEnabled=conEnabled; this.conHotKeys=false; this.sNombreHotKeyAbstractAction=""; this.sTipoBusqueda="NINGUNO"; this.rowActual=-1; this.facturasproveedoressForeignKey=facturasproveedoressForeignKey; this.borderResaltarFacturasProveedores=borderResaltarFacturasProveedores; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,Border borderResaltar,JInternalFrameBase jInternalFrameBase) { this(facturasproveedoressForeignKey,borderResaltar,jInternalFrameBase,true); } public FacturasProveedoresTableCell(List<FacturasProveedores> facturasproveedoressForeignKey,Border borderResaltarFacturasProveedores,JInternalFrameBase jInternalFrameBase,Boolean conEnabled,Boolean conHotKeys,String sNombreHotKeyAbstractAction,String sTipoBusqueda) { super(new JCheckBoxMe()); this.iTotalRow=0; this.conEnabled=conEnabled; this.conHotKeys=conHotKeys; this.sNombreHotKeyAbstractAction=sNombreHotKeyAbstractAction; this.sTipoBusqueda=sTipoBusqueda; this.rowActual=-1; this.facturasproveedoressForeignKey=facturasproveedoressForeignKey; this.borderResaltarFacturasProveedores=borderResaltarFacturasProveedores; this.jInternalFrameBase=jInternalFrameBase; this.sTipo="FK"; } //PARA TABLECELL_FK_FIN public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) { Component component=new JCheckBoxMe(); if(sTipo=="FK") { component=this.getTableCellRendererComponentParaTableCellFk(table,value,isSelected,hasFocus,row,column); } else if(sTipo=="BOTON") { component=this.getTableCellRendererComponentParaTableCell(table,value,isSelected,hasFocus,row,column); } return component; } public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) { Component component=new JCheckBoxMe(); if(sTipo=="FK") { component=this.getTableCellEditorComponentParaTableCellFk(table,value,isSelected,row,column); } else if(sTipo=="BOTON") { component=this.getTableCellEditorComponentParaTableCell(table,value,isSelected,row,column); } return component; } public Component getTableCellRendererComponentParaTableCellFk(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) { try{ int intSelectedRow = row; //ARCHITECTURE /* if(Constantes.ISUSAEJBLOGICLAYER) { perfil =(Perfil) perfilLogic.getPerfils().toArray()[table.convertRowIndexToModel(intSelectedRow)]; } else if(Constantes.ISUSAEJBREMOTE) { perfil =(Perfil) perfils.toArray()[table.convertRowIndexToModel(intSelectedRow)]; } */ //ARCHITECTURE jLabelFacturasProveedores=new JLabelMe(); /* if(perfil.getIsChanged()) { perfil.setsistema_descripcion((getActualSistemaForeignKeyDescripcion((Long)value))); } */ String sFacturasProveedoresDescripcion=""; sFacturasProveedoresDescripcion=jInternalFrameBase.getDescripcionFk("FacturasProveedores",table,value,intSelectedRow); jLabelFacturasProveedores.setText(sFacturasProveedoresDescripcion); if(this.borderResaltarFacturasProveedores!=null) { jLabelFacturasProveedores.setBorder(this.borderResaltarFacturasProveedores); } jLabelFacturasProveedores.setOpaque(true); //if(row!=(this.iTotalRow-1)) { if((this.jInternalFrameBase.conTotales && row != table.getRowCount()-1) || !this.jInternalFrameBase.conTotales) { jLabelFacturasProveedores.setBackground(row % 2 == 0 ? FuncionesSwing.getColorTextFields(Constantes2.S_FONDOCONTROL_COLOR) : Funciones2.getColorFilaTabla2()); } else { jLabelFacturasProveedores.setBackground(Funciones2.getColorFilaTablaTotales()); } if(isSelected) { jLabelFacturasProveedores.setForeground(FuncionesSwing.getColorSelectedForeground()); } } catch(Exception e) { ; } this.jLabelFacturasProveedores.setEnabled(this.conEnabled); FuncionesSwing.setBoldLabel(this.jLabelFacturasProveedores, this.jInternalFrameBase.getsTipoTamanioGeneralTabla(),true,false,this.jInternalFrameBase); return this.jLabelFacturasProveedores; } @SuppressWarnings({"unchecked" }) public Component getTableCellEditorComponentParaTableCellFk(JTable table,Object value,boolean isSelected,int row,int column) { this.jComboBoxFacturasProveedores=new JComboBoxMe(); try{ int intSelectedRow = row; //ARCHITECTURE /* if(Constantes.ISUSAEJBLOGICLAYER) { perfil =(Perfil) perfilLogic.getPerfils().toArray()[table.convertRowIndexToModel(intSelectedRow)]; } else if(Constantes.ISUSAEJBREMOTE) { perfil =(Perfil) perfils.toArray()[table.convertRowIndexToModel(intSelectedRow)]; } */ //ARCHITECTURE if(!FacturasProveedoresJInternalFrame.ISBINDING_MANUAL) { } else { this.jComboBoxFacturasProveedores.removeAllItems(); //SIEMPRE <0 , NO USADO POR EL MOMENTO //COMBO DE FILA ACTUAL SE ACTUALIZA, LOS DEMAS USAN EL ANTERIOR COMBO if(this.rowActual<0 || (this.rowActual>=0 && this.rowActual!=row)) { for(FacturasProveedores facturasproveedores:this.facturasproveedoressForeignKey) { this.jComboBoxFacturasProveedores.addItem(facturasproveedores); } } else { if(this.rowActual==row && row>=0) { for(FacturasProveedores facturasproveedores:this.facturasproveedoressForeignKeyActual) { this.jComboBoxFacturasProveedores.addItem(facturasproveedores); } } } } //this.jComboBoxFacturasProveedores.setSelectedItem(perfil.getFacturasProveedores()); //setActualFacturasProveedoresForeignKey((Long)value,false,"Formulario"); FacturasProveedoresBeanSwingJInternalFrame.setActualComboBoxFacturasProveedoresGenerico((Long)value,this.jComboBoxFacturasProveedores,this.facturasproveedoressForeignKey); if(this.conHotKeys) { FacturasProveedoresBeanSwingJInternalFrame.setHotKeysComboBoxFacturasProveedoresGenerico(this.jComboBoxFacturasProveedores,this.jInternalFrameBase,this.sNombreHotKeyAbstractAction,this.sTipoBusqueda); } //NO_FUNCIONA_perfil.setsistema_descripcion(getActualFacturasProveedoresForeignKeyDescripcion((Long)value)); valor=value; this.jComboBoxFacturasProveedores.setOpaque(true); } catch(Exception e) { e.printStackTrace(); } this.jComboBoxFacturasProveedores.setEnabled(this.conEnabled); FuncionesSwing.setBoldComboBox(this.jComboBoxFacturasProveedores, this.jInternalFrameBase.getsTipoTamanioGeneralTabla(),true,false,this.jInternalFrameBase); return this.jComboBoxFacturasProveedores; } public Component getTableCellRendererComponentParaTableCell(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) { jButtonFacturasProveedores =new JButtonMe((row+1)+"-Facturas Proveedores"); jButtonFacturasProveedores.setToolTipText((row+1)+"-Facturas Proveedores"); if(this.borderResaltarFacturasProveedores!=null) { jButtonFacturasProveedores.setBorder(this.borderResaltarFacturasProveedores); } jButtonFacturasProveedores.setOpaque(true); jButtonFacturasProveedores.setBackground(row % 2 == 0 ? FuncionesSwing.getColorTextFields(Constantes2.S_FONDOCONTROL_COLOR) : Funciones2.getColorFilaTabla2()); if(isSelected) { jButtonFacturasProveedores.setForeground(FuncionesSwing.getColorSelectedForeground()); } this.jButtonFacturasProveedores.setEnabled(this.conEnabled); return jButtonFacturasProveedores; } public Component getTableCellEditorComponentParaTableCell(JTable table,Object value,boolean isSelected,final int row,int column) { jButtonFacturasProveedores=new JButtonMe((row+1)+"-Facturas Proveedores"); jButtonFacturasProveedores.setToolTipText((row+1)+"-Facturas Proveedores"); if(this.borderResaltarFacturasProveedores!=null) { jButtonFacturasProveedores.setBorder(this.borderResaltarFacturasProveedores); } /* jButtonFacturasProveedores.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { //jButtonFacturasProveedoresActionPerformed(evt,row,true,false); jInternalFrameBase.jButtonRelacionActionPerformed("FacturasProveedores",evt,row,true,false); } } ); */ this.jButtonFacturasProveedores.addActionListener(new ButtonActionListener(this.jInternalFrameBase,"TableCell","FacturasProveedores",row)); valor=value; this.jButtonFacturasProveedores.setEnabled(this.conEnabled); return jButtonFacturasProveedores; } public FacturasProveedoresTableCell(Border borderResaltarFacturasProveedores,JInternalFrameBase jInternalFrameBase,Boolean conEnabled) { super(new JCheckBoxMe()); this.conEnabled=conEnabled; this.jInternalFrameBase=jInternalFrameBase; this.borderResaltarFacturasProveedores=borderResaltarFacturasProveedores; this.sTipo="BOTON"; } public FacturasProveedoresTableCell(Border borderResaltarFacturasProveedores,JInternalFrameBase jInternalFrameBase) { this(borderResaltarFacturasProveedores,jInternalFrameBase,true); } public Object getCellEditorValue() { Object value=new Object(); Long idActual=0L; if(sTipo=="FK") { FacturasProveedores facturasproveedores=((FacturasProveedores)this.jComboBoxFacturasProveedores.getSelectedItem()); if(facturasproveedores!=null) { idActual=facturasproveedores.getId(); } value=idActual; } else if(sTipo=="BOTON") { value=valor; } return value; } public boolean stopCellEditing() { fireEditingStopped(); return true; } public Integer getRowActual() { return this.rowActual; } public void setRowActual(Integer rowActual) { this.rowActual = rowActual; } public Boolean getConEnabled() { return this.conEnabled; } public void setConEnabled(Boolean conEnabled) { this.conEnabled = conEnabled; } public Boolean getConHotKeys() { return this.conHotKeys; } public void setConHotKeys(Boolean conHotKeys) { this.conHotKeys = conHotKeys; } @SuppressWarnings("rawtypes") public JComboBox getjComboBoxFacturasProveedores() { return this.jComboBoxFacturasProveedores; } @SuppressWarnings("rawtypes") public void setjComboBoxFacturasProveedores(JComboBox jComboBoxFacturasProveedores) { this.jComboBoxFacturasProveedores = jComboBoxFacturasProveedores; } public List<FacturasProveedores> getfacturasproveedoressForeignKey() { return this.facturasproveedoressForeignKey; } public void setfacturasproveedoressForeignKey(List<FacturasProveedores> facturasproveedoressForeignKey) { this.facturasproveedoressForeignKey = facturasproveedoressForeignKey; } public List<FacturasProveedores> getfacturasproveedoressForeignKeyActual() { return this.facturasproveedoressForeignKeyActual; } public void setfacturasproveedoressForeignKeyActual(List<FacturasProveedores> facturasproveedoressForeignKeyActual) { this.facturasproveedoressForeignKeyActual = facturasproveedoressForeignKeyActual; } @SuppressWarnings("unchecked") public void RecargarFacturasProveedoressForeignKey() { this.jComboBoxFacturasProveedores.removeAllItems(); //SIEMPRE <0 , NO USADO POR EL MOMENTO //COMBO DE FILA ACTUAL SE ACTUALIZA, LOS DEMAS USAN EL ANTERIOR COMBO if(this.rowActual<0) { for(FacturasProveedores facturasproveedores:this.facturasproveedoressForeignKey) { this.jComboBoxFacturasProveedores.addItem(facturasproveedores); } } else { for(FacturasProveedores facturasproveedores:this.facturasproveedoressForeignKeyActual) { this.jComboBoxFacturasProveedores.addItem(facturasproveedores); } } } }
package com.moonapi.demo; import com.sun.istack.internal.Nullable; import org.apache.commons.codec.binary.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.io.UnsupportedEncodingException; import java.util.*; class MoonapiSign { private final static String ALGORITHM = "UTF-8"; public static String generateHmacSHA1Signature(Map<String, String> parameters, String accessKeySecret) throws Exception { String signString = generateSignString(parameters, accessKeySecret); byte[] signBytes = hmacSHA1Signature(accessKeySecret, signString); assert signBytes != null; return byteToHex(signBytes); } public static String generateMd5Signature(Map<String, String> parameters, String accessKeySecret) throws Exception { String signString = generateSignString(parameters, accessKeySecret); byte[] signBytes = md5Signature(accessKeySecret, signString); assert signBytes != null; return byteToHex(signBytes); } public static String generateSignString(Map<String, String> parameters, String accessKeySecret) { ArrayList<String> arrString = new ArrayList<String>(); Set<String> keySet = parameters.keySet(); for (String key : keySet) { String value = parameters.get(key); arrString.add(key+"="+value); } Collections.sort(arrString); return String.join("&", arrString)+":"+accessKeySecret; } public static String getUrlQueryFromParams(Map<String, String> parameters){ ArrayList<String> arrString = new ArrayList<String>(); Set<String> keySet = parameters.keySet(); for (String key : keySet) { String value = parameters.get(key); arrString.add(key+"="+value); } return String.join("&", arrString); } public static byte[] hmacSHA1Signature(String secret, String baseString) throws Exception { if (isEmpty(secret)) { throw new IOException("secret can not be empty"); } if (isEmpty(baseString)) { return null; } Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), ALGORITHM); mac.init(keySpec); return mac.doFinal(baseString.getBytes(StandardCharsets.UTF_8)); } public static byte[] md5Signature(String secret, String baseString) throws Exception { if (isEmpty(secret)) { throw new IOException("secret can not be empty"); } if (isEmpty(baseString)) { return null; } MessageDigest md5=MessageDigest.getInstance("MD5"); return md5.digest(baseString.getBytes(StandardCharsets.UTF_8)); } private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } public static boolean isEmpty(@Nullable Object str) { return str == null || "".equals(str); } }
package io.github.amayaframework.core.actions; import com.github.romanqed.util.IOUtil; import io.github.amayaframework.core.contexts.HttpRequest; import io.github.amayaframework.core.pipeline.PipelineAction; import io.github.amayaframework.core.pipeline.RequestData; import io.github.amayaframework.http.ContentType; import java.io.InputStream; /** * <p>Input action which parse request body action.</p> * <p>Receives: {@link RequestData}</p> * <p>Returns: {@link RequestData}</p> */ public final class ParseRequestBodyAction extends PipelineAction<RequestData, RequestData> { @Override public RequestData execute(RequestData requestData) { HttpRequest request = requestData.getRequest(); InputStream bodyStream = requestData.getInputStream(); // Skipping body processing if the request doesn't have one if (!requestData.getMethod().isHasBody()) { request.setBody(bodyStream); return requestData; } // Process request body String rawType = requestData.getContentType(); // If there is no content type header, skip body processing if (rawType == null) { request.setBody(bodyStream); return requestData; } ContentType type = ContentType.fromHeader(rawType); // If the content-header is unknown, skip body processing if (type == null) { request.setBody(bodyStream); return requestData; } if (!type.isString()) { request.setBody(bodyStream); request.setContentType(type); return requestData; } request.setContentType(type); request.setBody(IOUtil.readInputStream(bodyStream, requestData.getCharset())); return requestData; } }
package com.github.jptx1234.mdm.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.jptx1234.mdm.dao.StuffPackDecomposeDao; import com.github.jptx1234.mdm.model.StuffPackDecompose; import com.github.jptx1234.mdm.service.StuffPackDecomposeService; @Service("stuffPackDecomposeService") public class StuffPackDecomposeServiceImpl implements StuffPackDecomposeService { @Autowired private StuffPackDecomposeDao stuffPackDecomposeDao; @Override public int count(StuffPackDecompose example) { int count = stuffPackDecomposeDao.count(example); return count; } @Override public List<StuffPackDecompose> list(StuffPackDecompose example, int pageNum, int pageSize) { int start = pageSize * (pageNum - 1); List<StuffPackDecompose> list = stuffPackDecomposeDao.listByPage(example, start, pageSize); return list; } @Override public int delete(List<Integer> idList) { return stuffPackDecomposeDao.delete(idList); } @Override public void add(StuffPackDecompose stuffPackType) { stuffPackDecomposeDao.insert(stuffPackType); } @Override public int countBlur(String kw, Integer packId) { return stuffPackDecomposeDao.countBlur(kw, packId); } @Override public List<StuffPackDecompose> listBlur(String kw, Integer page, Integer pageSize, Integer packId) { int start = pageSize * (page - 1); return stuffPackDecomposeDao.listBlur(kw, start, pageSize, packId); } }
package uk.ac.belfastmet.rhi.service; import uk.ac.belfastmet.rhi.domain.Rhi; public interface RhiRestService { Iterable<Rhi> list(); Rhi create(Rhi rhi); Rhi read(Integer rhiId); Rhi update(Integer rhiId, Rhi rhi); void delete(Integer rhiId); }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Drivetrain; public class AutoBackOutOfEdgeOfTarmac extends CommandBase { protected final Drivetrain drivetrain; /** Creates a new AutoWaitForTeammate. */ public AutoBackOutOfEdgeOfTarmac(Drivetrain drivetrain) { // Use addRequirements() here to declare subsystem dependencies. this.drivetrain = drivetrain; this.addRequirements(drivetrain); } // Called when the command is initially scheduled. @Override public void initialize() {} // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { this.drivetrain.driveWithMotionMagic(-45000, -45000); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) {} // Returns true when the command should end. @Override public boolean isFinished() { if (this.drivetrain.isDoneWithMotionMagic()) { return true; } else { return false; } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.user; import java.lang.reflect.Field; import java.util.Arrays; import java.util.ArrayList; import javax.inject.Inject; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.dao.AffinityGroupDao; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.messagebus.MessageBus; import org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleDao; import com.cloud.vm.snapshot.VMSnapshotManager; import com.cloud.vm.snapshot.VMSnapshotVO; import com.cloud.vm.snapshot.dao.VMSnapshotDao; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.configuration.dao.ResourceLimitDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterVnetDao; import com.cloud.dc.dao.DedicatedResourceDao; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.as.AutoScaleManager; import com.cloud.network.dao.AccountGuestVlanMapDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.RemoteAccessVpnDao; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.dao.SecurityGroupDao; import com.cloud.network.vpc.VpcManager; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.network.vpn.Site2SiteVpnManager; import com.cloud.projects.ProjectManager; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.storage.VolumeApiService; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.template.TemplateManager; import com.cloud.user.Account.State; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.InstanceGroupDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @RunWith(MockitoJUnitRunner.class) public class AccountManagerImplTest { @Mock AccountDao _accountDao; @Mock ConfigurationDao _configDao; @Mock ResourceCountDao _resourceCountDao; @Mock UserDao _userDao; @Mock InstanceGroupDao _vmGroupDao; @Mock UserAccountDao _userAccountDao; @Mock VolumeDao _volumeDao; @Mock UserVmDao _userVmDao; @Mock VMTemplateDao _templateDao; @Mock NetworkDao _networkDao; @Mock SecurityGroupDao _securityGroupDao; @Mock VMInstanceDao _vmDao; @Mock protected SnapshotDao _snapshotDao; @Mock protected VMTemplateDao _vmTemplateDao; @Mock SecurityGroupManager _networkGroupMgr; @Mock NetworkOrchestrationService _networkMgr; @Mock SnapshotManager _snapMgr; @Mock UserVmManager _vmMgr; @Mock TemplateManager _tmpltMgr; @Mock ConfigurationManager _configMgr; @Mock VirtualMachineManager _itMgr; @Mock RemoteAccessVpnDao _remoteAccessVpnDao; @Mock RemoteAccessVpnService _remoteAccessVpnMgr; @Mock VpnUserDao _vpnUser; @Mock DataCenterDao _dcDao; @Mock DomainManager _domainMgr; @Mock ProjectManager _projectMgr; @Mock ProjectDao _projectDao; @Mock AccountDetailsDao _accountDetailsDao; @Mock DomainDao _domainDao; @Mock ProjectAccountDao _projectAccountDao; @Mock IPAddressDao _ipAddressDao; @Mock VpcManager _vpcMgr; @Mock DomainRouterDao _routerDao; @Mock Site2SiteVpnManager _vpnMgr; @Mock AutoScaleManager _autoscaleMgr; @Mock VolumeApiService volumeService; @Mock AffinityGroupDao _affinityGroupDao; @Mock AccountGuestVlanMapDao _accountGuestVlanMapDao; @Mock DataCenterVnetDao _dataCenterVnetDao; @Mock ResourceLimitService _resourceLimitMgr; @Mock ResourceLimitDao _resourceLimitDao; @Mock DedicatedResourceDao _dedicatedDao; @Mock GlobalLoadBalancerRuleDao _gslbRuleDao; @Mock MessageBus _messageBus; @Mock VMSnapshotManager _vmSnapshotMgr; @Mock VMSnapshotDao _vmSnapshotDao; @Mock User callingUser; @Mock Account callingAccount; AccountManagerImpl accountManager; @Mock SecurityChecker securityChecker; @Before public void setup() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { accountManager = new AccountManagerImpl(); for (Field field : AccountManagerImpl.class.getDeclaredFields()) { if (field.getAnnotation(Inject.class) != null) { field.setAccessible(true); try { Field mockField = this.getClass().getDeclaredField( field.getName()); field.set(accountManager, mockField.get(this)); } catch (Exception e) { // ignore missing fields } } } accountManager.setSecurityCheckers(Arrays.asList(securityChecker)); CallContext.register(callingUser, callingAccount); } @After public void cleanup() { CallContext.unregister(); } @Test public void disableAccountNotexisting() throws ConcurrentOperationException, ResourceUnavailableException { Mockito.when(_accountDao.findById(42l)).thenReturn(null); Assert.assertTrue(accountManager.disableAccount(42)); } @Test public void disableAccountDisabled() throws ConcurrentOperationException, ResourceUnavailableException { AccountVO disabledAccount = new AccountVO(); disabledAccount.setState(State.disabled); Mockito.when(_accountDao.findById(42l)).thenReturn(disabledAccount); Assert.assertTrue(accountManager.disableAccount(42)); } @Test public void disableAccount() throws ConcurrentOperationException, ResourceUnavailableException { AccountVO account = new AccountVO(); account.setState(State.enabled); Mockito.when(_accountDao.findById(42l)).thenReturn(account); Mockito.when(_accountDao.createForUpdate()).thenReturn(new AccountVO()); Mockito.when( _accountDao.update(Mockito.eq(42l), Mockito.any(AccountVO.class))).thenReturn(true); Mockito.when(_vmDao.listByAccountId(42l)).thenReturn( Arrays.asList(Mockito.mock(VMInstanceVO.class))); Assert.assertTrue(accountManager.disableAccount(42)); Mockito.verify(_accountDao, Mockito.atLeastOnce()).update( Mockito.eq(42l), Mockito.any(AccountVO.class)); } @Test public void deleteUserAccount() { AccountVO account = new AccountVO(); account.setId(42l); DomainVO domain = new DomainVO(); Mockito.when(_accountDao.findById(42l)).thenReturn(account); Mockito.when( securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(ControlledEntity.class), Mockito.any(AccessType.class), Mockito.anyString())) .thenReturn(true); Mockito.when(_accountDao.remove(42l)).thenReturn(true); Mockito.when(_configMgr.releaseAccountSpecificVirtualRanges(42l)) .thenReturn(true); Mockito.when(_domainMgr.getDomain(Mockito.anyLong())).thenReturn(domain); Mockito.when( securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(Domain.class))) .thenReturn(true); Mockito.when(_vmSnapshotDao.listByAccountId(Mockito.anyLong())).thenReturn(new ArrayList<VMSnapshotVO>()); Assert.assertTrue(accountManager.deleteUserAccount(42)); // assert that this was a clean delete Mockito.verify(_accountDao, Mockito.never()).markForCleanup( Mockito.eq(42l)); } @Test public void deleteUserAccountCleanup() { AccountVO account = new AccountVO(); account.setId(42l); DomainVO domain = new DomainVO(); Mockito.when(_accountDao.findById(42l)).thenReturn(account); Mockito.when( securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(ControlledEntity.class), Mockito.any(AccessType.class), Mockito.anyString())) .thenReturn(true); Mockito.when(_accountDao.remove(42l)).thenReturn(true); Mockito.when(_configMgr.releaseAccountSpecificVirtualRanges(42l)) .thenReturn(true); Mockito.when(_userVmDao.listByAccountId(42l)).thenReturn( Arrays.asList(Mockito.mock(UserVmVO.class))); Mockito.when( _vmMgr.expunge(Mockito.any(UserVmVO.class), Mockito.anyLong(), Mockito.any(Account.class))).thenReturn(false); Mockito.when(_domainMgr.getDomain(Mockito.anyLong())).thenReturn(domain); Mockito.when( securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(Domain.class))) .thenReturn(true); Assert.assertTrue(accountManager.deleteUserAccount(42)); // assert that this was NOT a clean delete Mockito.verify(_accountDao, Mockito.atLeastOnce()).markForCleanup( Mockito.eq(42l)); } }
package com.example.session.login; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Nate yu * @date 2020/11/10 - 20:02:43 * @Description TODO 完成用户注销功能 */ @WebServlet("/LogoutServlet") public class LogoutServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将Session对象中的User对象移除 request.getSession().removeAttribute("user"); response.sendRedirect("/java_web_study/IndexServlet"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.match.flyantschat.web.v1; import com.match.common.context.UserContext; import com.match.oim.client.FriendsClient; import com.match.oim.client.bean.FriendsApplyRecordDTO; import com.match.oim.client.bean.FriendsApplyRecordStatus; import com.match.oim.client.bean.MessageUserSimpleInfoDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @Author zhangchao * @Date 2019/6/13 11:42 * @Version v1.0 */ @RestController @RequestMapping("/friends") @Slf4j public class FriendsController { @Autowired private FriendsClient friendsService; @PostMapping("/applyFriends") public void applyFriends(String messageUserId){ String peopleId = UserContext.getUser().getId(); friendsService.applyFriends(peopleId,messageUserId); } @PostMapping("/handlerFriendsApply") public void handlerFriendsApply(String id, FriendsApplyRecordStatus status){ String peopleId = UserContext.getUser().getId(); friendsService.handlerFriendsApply(peopleId,id,status); } @GetMapping("/getFriendsApplyList") public List<FriendsApplyRecordDTO> getFriendsApplyList(){ String peopleId = UserContext.getUser().getId(); return friendsService.getFriendsApplyList(peopleId); } @GetMapping("/getFriendsList") public List<MessageUserSimpleInfoDTO> getFriendsList(){ String peopleId = UserContext.getUser().getId(); return friendsService.getFriendsList(peopleId); } }
/** * */ package repast.simphony.scenario; /** * Event used to convey data about a scenario change. * @author Nick Collier */ public class ScenarioChangedEvent { private Object source; private String property; public ScenarioChangedEvent(Object source, String property) { this.source = source; this.property = property; } /** * Gets the source of the scenario change. * * @return the source */ public Object getSource() { return source; } /** * Gets the name of the scenario property that has changed. * * @return the property */ public String getProperty() { return property; } }
package com.em.validation.client.gwt.defects; /* GWT Validation Framework - A JSR-303 validation framework for GWT (c) gwt-validation contributors (http://code.google.com/p/gwt-validation/) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ import com.em.validation.client.core.defects.Defect_041; public class GwtDefect_041 extends Defect_041 { @Override public String getModuleName() { return "com.em.validation.ValidationTest"; } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE89_SQL_Injection__Property_executeBatch_10.java Label Definition File: CWE89_SQL_Injection.label.xml Template File: sources-sinks-10.tmpl.java */ /* * @description * CWE: 89 SQL Injection * BadSource: Property Read data from a system property * GoodSource: A hardcoded string * Sinks: executeBatch * GoodSink: Use prepared statement and executeBatch (properly) * BadSink : data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection * Flow Variant: 10 Control flow: if(IO.staticTrue) and if(IO.staticFalse) * * */ import java.sql.*; import java.util.logging.Level; public class CWE89_SQL_Injection__Property_executeBatch_10 extends AbstractTestCase { public void bad() throws Throwable { String data; if (IO.staticTrue) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticTrue) { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); for (int i = 0; i < names.length; i++) { /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */ sqlStatement.addBatch("update users set hitcount=hitcount+1 where name='" + names[i] + "'"); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } } /* goodG2B1() - use goodsource and badsink by changing first IO.staticTrue to IO.staticFalse */ private void goodG2B1() throws Throwable { String data; if (IO.staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if (IO.staticTrue) { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); for (int i = 0; i < names.length; i++) { /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */ sqlStatement.addBatch("update users set hitcount=hitcount+1 where name='" + names[i] + "'"); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } } /* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { String data; if (IO.staticTrue) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticTrue) { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; Statement sqlStatement = null; try { dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.createStatement(); for (int i = 0; i < names.length; i++) { /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */ sqlStatement.addBatch("update users set hitcount=hitcount+1 where name='" + names[i] + "'"); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } } /* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */ private void goodB2G1() throws Throwable { String data; if (IO.staticTrue) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } } /* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { String data; if (IO.staticTrue) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticTrue) { if (data != null) { String names[] = data.split("-"); int successCount = 0; Connection dbConnection = null; PreparedStatement sqlStatement = null; try { /* FIX: Use prepared statement and executeBatch (properly) */ dbConnection = IO.getDBConnection(); sqlStatement = dbConnection.prepareStatement("update users set hitcount=hitcount+1 where name=?"); for (int i = 0; i < names.length; i++) { sqlStatement.setString(1, names[i]); sqlStatement.addBatch(); } int resultsArray[] = sqlStatement.executeBatch(); for (int i = 0; i < names.length; i++) { if (resultsArray[i] > 0) { successCount++; } } IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries."); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql); } finally { try { if (sqlStatement != null) { sqlStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (dbConnection != null) { dbConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } } public void good() throws Throwable { goodG2B1(); goodG2B2(); goodB2G1(); goodB2G2(); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
/* * Copyright 1999-2017 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.jd.jdbc.sqlparser.visitor; public enum VisitorFeature { OutputUCase, OutputPrettyFormat, OutputParameterized, OutputDesensitize, OutputUseInsertValueClauseOriginalString, OutputSkipSelectListCacheString, OutputSkipInsertColumnsString, OutputParameterizedQuesUnMergeInList, OutputParameterizedQuesUnMergeOr, /** * @deprecated */ OutputKeepParenthesisWhenNotExpr; private VisitorFeature() { mask = (1 << ordinal()); } public final int mask; public static boolean isEnabled(int features, VisitorFeature feature) { return (features & feature.mask) != 0; } public static int config(int features, VisitorFeature feature, boolean state) { if (state) { features |= feature.mask; } else { features &= ~feature.mask; } return features; } public static int of(VisitorFeature... features) { if (features == null) { return 0; } int value = 0; for (VisitorFeature feature : features) { value |= feature.mask; } return value; } }
/* * %CopyrightBegin% * * Copyright Ericsson AB 2000-2021. 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. * * %CopyrightEnd% */ package com.ericsson.otp.erlang; import java.io.IOException; /** * <p> * Maintains a connection between a Java process and a remote Erlang, Java or C * node. The object maintains connection state and allows data to be sent to and * received from the peer. * </p> * * <p> * Once a connection is established between the local node and a remote node, * the connection object can be used to send and receive messages between the * nodes. * </p> * * <p> * The various receive methods are all blocking and will return only when a * valid message has been received or an exception is raised. * </p> * * <p> * If an exception occurs in any of the methods in this class, the connection * will be closed and must be reopened in order to resume communication with the * peer. * </p> * * <p> * The message delivery methods in this class deliver directly to * {@link OtpMbox mailboxes} in the {@link OtpNode OtpNode} class. * </p> * * <p> * It is not possible to create an instance of this class directly. * OtpCookedConnection objects are created as needed by the underlying mailbox * mechanism. * </p> */ public class OtpCookedConnection extends AbstractConnection { protected OtpNode self; /* * The connection needs to know which local pids have links that pass * through here, so that they can be notified in case of connection failure */ protected Links links = null; /* * Accept an incoming connection from a remote node. Used by {@link * OtpSelf#accept() OtpSelf.accept()} to create a connection based on data * received when handshaking with the peer node, when the remote node is the * connection intitiator. * * @exception java.io.IOException if it was not possible to connect to the * peer. * * @exception OtpAuthException if handshake resulted in an authentication * error */ // package scope OtpCookedConnection(final OtpNode self, final OtpTransport s) throws IOException, OtpAuthException { super(self, s); this.self = self; links = new Links(25); start(); } /* * Intiate and open a connection to a remote node. * * @exception java.io.IOException if it was not possible to connect to the * peer. * * @exception OtpAuthException if handshake resulted in an authentication * error. */ // package scope OtpCookedConnection(final OtpNode self, final OtpPeer other) throws IOException, OtpAuthException { super(self, other); this.self = self; links = new Links(25); start(); } // pass the error to the node @Override public void deliver(final Exception e) { self.deliverError(this, e); return; } /* * pass the message to the node for final delivery. Note that the connection * itself needs to know about links (in case of connection failure), so we * snoop for link/unlink too here. */ @Override public void deliver(final OtpMsg msg) { final boolean delivered = self.deliver(msg); switch (msg.type()) { case OtpMsg.linkTag: if (!delivered) { try { // no such pid - send exit to sender super.sendExit(msg.getRecipientPid(), msg.getSenderPid(), new OtpErlangAtom("noproc")); } catch (final IOException e) { } } break; default: break; } return; } /* * send to pid */ @SuppressWarnings("resource") void send(final OtpErlangPid from, final OtpErlangPid dest, final OtpErlangObject msg) throws IOException { // encode and send the message sendBuf(from, dest, new OtpOutputStream(msg)); } /* * send to remote name dest is recipient's registered name, the nodename is * implied by the choice of connection. */ @SuppressWarnings("resource") void send(final OtpErlangPid from, final String dest, final OtpErlangObject msg) throws IOException { // encode and send the message sendBuf(from, dest, new OtpOutputStream(msg)); } @Override public void close() { super.close(); breakLinks(); } @Override protected void finalize() { close(); } /* * this one called by dying/killed process */ void exit(final OtpErlangPid from, final OtpErlangPid to, final OtpErlangObject reason) { try { super.sendExit(from, to, reason); } catch (final Exception e) { } } /* * this one called explicitely by user code => use exit2 */ void exit2(final OtpErlangPid from, final OtpErlangPid to, final OtpErlangObject reason) { try { super.sendExit2(from, to, reason); } catch (final Exception e) { } } void link(final OtpErlangPid from, final OtpErlangPid to) throws OtpErlangExit { try { super.sendLink(from, to); } catch (final IOException e) { throw new OtpErlangExit("noproc", to); } } void unlink(final OtpErlangPid from, final OtpErlangPid to, final long unlink_id) { try { super.sendUnlink(from, to , unlink_id); } catch (final IOException e) { } } void unlink_ack(final OtpErlangPid from, final OtpErlangPid to, final long unlink_id) { try { super.sendUnlinkAck(from, to , unlink_id); } catch (final IOException e) { } } synchronized void node_link(OtpErlangPid local, OtpErlangPid remote, boolean add) { if (add) { links.addLink(local, remote, true); } else { links.removeLink(local, remote); } } /* * When the connection fails - send exit to all local pids with links * through this connection */ synchronized void breakLinks() { if (links != null) { final Link[] l = links.clearLinks(); if (l != null) { final int len = l.length; for (int i = 0; i < len; i++) { // send exit "from" remote pids to local ones self.deliver(new OtpMsg(OtpMsg.exitTag, l[i].remote(), l[i] .local(), new OtpErlangAtom("noconnection"))); } } } } }
/* * Copyright 2019 DiffPlug * * 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.diffplug.gradle.eclipse; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.gradle.api.Project; import groovy.util.Node; import com.diffplug.gradle.ProjectPlugin; /** * Eclipse projects can have [resource filters](https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Fconcepts%2Fresourcefilters.htm) * which include or exclude certain files. * * ![Screenshot](https://i.stack.imgur.com/7eIVE.png) * * This plugin allows you to easily configure these settings. * * ```groovy * apply plugin: 'com.diffplug.gradle.eclipse.resourcefilters' * eclipseResourceFilters { * exclude().folders().name('build') * include().folders().projectRelativePath('main/src/*') * exclude().files().name('*.class').recursive() * } * ``` * * For full details on what filters you can create, see {@link ResourceFilter}. */ public class ResourceFiltersPlugin extends ProjectPlugin { ResourceFiltersExtension extension; @SuppressWarnings("unchecked") @Override protected void applyOnce(Project project) { extension = project.getExtensions().create(ResourceFiltersExtension.NAME, ResourceFiltersExtension.class); EclipseProjectPlugin.modifyEclipseProject(project, eclipseModel -> { eclipseModel.getProject().getFile().getXmlTransformer().addAction(xmlProvider -> { Node rootNode = (Node) xmlProvider.asNode(); // remove the old filteredResources List<Node> toRemove = ((List<Node>) rootNode.children()).stream() .filter(Objects::nonNull) .filter(node -> FILTERED_RESOURCES.equals(node.name())) .collect(Collectors.toList()); toRemove.forEach(rootNode::remove); // now add ours Node filteredResources = rootNode.appendNode(FILTERED_RESOURCES); for (ResourceFilter toExclude : extension.filters) { toExclude.appendToFilteredResources(filteredResources); } }); }); } static final String FILTERED_RESOURCES = "filteredResources"; }
package p; class A{ int temp; void m(){ int i= 10; temp= 0; }; }
package net.barragem.view.backingbean; import javax.faces.event.ActionEvent; import net.barragem.business.bo.MensagemBo; import net.barragem.persistence.entity.Mensagem; import net.barragem.persistence.entity.Usuario; import net.barragem.scaffold.Paginavel; import net.barragem.scaffold.PaginavelSampleImpl; import net.barragem.scaffold.PersistenceHelper; import net.barragem.view.backingbean.componentes.TextoEFlagPrivadoDto; import org.ajax4jsf.model.KeepAlive; @KeepAlive public class ExibirMensagensBean extends BaseBean { private Usuario usuarioEmFoco; private TextoEFlagPrivadoDto mensagem = new TextoEFlagPrivadoDto(); private Paginavel<Mensagem> paginacaoMensagens; public Usuario getUsuarioEmFoco() { return usuarioEmFoco; } public void setUsuarioEmFoco(Usuario usuarioEmFoco) { this.usuarioEmFoco = usuarioEmFoco; } public TextoEFlagPrivadoDto getMensagem() { return mensagem; } public void setMensagem(TextoEFlagPrivadoDto mensagem) { this.mensagem = mensagem; } public Paginavel<Mensagem> getPaginacaoMensagens() { return paginacaoMensagens; } public void setPaginacaoMensagens(Paginavel<Mensagem> paginacaoMensagens) { this.paginacaoMensagens = paginacaoMensagens; } public String envia() { Mensagem focus = getBo(MensagemBo.class).envia(usuarioEmFoco, mensagem.getTexto(), mensagem.getPrivada()); paginacaoMensagens = new PaginavelSampleImpl<Mensagem>(PersistenceHelper.findByNamedQuery( "mensagensVisiveisQuery", getUsuarioLogado(), usuarioEmFoco), focus, null, 5); mensagem = new TextoEFlagPrivadoDto(); addMensagemAtualizacaoComSucesso(); return ""; } public void exclui(ActionEvent e) { PersistenceHelper.remove(paginacaoMensagens.getPagina().get(getIndex())); paginacaoMensagens = new PaginavelSampleImpl<Mensagem>(PersistenceHelper.findByNamedQuery( "mensagensVisiveisQuery", getUsuarioLogado(), usuarioEmFoco), paginacaoMensagens.getPaginaAtual(), 5); addMensagemAtualizacaoComSucesso(); } public void exibeMensagens(ActionEvent e) { usuarioEmFoco = PersistenceHelper.findByPk(Usuario.class, getId()); paginacaoMensagens = new PaginavelSampleImpl<Mensagem>(PersistenceHelper.findByNamedQuery( "mensagensVisiveisQuery", getUsuarioLogado(), usuarioEmFoco), null, 5); } public Integer getTotalMensagens() { return paginacaoMensagens.getSourceList().size(); } public Integer getTotalMensagensPrivadas() { Integer result = 0; for (Mensagem mensagem : paginacaoMensagens.getSourceList()) { if (mensagem.isPrivada()) { result++; } } return result; } }
package CSharp.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.DefaultNodeEditor; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.openapi.editor.EditorContext; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.nodeEditor.cells.EditorCell_Collection; import jetbrains.mps.nodeEditor.cells.EditorCell_Constant; import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo; import jetbrains.mps.nodeEditor.cellMenu.OldNewCompositeSubstituteInfo; import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo; import jetbrains.mps.nodeEditor.cellMenu.DefaultChildSubstituteInfo; public class Primary_expression_start_block_8_1_2_Editor extends DefaultNodeEditor { public EditorCell createEditorCell(EditorContext editorContext, SNode node) { return this.createCollection_ozq0pw_a(editorContext, node); } private EditorCell createCollection_ozq0pw_a(EditorContext editorContext, SNode node) { EditorCell_Collection editorCell = EditorCell_Collection.createIndent2(editorContext, node); editorCell.setCellId("Collection_ozq0pw_a"); editorCell.setBig(true); editorCell.addEditorCell(this.createConstant_ozq0pw_a0(editorContext, node)); editorCell.addEditorCell(this.createRefNode_ozq0pw_b0(editorContext, node)); editorCell.addEditorCell(this.createConstant_ozq0pw_c0(editorContext, node)); return editorCell; } private EditorCell createConstant_ozq0pw_a0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "["); editorCell.setCellId("Constant_ozq0pw_a0"); editorCell.setDefaultText(""); return editorCell; } private EditorCell createRefNode_ozq0pw_b0(EditorContext editorContext, SNode node) { SingleRoleCellProvider provider = new Primary_expression_start_block_8_1_2_Editor.Expression_list_1SingleRoleHandler_ozq0pw_b0(node, MetaAdapterFactory.getContainmentLink(0x5f522167449a4486L, 0x94654f30de6e5cecL, 0x70aadf795f706cL, 0x70aadf795f737fL, "Expression_list_1"), editorContext); return provider.createCell(); } private class Expression_list_1SingleRoleHandler_ozq0pw_b0 extends SingleRoleCellProvider { public Expression_list_1SingleRoleHandler_ozq0pw_b0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) { super(ownerNode, containmentLink, context); } protected EditorCell createChildCell(SNode child) { EditorCell editorCell = super.createChildCell(child); installCellInfo(child, editorCell); return editorCell; } private void installCellInfo(SNode child, EditorCell editorCell) { if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) { editorCell.setSubstituteInfo(new OldNewCompositeSubstituteInfo(myEditorContext, new SChildSubstituteInfo(editorCell, myOwnerNode, MetaAdapterFactory.getContainmentLink(0x5f522167449a4486L, 0x94654f30de6e5cecL, 0x70aadf795f706cL, 0x70aadf795f737fL, "Expression_list_1"), child), new DefaultChildSubstituteInfo(myOwnerNode, myContainmentLink.getDeclarationNode(), myEditorContext))); } if (editorCell.getRole() == null) { editorCell.setRole("Expression_list_1"); } } @Override protected EditorCell createEmptyCell() { EditorCell editorCell = createEmptyCell_internal(myEditorContext, myOwnerNode); installCellInfo(null, editorCell); return editorCell; } private EditorCell createEmptyCell_internal(EditorContext editorContext, SNode node) { return this.createConstant_ozq0pw_a1a(editorContext, node); } private EditorCell createConstant_ozq0pw_a1a(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, " "); editorCell.setCellId("Constant_ozq0pw_a1a"); editorCell.setDefaultText(""); return editorCell; } } private EditorCell createConstant_ozq0pw_c0(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, "]"); editorCell.setCellId("Constant_ozq0pw_c0"); editorCell.setDefaultText(""); return editorCell; } }
/* * Copyright 2011 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jayway.jsonpath.spi.impl; import com.jayway.jsonpath.InvalidJsonException; import com.jayway.jsonpath.spi.MappingProvider; import com.jayway.jsonpath.spi.Mode; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.type.CollectionType; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringWriter; import java.util.*; /** * @author Kalle Stenflo */ public class JacksonProvider extends AbstractJsonProvider implements MappingProvider{ private ObjectMapper objectMapper = new ObjectMapper(); @Override public Mode getMode() { return Mode.STRICT; } @Override public Object parse(String json) throws InvalidJsonException { try { return objectMapper.readValue(json, Object.class); } catch (IOException e) { throw new InvalidJsonException(e); } } @Override public Object parse(Reader jsonReader) throws InvalidJsonException { try { return objectMapper.readValue(jsonReader, Object.class); } catch (IOException e) { throw new InvalidJsonException(e); } } @Override public Object parse(InputStream jsonStream) throws InvalidJsonException { try { return objectMapper.readValue(jsonStream, Object.class); } catch (IOException e) { throw new InvalidJsonException(e); } } @Override public String toJson(Object obj) { StringWriter writer = new StringWriter(); try { JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(writer); objectMapper.writeValue(jsonGenerator, obj); writer.close(); return writer.getBuffer().toString(); } catch (IOException e) { throw new InvalidJsonException(); } } @Override public Map<String, Object> createMap() { return new HashMap<String, Object>(); } @Override public List<Object> createList() { return new LinkedList<Object>(); } //------------------------------------------------------------------- // // Mapping provider // //------------------------------------------------------------------- @Override public <T> T convertValue(Object fromValue, Class<T> toValueType) throws IllegalArgumentException { return objectMapper.convertValue(fromValue, toValueType); } @Override @SuppressWarnings({"unchecked"}) public <T extends Collection<E>, E> T convertValue(Object fromValue, Class<T> collectionType, Class<E> elementType) throws IllegalArgumentException { CollectionType colType = objectMapper.getTypeFactory().constructCollectionType(collectionType, elementType); return (T)objectMapper.convertValue(fromValue, colType); } }
package edu.ucsb.cs156.spring.hello; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class HelloController { @RequestMapping("/") public String index() { return "Greetings from ningxia!"; } }
/******************************************************************************* * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. *******************************************************************************/ package org.alljoyn.validation.testing.suites.controller.alljoyn; import org.alljoyn.bus.BusException; import org.alljoyn.bus.annotation.BusInterface; import org.alljoyn.bus.annotation.BusProperty; import org.alljoyn.bus.annotation.BusMethod; import org.alljoyn.bus.annotation.BusSignal; @BusInterface(name="org.allseen.LSF.ControllerService") public interface ControllerServiceBusInterface { /* from service_framework\standard_core_library\lighting_controller_service\src\ServiceDescription.cc */ /* " <property name="Version" type="u" access="read" />" */ @BusProperty(signature="u") public int getVersion() throws BusException; /* " <method name="LightingResetControllerService">" " <arg name="responseCode" type="u" direction="out" />"" " </method>" */ @BusMethod(replySignature = "u") public int LightingResetControllerService() throws BusException; /* " <method name="GetControllerServiceVersion">" " <arg name="version" type="u" direction="out" />" " </method>" */ @BusMethod(replySignature = "u") public int GetControllerServiceVersion() throws BusException; /* " <signal name="ControllerServiceLightingReset"></signal>" */ @BusSignal public void ControllerServiceLightingReset() throws BusException; }
package ru.job4j.additionaltask; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static java.util.concurrent.TimeUnit.SECONDS; /** * Class is bank. * * @since 22/10/2017 * @version 1 */ public class Bank { /** * Collection of rush hours in form of TimeDistance class, value is counter. */ private final HashMap<TimeDistance, Integer> rushHours = new HashMap<>(); /** * Customers of bank. */ private final List<Customer> customers = new ArrayList<>(); /** * Adds customer. * * @param customer is customer */ public void addCustomer(Customer customer) { customers.add(customer); } /** * Finds rush hours. * * @return list of rush hours in form of TimeDistance class. */ public List<TimeDistance> findRushHour() { for (Customer customer : customers) { long start = customer.getTimeInBank().start; long end = customer.getTimeInBank().end; find(start, end); } // ищем максимальное значение int max = Integer.MIN_VALUE; for (int i : rushHours.values()) { if(i > max) max = i; } // по значению Integer. являющегося счетчиком, // в карте забираем TimeDistance List<TimeDistance> result = new ArrayList<>(); for(Map.Entry<TimeDistance, Integer> pair : rushHours.entrySet()) { if (pair.getValue() == max) result.add(pair.getKey()); } return result; } /** * Finds rush hour from start time interval. * * @param start of time interval * @param end of time interval */ private void find(long start, long end) { int count = 0; long s = start; long e = end; for(int i = 0; i < customers.size(); i++) { long newStart = customers.get(i).getTimeInBank().start; long newEnd = customers.get(i).getTimeInBank().end; if(s <= newStart && e > newStart) { s = newStart; count++; if(newEnd < e) { e = newEnd; } } else if (s > newStart && e > newStart && newEnd > s) { count++; if (newEnd <= e) { e = newEnd; } } } rushHours.put(new TimeDistance(s, e), count); } }
/* * 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.gobblin.hive.metastore; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.apache.avro.Schema; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.IMetaStoreClient; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.serde2.avro.AvroSerdeUtils; import org.apache.thrift.TException; import org.joda.time.DateTime; import com.codahale.metrics.Timer; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.primitives.Ints; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.configuration.State; import org.apache.gobblin.hive.AutoCloseableHiveLock; import org.apache.gobblin.hive.HiveLock; import org.apache.gobblin.hive.HiveMetaStoreClientFactory; import org.apache.gobblin.hive.HiveMetastoreClientPool; import org.apache.gobblin.hive.HivePartition; import org.apache.gobblin.hive.HiveRegProps; import org.apache.gobblin.hive.HiveRegister; import org.apache.gobblin.hive.HiveRegistrationUnit.Column; import org.apache.gobblin.hive.HiveTable; import org.apache.gobblin.hive.spec.HiveSpec; import org.apache.gobblin.metrics.GobblinMetrics; import org.apache.gobblin.metrics.GobblinMetricsRegistry; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.event.EventSubmitter; import org.apache.gobblin.metrics.kafka.KafkaSchemaRegistry; import org.apache.gobblin.source.extractor.extract.kafka.KafkaSource; import org.apache.gobblin.util.AutoReturnableObject; import org.apache.gobblin.util.AvroUtils; /** * An implementation of {@link HiveRegister} that uses {@link IMetaStoreClient} for Hive registration. * * <p> * An instance of this class is constructed with a {@link State} object or obtained via * {@link HiveRegister#get(State)}. Property {@link HiveRegProps#HIVE_DB_ROOT_DIR} is required for registering * a table or a partition if the database does not exist. * </p> * * <p> * The {@link #register(HiveSpec)} method is asynchronous and returns immediately. Registration is performed in a * thread pool whose size is controlled by {@link HiveRegProps#HIVE_REGISTER_THREADS}. * </p> * * @author Ziyang Liu */ @Slf4j @Alpha public class HiveMetaStoreBasedRegister extends HiveRegister { public static final String HIVE_REGISTER_METRICS_PREFIX = "hiveRegister."; public static final String ADD_PARTITION_TIMER = HIVE_REGISTER_METRICS_PREFIX + "addPartitionTimerTimer"; public static final String SCHEMA_SOURCE_DB = HIVE_REGISTER_METRICS_PREFIX + "schema.source.dbName"; public static final String GET_HIVE_PARTITION = HIVE_REGISTER_METRICS_PREFIX + "getPartitionTimer"; public static final String ALTER_PARTITION = HIVE_REGISTER_METRICS_PREFIX + "alterPartitionTimer"; public static final String TABLE_EXISTS = HIVE_REGISTER_METRICS_PREFIX + "tableExistsTimer"; public static final String ALTER_TABLE = HIVE_REGISTER_METRICS_PREFIX + "alterTableTimer"; public static final String GET_HIVE_DATABASE = HIVE_REGISTER_METRICS_PREFIX + "getDatabaseTimer"; public static final String CREATE_HIVE_DATABASE = HIVE_REGISTER_METRICS_PREFIX + "createDatabaseTimer"; public static final String CREATE_HIVE_TABLE = HIVE_REGISTER_METRICS_PREFIX + "createTableTimer"; public static final String GET_HIVE_TABLE = HIVE_REGISTER_METRICS_PREFIX + "getTableTimer"; public static final String GET_SCHEMA_SOURCE_HIVE_TABLE = HIVE_REGISTER_METRICS_PREFIX + "getSchemaSourceTableTimer"; public static final String GET_AND_SET_LATEST_SCHEMA = HIVE_REGISTER_METRICS_PREFIX + "getAndSetLatestSchemaTimer"; public static final String DROP_TABLE = HIVE_REGISTER_METRICS_PREFIX + "dropTableTimer"; public static final String PATH_REGISTER_TIMER = HIVE_REGISTER_METRICS_PREFIX + "pathRegisterTimer"; public static final String SKIP_PARTITION_DIFF_COMPUTATION = HIVE_REGISTER_METRICS_PREFIX + "skip.partition.diff.computation"; public static final String FETCH_LATEST_SCHEMA = HIVE_REGISTER_METRICS_PREFIX + "fetchLatestSchemaFromSchemaRegistry"; //A config which when enabled checks for the existence of a partition in Hive before adding the partition. // This is done to minimize the add_partition calls sent to Hive. public static final String REGISTER_PARTITION_WITH_PULL_MODE = HIVE_REGISTER_METRICS_PREFIX + "registerPartitionWithPullMode"; /** * To reduce lock aquisition and RPC to metaStoreClient, we cache the result of query regarding to * the existence of databases and tables in {@link #tableAndDbExistenceCache}, * so that for databases/tables existed in cache, a RPC for query the existence can be saved. * * We make this optimization configurable by setting {@link #OPTIMIZED_CHECK_ENABLED} to be true. */ public static final String OPTIMIZED_CHECK_ENABLED = "hiveRegister.cacheDbTableExistence"; private final HiveMetastoreClientPool clientPool; private final HiveLock locks; private final EventSubmitter eventSubmitter; private final MetricContext metricContext; private final boolean shouldUpdateLatestSchema; private final boolean registerPartitionWithPullMode; /** * Local cache that contains records for both databases and tables. * To distinguish tables with the same name but in different databases, * use the <databaseName>:<tableName> as the key. * * The value(true/false) in cache doesn't really matter, the existence of entry in cache guarantee the table is existed on hive. * The value in k-v pair in cache indicates: * when the first time a table/database is loaded into the cache, whether they existed on the remote hiveMetaStore side. */ CacheLoader<String, Boolean> cacheLoader = new CacheLoader<String, Boolean>() { @Override public Boolean load(String key) throws Exception { return true; } }; Cache<String, Boolean> tableAndDbExistenceCache = CacheBuilder.newBuilder().build(cacheLoader); private final boolean optimizedChecks; private final State state; //If this is true, after we know the partition is existing, we will skip the partition in stead of getting the existing // partition and computing the diff to see if it needs to be updated. Use this only when you can make sure the metadata //for a partition is immutable private final boolean skipDiffComputation; @VisibleForTesting protected Optional<KafkaSchemaRegistry> schemaRegistry = Optional.absent(); private String topicName = ""; public HiveMetaStoreBasedRegister(State state, Optional<String> metastoreURI) throws IOException { super(state); this.state = state; this.locks = new HiveLock(state.getProperties()); this.optimizedChecks = state.getPropAsBoolean(OPTIMIZED_CHECK_ENABLED, true); this.skipDiffComputation = state.getPropAsBoolean(SKIP_PARTITION_DIFF_COMPUTATION, false); this.shouldUpdateLatestSchema = state.getPropAsBoolean(FETCH_LATEST_SCHEMA, false); this.registerPartitionWithPullMode = state.getPropAsBoolean(REGISTER_PARTITION_WITH_PULL_MODE, false); if(this.shouldUpdateLatestSchema) { this.schemaRegistry = Optional.of(KafkaSchemaRegistry.get(state.getProperties())); topicName = state.getProp(KafkaSource.TOPIC_NAME); } GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(this.props.getNumThreads()); config.setMaxIdle(this.props.getNumThreads()); this.clientPool = HiveMetastoreClientPool.get(this.props.getProperties(), metastoreURI); this.metricContext = GobblinMetricsRegistry.getInstance().getMetricContext(state, HiveMetaStoreBasedRegister.class, GobblinMetrics.getCustomTagsFromState(state)); this.eventSubmitter = new EventSubmitter.Builder(this.metricContext, "org.apache.gobblin.hive.HiveMetaStoreBasedRegister").build(); } @Override protected void registerPath(HiveSpec spec) throws IOException { try (Timer.Context context = this.metricContext.timer(PATH_REGISTER_TIMER).time(); AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { Table table = HiveMetaStoreUtils.getTable(spec.getTable()); // Abort the rest of operations if a view is seen. if (table.getTableType().equals(TableType.VIRTUAL_VIEW.name())) { String msg = "Cannot register paths against a view on Hive for:" + spec.getPath() + " on table:" + spec.getTable().toString(); log.info(msg); HiveMetaStoreEventHelper.submitFailedPathRegistration(eventSubmitter, spec, new UnsupportedOperationException(msg)); } createDbIfNotExists(client.get(), table.getDbName()); createOrAlterTable(client.get(), table, spec); Optional<HivePartition> partition = spec.getPartition(); if (partition.isPresent()) { addOrAlterPartition(client.get(), table, partition.get()); } HiveMetaStoreEventHelper.submitSuccessfulPathRegistration(eventSubmitter, spec); } catch (TException e) { HiveMetaStoreEventHelper.submitFailedPathRegistration(eventSubmitter, spec, e); throw new IOException(e); } } /** * This method is used to update the table schema to the latest schema * It will fetch creation time of the latest schema from schema registry and compare that * with the creation time of writer's schema. If they are the same, then we will update the * table schema to the writer's schema, else we will keep the table schema the same as schema of * existing table. * Note: If there is no schema specified in the table spec, we will directly update the schema to * the existing table schema * Note: We cannot treat the creation time as version number of schema, since schema registry allows * "out of order registration" of schemas, this means chronological latest is NOT what the registry considers latest. * @param spec * @param table * @param existingTable * @throws IOException */ @VisibleForTesting protected void updateSchema(HiveSpec spec, Table table, HiveTable existingTable) throws IOException{ if (this.schemaRegistry.isPresent() && existingTable.getSerDeProps().getProp( AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName()) != null) { try (Timer.Context context = this.metricContext.timer(GET_AND_SET_LATEST_SCHEMA).time()) { Schema existingTableSchema = new Schema.Parser().parse(existingTable.getSerDeProps().getProp( AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName())); String existingSchemaCreationTime = AvroUtils.getSchemaCreationTime(existingTableSchema); // If no schema set for the table spec, we fall back to existing schema if (spec.getTable().getSerDeProps().getProp(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName()) == null) { spec.getTable() .getSerDeProps() .setProp(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName(), existingTableSchema); HiveMetaStoreUtils.updateColumnsInfoIfNeeded(spec); table.setSd(HiveMetaStoreUtils.getStorageDescriptor(spec.getTable())); return; } Schema writerSchema = new Schema.Parser().parse(( spec.getTable().getSerDeProps().getProp(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName()))); String writerSchemaCreationTime = AvroUtils.getSchemaCreationTime(writerSchema); if(existingSchemaCreationTime != null && !existingSchemaCreationTime.equals(writerSchemaCreationTime)) { // If creation time of writer schema does not equal to the existing schema, we compare with schema fetched from // schema registry to determine whether to update the schema Schema latestSchema = (Schema) this.schemaRegistry.get().getLatestSchemaByTopic(topicName); String latestSchemaCreationTime = AvroUtils.getSchemaCreationTime(latestSchema); if (latestSchemaCreationTime != null && latestSchemaCreationTime.equals(existingSchemaCreationTime)) { // If latest schema creation time equals to existing schema creation time, we keep the schema as existing table schema spec.getTable() .getSerDeProps() .setProp(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName(), existingTableSchema); HiveMetaStoreUtils.updateColumnsInfoIfNeeded(spec); table.setSd(HiveMetaStoreUtils.getStorageDescriptor(spec.getTable())); } } } catch ( IOException e) { log.error(String.format("Error when updating latest schema for topic %s", topicName)); throw new IOException(e); } } } /** * If table existed on Hive side will return false; * Or will create the table thru. RPC and return retVal from remote MetaStore. */ private boolean ensureHiveTableExistenceBeforeAlternation(String tableName, String dbName, IMetaStoreClient client, Table table) throws TException, IOException{ try (AutoCloseableHiveLock lock = this.locks.getTableLock(dbName, tableName)) { try { if (!existsTable(dbName, tableName, client)) { try (Timer.Context context = this.metricContext.timer(CREATE_HIVE_TABLE).time()) { client.createTable(getTableWithCreateTimeNow(table)); log.info(String.format("Created Hive table %s in db %s", tableName, dbName)); return true; } } } catch (AlreadyExistsException ignore) { // Table already exists, continue } catch (TException e) { log.error( String.format("Unable to create Hive table %s in db %s: " + e.getMessage(), tableName, dbName), e); throw e; } log.info("Table {} already exists in db {}.", tableName, dbName); // When the logic up to here it means table already existed in db. Return false. return false; } } private void alterTableIfNeeded (String tableName, String dbName, IMetaStoreClient client, Table table, HiveSpec spec) throws TException, IOException { try { HiveTable existingTable; try (Timer.Context context = this.metricContext.timer(GET_HIVE_TABLE).time()) { existingTable = HiveMetaStoreUtils.getHiveTable(client.getTable(dbName, tableName)); } HiveTable schemaSourceTable = existingTable; if (state.contains(SCHEMA_SOURCE_DB)) { try (Timer.Context context = this.metricContext.timer(GET_SCHEMA_SOURCE_HIVE_TABLE).time()) { // We assume the schema source table has the same table name as the origin table, so only the db name can be configured schemaSourceTable = HiveMetaStoreUtils.getHiveTable(client.getTable(state.getProp(SCHEMA_SOURCE_DB, dbName), tableName)); } } if(shouldUpdateLatestSchema) { updateSchema(spec, table, schemaSourceTable); } if (needToUpdateTable(existingTable, HiveMetaStoreUtils.getHiveTable(table))) { try (Timer.Context context = this.metricContext.timer(ALTER_TABLE).time()) { client.alter_table(dbName, tableName, getNewTblByMergingExistingTblProps(table, existingTable)); } log.info(String.format("updated Hive table %s in db %s", tableName, dbName)); } } catch (TException e2) { log.error( String.format("Unable to alter Hive table %s in db %s: " + e2.getMessage(), tableName, dbName), e2); throw e2; } } /** * If databse existed on Hive side will return false; * Or will create the table thru. RPC and return retVal from remote MetaStore. * @param hiveDbName is the hive databases to be checked for existence */ private boolean ensureHiveDbExistence(String hiveDbName, IMetaStoreClient client) throws IOException{ try (AutoCloseableHiveLock lock = this.locks.getDbLock(hiveDbName)) { Database db = new Database(); db.setName(hiveDbName); try { try (Timer.Context context = this.metricContext.timer(GET_HIVE_DATABASE).time()) { client.getDatabase(db.getName()); } return false; } catch (NoSuchObjectException nsoe) { // proceed with create } catch (TException te) { throw new IOException(te); } Preconditions.checkState(this.hiveDbRootDir.isPresent(), "Missing required property " + HiveRegProps.HIVE_DB_ROOT_DIR); db.setLocationUri(new Path(this.hiveDbRootDir.get(), hiveDbName + HIVE_DB_EXTENSION).toString()); try { try (Timer.Context context = this.metricContext.timer(CREATE_HIVE_DATABASE).time()) { client.createDatabase(db); } log.info("Created database " + hiveDbName); HiveMetaStoreEventHelper.submitSuccessfulDBCreation(this.eventSubmitter, hiveDbName); return true; } catch (AlreadyExistsException e) { return false; } catch (TException e) { HiveMetaStoreEventHelper.submitFailedDBCreation(this.eventSubmitter, hiveDbName, e); throw new IOException("Unable to create Hive database " + hiveDbName, e); } } } /** * @return true if the db is successfully created. * false if the db already exists. * @throws IOException */ private boolean createDbIfNotExists(IMetaStoreClient client, String dbName) throws IOException { boolean retVal; if (this.optimizedChecks) { try { retVal = this.tableAndDbExistenceCache.get(dbName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return ensureHiveDbExistence(dbName, client); } }); } catch (ExecutionException ee) { throw new IOException("Database existence checking throwing execution exception.", ee); } return retVal; } else { return this.ensureHiveDbExistence(dbName, client); } } /** * @deprecated Use {@link #createDbIfNotExists(IMetaStoreClient, String)} directly. */ @Deprecated public boolean createDbIfNotExists(String dbName) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { return createDbIfNotExists(client.get(), dbName); } } /** * @deprecated Please use {@link #createOrAlterTable(IMetaStoreClient, Table, HiveSpec)} instead. */ @Deprecated @Override public boolean createTableIfNotExists(HiveTable table) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { return createTableIfNotExists(client.get(), HiveMetaStoreUtils.getTable(table), table); } } /** * @deprecated Use {@link #addOrAlterPartition} instead. */ @Deprecated @Override public boolean addPartitionIfNotExists(HiveTable table, HivePartition partition) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient(); AutoCloseableHiveLock lock = this.locks.getTableLock(table.getDbName(), table.getTableName())) { try { try (Timer.Context context = this.metricContext.timer(GET_HIVE_PARTITION).time()) { client.get().getPartition(table.getDbName(), table.getTableName(), partition.getValues()); } return false; } catch (NoSuchObjectException e) { try (Timer.Context context = this.metricContext.timer(ADD_PARTITION_TIMER).time()) { client.get().add_partition(getPartitionWithCreateTimeNow(HiveMetaStoreUtils.getPartition(partition))); } HiveMetaStoreEventHelper.submitSuccessfulPartitionAdd(this.eventSubmitter, table, partition); return true; } } catch (TException e) { HiveMetaStoreEventHelper.submitFailedPartitionAdd(this.eventSubmitter, table, partition, e); throw new IOException(String.format("Unable to add partition %s in table %s in db %s", partition.getValues(), table.getTableName(), table.getDbName()), e); } } @Deprecated /** * @deprecated Please use {@link #createOrAlterTable(IMetaStoreClient, Table, HiveSpec)} instead. */ private boolean createTableIfNotExists(IMetaStoreClient client, Table table, HiveTable hiveTable) throws IOException { String dbName = table.getDbName(); String tableName = table.getTableName(); try (AutoCloseableHiveLock lock = this.locks.getTableLock(dbName, tableName)) { boolean tableExists; try (Timer.Context context = this.metricContext.timer(TABLE_EXISTS).time()) { tableExists = client.tableExists(table.getDbName(), table.getTableName()); } if (tableExists) { return false; } try (Timer.Context context = this.metricContext.timer(CREATE_HIVE_TABLE).time()) { client.createTable(getTableWithCreateTimeNow(table)); } log.info(String.format("Created Hive table %s in db %s", tableName, dbName)); HiveMetaStoreEventHelper.submitSuccessfulTableCreation(this.eventSubmitter, hiveTable); return true; } catch (TException e) { HiveMetaStoreEventHelper.submitFailedTableCreation(eventSubmitter, hiveTable, e); throw new IOException(String.format("Error in creating or altering Hive table %s in db %s", table.getTableName(), table.getDbName()), e); } } private void createOrAlterTable(IMetaStoreClient client, Table table, HiveSpec spec) throws TException, IOException { String dbName = table.getDbName(); String tableName = table.getTableName(); this.ensureHiveTableExistenceBeforeAlternation(tableName, dbName, client, table); alterTableIfNeeded(tableName, dbName, client, table, spec); } public boolean existsTable(String dbName, String tableName, IMetaStoreClient client) throws IOException { Boolean tableExits = this.tableAndDbExistenceCache.getIfPresent(dbName + ":" + tableName ); if (this.optimizedChecks && tableExits != null && tableExits) { return true; } try { boolean exists; try (Timer.Context context = this.metricContext.timer(TABLE_EXISTS).time()) { exists = client.tableExists(dbName, tableName); } this.tableAndDbExistenceCache.put(dbName + ":" + tableName, exists); return exists; } catch (TException e) { throw new IOException(String.format("Unable to check existence of table %s in db %s", tableName, dbName), e); } } @Override public boolean existsTable(String dbName, String tableName) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { return existsTable(dbName, tableName, client.get()); } } @Override public boolean existsPartition(String dbName, String tableName, List<Column> partitionKeys, List<String> partitionValues) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { try (Timer.Context context = this.metricContext.timer(GET_HIVE_PARTITION).time()) { client.get().getPartition(dbName, tableName, partitionValues); } return true; } catch (NoSuchObjectException e) { return false; } catch (TException e) { throw new IOException(String.format("Unable to check existence of partition %s in table %s in db %s", partitionValues, tableName, dbName), e); } } @Override public void dropTableIfExists(String dbName, String tableName) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { boolean tableExists; try (Timer.Context context = this.metricContext.timer(TABLE_EXISTS).time()) { tableExists = client.get().tableExists(dbName, tableName); } if (tableExists) { try (Timer.Context context = this.metricContext.timer(DROP_TABLE).time()) { client.get().dropTable(dbName, tableName, false, false); } String metastoreURI = this.clientPool.getHiveConf().get(HiveMetaStoreClientFactory.HIVE_METASTORE_TOKEN_SIGNATURE, "null"); HiveMetaStoreEventHelper.submitSuccessfulTableDrop(eventSubmitter, dbName, tableName, metastoreURI); log.info("Dropped table " + tableName + " in db " + dbName); } } catch (TException e) { HiveMetaStoreEventHelper.submitFailedTableDrop(eventSubmitter, dbName, tableName, e); throw new IOException(String.format("Unable to deregister table %s in db %s", tableName, dbName), e); } } @Override public void dropPartitionIfExists(String dbName, String tableName, List<Column> partitionKeys, List<String> partitionValues) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { if (client.get().getPartition(dbName, tableName, partitionValues) == null) { // Partition does not exist. Nothing to do return; } try (Timer.Context context = this.metricContext.timer(DROP_TABLE).time()) { client.get().dropPartition(dbName, tableName, partitionValues, false); } String metastoreURI = this.clientPool.getHiveConf().get(HiveMetaStoreClientFactory.HIVE_METASTORE_TOKEN_SIGNATURE, "null"); HiveMetaStoreEventHelper.submitSuccessfulPartitionDrop(eventSubmitter, dbName, tableName, partitionValues, metastoreURI); log.info("Dropped partition " + partitionValues + " in table " + tableName + " in db " + dbName); } catch (NoSuchObjectException e) { // Partition does not exist. Nothing to do } catch (TException e) { HiveMetaStoreEventHelper.submitFailedPartitionDrop(eventSubmitter, dbName, tableName, partitionValues, e); throw new IOException(String.format("Unable to check existence of Hive partition %s in table %s in db %s", partitionValues, tableName, dbName), e); } } @Override public void addOrAlterPartition(HiveTable table, HivePartition partition) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { addOrAlterPartition(client.get(), HiveMetaStoreUtils.getTable(table), partition); } catch (TException te) { throw new IOException( String.format("Failed to add/alter partition %s.%s@%s", table.getDbName(), table.getTableName(), partition.getValues()), te); } } private void addOrAlterPartitionWithPushMode(IMetaStoreClient client, Table table, HivePartition partition) throws TException, IOException { Partition nativePartition = HiveMetaStoreUtils.getPartition(partition); Preconditions.checkArgument(table.getPartitionKeysSize() == nativePartition.getValues().size(), String.format("Partition key size is %s but partition value size is %s", table.getPartitionKeys().size(), nativePartition.getValues().size())); try (AutoCloseableHiveLock lock = this.locks.getPartitionLock(table.getDbName(), table.getTableName(), nativePartition.getValues())) { try { try (Timer.Context context = this.metricContext.timer(ADD_PARTITION_TIMER).time()) { client.add_partition(getPartitionWithCreateTimeNow(nativePartition)); } log.info(String.format("Added partition %s to table %s with location %s", stringifyPartition(nativePartition), table.getTableName(), nativePartition.getSd().getLocation())); } catch (AlreadyExistsException e) { try { if (this.skipDiffComputation) { onPartitionExistWithoutComputingDiff(table, nativePartition, e); } else { onPartitionExist(client, table, partition, nativePartition, null); } } catch (Throwable e2) { log.error(String.format( "Unable to add or alter partition %s in table %s with location %s: " + e2.getMessage(), stringifyPartitionVerbose(nativePartition), table.getTableName(), nativePartition.getSd().getLocation()), e2); throw e2; } } } } private void addOrAlterPartition(IMetaStoreClient client, Table table, HivePartition partition) throws TException, IOException { if(!registerPartitionWithPullMode) { addOrAlterPartitionWithPushMode(client, table, partition); } else { addOrAlterPartitionWithPullMode(client, table, partition); } } private void addOrAlterPartitionWithPullMode(IMetaStoreClient client, Table table, HivePartition partition) throws TException, IOException { Partition nativePartition = HiveMetaStoreUtils.getPartition(partition); Preconditions.checkArgument(table.getPartitionKeysSize() == nativePartition.getValues().size(), String.format("Partition key size is %s but partition value size is %s", table.getPartitionKeys().size(), nativePartition.getValues().size())); try (AutoCloseableHiveLock lock = this.locks.getPartitionLock(table.getDbName(), table.getTableName(), nativePartition.getValues())) { Partition existedPartition; try { try (Timer.Context context = this.metricContext.timer(GET_HIVE_PARTITION).time()) { existedPartition = client.getPartition(table.getDbName(), table.getTableName(), nativePartition.getValues()); if (this.skipDiffComputation) { onPartitionExistWithoutComputingDiff(table, nativePartition, null); } else { onPartitionExist(client, table, partition, nativePartition, existedPartition); } } } catch (NoSuchObjectException e) { try (Timer.Context context = this.metricContext.timer(ADD_PARTITION_TIMER).time()) { client.add_partition(getPartitionWithCreateTimeNow(nativePartition)); } catch (Throwable e2) { log.error(String.format( "Unable to add or alter partition %s in table %s with location %s: " + e2.getMessage(), stringifyPartitionVerbose(nativePartition), table.getTableName(), nativePartition.getSd().getLocation()), e2); throw e2; } log.info(String.format("Added partition %s to table %s with location %s", stringifyPartition(nativePartition), table.getTableName(), nativePartition.getSd().getLocation())); } } } private void onPartitionExist(IMetaStoreClient client, Table table, HivePartition partition, Partition nativePartition, Partition existedPartition) throws TException { HivePartition existingPartition; if(existedPartition == null) { try (Timer.Context context = this.metricContext.timer(GET_HIVE_PARTITION).time()) { existingPartition = HiveMetaStoreUtils.getHivePartition( client.getPartition(table.getDbName(), table.getTableName(), nativePartition.getValues())); } } else { existingPartition = HiveMetaStoreUtils.getHivePartition(existedPartition); } if (needToUpdatePartition(existingPartition, partition)) { log.info(String.format("Partition update required. ExistingPartition %s, newPartition %s", stringifyPartition(existingPartition), stringifyPartition(partition))); Partition newPartition = getPartitionWithCreateTime(nativePartition, existingPartition); log.info(String.format("Altering partition %s", newPartition)); try (Timer.Context context = this.metricContext.timer(ALTER_PARTITION).time()) { client.alter_partition(table.getDbName(), table.getTableName(), newPartition); } log.info(String.format("Updated partition %s in table %s with location %s", stringifyPartition(newPartition), table.getTableName(), nativePartition.getSd().getLocation())); } else { log.debug(String.format("Partition %s in table %s with location %s already exists and no need to update", stringifyPartition(nativePartition), table.getTableName(), nativePartition.getSd().getLocation())); } } private void onPartitionExistWithoutComputingDiff(Table table, Partition nativePartition, TException e) throws TException { if(e == null) { return; } if (e instanceof AlreadyExistsException) { log.debug(String.format("Partition %s in table %s with location %s already exists and no need to update", stringifyPartition(nativePartition), table.getTableName(), nativePartition.getSd().getLocation())); } else { throw e; } } private static String stringifyPartition(Partition partition) { if (log.isDebugEnabled()) { return stringifyPartitionVerbose(partition); } return Arrays.toString(partition.getValues().toArray()); } private static String stringifyPartition(HivePartition partition) { return partition.toString(); } private static String stringifyPartitionVerbose(Partition partition) { return partition.toString(); } @Override public Optional<HiveTable> getTable(String dbName, String tableName) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { Table hiveTable; try (Timer.Context context = this.metricContext.timer(GET_HIVE_TABLE).time()) { hiveTable = client.get().getTable(dbName, tableName); } return Optional.of(HiveMetaStoreUtils.getHiveTable(hiveTable)); } catch (NoSuchObjectException e) { return Optional.<HiveTable> absent(); } catch (TException e) { throw new IOException("Unable to get table " + tableName + " in db " + dbName, e); } } @Override public Optional<HivePartition> getPartition(String dbName, String tableName, List<Column> partitionKeys, List<String> partitionValues) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { Partition hivePartition; try (Timer.Context context = this.metricContext.timer(GET_HIVE_PARTITION).time()) { hivePartition = client.get().getPartition(dbName, tableName, partitionValues); } return Optional.of(HiveMetaStoreUtils.getHivePartition(hivePartition)); } catch (NoSuchObjectException e) { return Optional.<HivePartition> absent(); } catch (TException e) { throw new IOException( "Unable to get partition " + partitionValues + " from table " + tableName + " in db " + dbName, e); } } @Override public void alterTable(HiveTable table) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { Table existingTable; //During alter table we need to persist the existing property of iceberg in HMS try (Timer.Context context = this.metricContext.timer(GET_HIVE_TABLE).time()) { existingTable = client.get().getTable(table.getDbName(), table.getTableName()); } catch (Exception e){ throw new IOException("Cannot get table " + table.getTableName() + " in db " + table.getDbName(), e); } try (Timer.Context context = this.metricContext.timer(ALTER_TABLE).time()) { table.getProps().addAllIfNotExist(HiveMetaStoreUtils.getTableProps(existingTable)); client.get().alter_table(table.getDbName(), table.getTableName(), getTableWithCreateTimeNow(HiveMetaStoreUtils.getTable(table))); } HiveMetaStoreEventHelper.submitSuccessfulTableAlter(eventSubmitter, table); } catch (TException e) { HiveMetaStoreEventHelper.submitFailedTableAlter(eventSubmitter, table, e); throw new IOException("Unable to alter table " + table.getTableName() + " in db " + table.getDbName(), e); } } @Override public void alterPartition(HiveTable table, HivePartition partition) throws IOException { try (AutoReturnableObject<IMetaStoreClient> client = this.clientPool.getClient()) { try (Timer.Context context = this.metricContext.timer(ALTER_PARTITION).time()) { client.get().alter_partition(table.getDbName(), table.getTableName(), getPartitionWithCreateTimeNow(HiveMetaStoreUtils.getPartition(partition))); } HiveMetaStoreEventHelper.submitSuccessfulPartitionAlter(eventSubmitter, table, partition); } catch (TException e) { HiveMetaStoreEventHelper.submitFailedPartitionAlter(eventSubmitter, table, partition, e); throw new IOException(String.format("Unable to alter partition %s in table %s in db %s", partition.getValues(), table.getTableName(), table.getDbName()), e); } } private Partition getPartitionWithCreateTimeNow(Partition partition) { return getPartitionWithCreateTime(partition, Ints.checkedCast(DateTime.now().getMillis() / 1000)); } private Partition getPartitionWithCreateTime(Partition partition, HivePartition referencePartition) { return getPartitionWithCreateTime(partition, Ints.checkedCast(referencePartition.getCreateTime().or(DateTime.now().getMillis() / 1000))); } /** * Sets create time if not already set. */ private Partition getPartitionWithCreateTime(Partition partition, int createTime) { if (partition.isSetCreateTime() && partition.getCreateTime() > 0) { return partition; } Partition actualPartition = partition.deepCopy(); actualPartition.setCreateTime(createTime); return actualPartition; } private Table getTableWithCreateTimeNow(Table table) { return gettableWithCreateTime(table, Ints.checkedCast(DateTime.now().getMillis() / 1000)); } private Table getTableWithCreateTime(Table table, HiveTable referenceTable) { return gettableWithCreateTime(table, Ints.checkedCast(referenceTable.getCreateTime().or(DateTime.now().getMillis() / 1000))); } /** * Sets create time if not already set. */ private Table gettableWithCreateTime(Table table, int createTime) { if (table.isSetCreateTime() && table.getCreateTime() > 0) { return table; } Table actualtable = table.deepCopy(); actualtable.setCreateTime(createTime); return actualtable; } /** * Used to merge properties from existingTable to newTable. * e.g. New table will inherit creation time from existing table. * * This method is extensible for customized logic in merging table properties. * @param newTable * @param existingTable */ protected Table getNewTblByMergingExistingTblProps(Table newTable, HiveTable existingTable) { Table table = getTableWithCreateTime(newTable, existingTable); // Get existing parameters Map<String, String> allParameters = HiveMetaStoreUtils.getParameters(existingTable.getProps()); // Apply new parameters allParameters.putAll(table.getParameters()); table.setParameters(allParameters); return table; } }
package sk.kottman.androlua; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import org.keplerproject.luajava.*; public class LuaActivity extends Activity implements ServiceConnection { Lua service; String modName = null; LuaObject modTable; int argRef = 0; Bundle state; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); state = savedInstanceState; Intent intent = getIntent(); modName = intent.getStringExtra("LUA_MODULE"); argRef = intent.getIntExtra("LUA_MODULE_ARG", 0); Lua.bind(this, this); } protected void setLuaModule(CharSequence mod) { getIntent().putExtra("LUA_MODULE", mod); } @Override protected void onActivityResult(int request, int result, Intent data) { service.invokeMethod(modTable,"onActivityResult",request,result,data); } @Override public void onPause() { super.onPause(); service.invokeMethod(modTable,"onPause"); } @Override public void onResume() { super.onResume(); if (service != null) service.invokeMethod(modTable,"onResume"); } @Override public void onStart() { super.onStart(); if (service != null) service.invokeMethod(modTable,"onStart"); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (service != null) service.invokeMethod(modTable, "onSaveInstanceState", outState); } @Override public void onRestoreInstanceState(Bundle savedState) { } @Override public void onStop() { super.onStop(); service.invokeMethod(modTable,"onStop"); } @Override public void onDestroy() { super.onDestroy(); service.invokeMethod(modTable,"onDestroy"); Lua.unbind(this,this); } @Override public boolean onCreateOptionsMenu(Menu menu) { Object res = service.invokeMethod(modTable, "onCreateOptionsMenu", menu); return res != null ? (Boolean)res : false; } @Override public boolean onOptionsItemSelected(MenuItem item) { Object res = service.invokeMethod(modTable, "onOptionsItemSelected", item); if (res == null) { return super.onOptionsItemSelected(item); } else { return true; } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); service.invokeMethod(modTable, "onCreateContextMenu", menu,v,menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { Object res = service.invokeMethod(modTable, "onContextItemSelected", item); if (res != null) { return super.onContextItemSelected(item); } else { return true; } } public void log(String msg) { Lua.log(msg); } public void onServiceConnected(ComponentName name, IBinder iservice) { Log.d("lua","setting activity"); service = ((Lua.LocalBinder)iservice).getService(); modTable = service.require(modName); if (modTable == null) { finish(); return; } service.setGlobal("current_activity",this); Object res; Object arg = null; if (argRef != 0) { arg = LuaObject.fromReference(Lua.L,argRef); } try { if (modTable.isFunction()) { res = modTable.call(new Object[]{this,arg,state}); modTable = null; } else { res = service.invokeMethod(modTable,"onCreate",this,arg,state); } } catch (LuaException e) { log("onCreate "+e.getMessage()); res = null; } if (res == null) { finish(); return; } if (res instanceof View) { setContentView((View)res); } else if (! (res instanceof Boolean)){ log("onCreate must return a View"); finish(); return; } service.invokeMethod(modTable,"onStart"); if (state != null) { super.onRestoreInstanceState(state); } service.invokeMethod(modTable,"onResume"); } public void onServiceDisconnected(ComponentName name) { // Really should not be called! this.service = null; } }
package org.acme.util.adapter.rest; import javax.ws.rs.core.Link; import javax.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.List; public interface Links { String NEXT = "next"; String PREV = "prev"; String SELF = "self"; String OFFSET = "offset"; String LIMIT = "limit"; static Link getSelfLink(UriInfo uriInfo) { final var uri = uriInfo.getAbsolutePath(); return Link.fromUri(uri).rel(SELF).build(); } static Link[] getPaginationLinks(Range range, int count, UriInfo uriInfo) { int offset = range.getOffset(); int limit = range.getLimit(); final List<Link> links = new ArrayList<>(); if (limit <= count) { final var next = uriInfo.getAbsolutePathBuilder() .queryParam(OFFSET, offset + limit) .queryParam(LIMIT, limit).build(); links.add(Link.fromUri(next).rel(NEXT).build()); } if (offset > 0) { final var prev = uriInfo.getAbsolutePathBuilder() .queryParam(OFFSET, Integer.max(offset - limit, 0)) .queryParam(LIMIT, limit).build(); links.add(Link.fromUri(prev).rel(PREV).build()); } return links.toArray(new Link[0]); } }
package org.apache.solr.util; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.lucene.util.IOUtils; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.util.StrUtils; import org.noggit.JSONParser; import org.noggit.ObjectBuilder; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.apache.solr.common.cloud.ZkNodeProps.makeMap; public class CommandOperation { public final String name; private Object commandData;//this is most often a map private List<String> errors = new ArrayList<>(); CommandOperation(String operationName, Object metaData) { commandData = metaData; this.name = operationName; } public String getStr(String key, String def) { if (ROOT_OBJ.equals(key)) { Object obj = getRootPrimitive(); return obj == def ? null : String.valueOf(obj); } Object o = getMapVal(key); return o == null ? def : String.valueOf(o); } public Map<String,Object> getDataMap() { if (commandData instanceof Map) { //noinspection unchecked return (Map<String,Object>)commandData; } addError(StrUtils.formatString("The command ''{0}'' should have the values as a json object {key:val} format", name)); return Collections.emptyMap(); } private Object getRootPrimitive() { if (commandData instanceof Map) { errors.add(StrUtils.formatString("The value has to be a string for command : ''{0}'' ", name)); return null; } return commandData; } public Object getVal(String key) { return getMapVal(key); } private Object getMapVal(String key) { if (commandData instanceof Map) { Map metaData = (Map) commandData; return metaData.get(key); } else { String msg = " value has to be an object for operation :" + name; if (!errors.contains(msg)) errors.add(msg); return null; } } public List<String> getStrs(String key) { List<String> val = getStrs(key, null); if (val == null) { errors.add(StrUtils.formatString(REQD, key)); } return val; } static final String REQD = "''{0}'' is a required field"; /** * Get collection of values for a key. If only one val is present a * single value collection is returned */ public List<String> getStrs(String key, List<String> def) { Object v = null; if (ROOT_OBJ.equals(key)) { v = getRootPrimitive(); } else { v = getMapVal(key); } if (v == null) { return def; } else { if (v instanceof List) { ArrayList<String> l = new ArrayList<>(); for (Object o : (List) v) { l.add(String.valueOf(o)); } if (l.isEmpty()) return def; return l; } else { return singletonList(String.valueOf(v)); } } } /** * Get a required field. If missing it adds to the errors */ public String getStr(String key) { if (ROOT_OBJ.equals(key)) { Object obj = getRootPrimitive(); if (obj == null) { errors.add(StrUtils.formatString(REQD, name)); } return obj == null ? null : String.valueOf(obj); } String s = getStr(key, null); if (s == null) errors.add(StrUtils.formatString(REQD, key)); return s; } private Map errorDetails() { return makeMap(name, commandData, ERR_MSGS, errors); } public boolean hasError() { return !errors.isEmpty(); } public void addError(String s) { if (errors.contains(s)) return; errors.add(s); } /** * Get all the values from the metadata for the command * without the specified keys */ public Map<String,Object> getValuesExcluding(String... keys) { getMapVal(null); if (hasError()) return emptyMap();//just to verify the type is Map @SuppressWarnings("unchecked") LinkedHashMap<String,Object> cp = new LinkedHashMap<>((Map<String,Object>)commandData); if (keys == null) return cp; for (String key : keys) { cp.remove(key); } return cp; } public List<String> getErrors() { return errors; } public static final String ERR_MSGS = "errorMessages"; public static final String ROOT_OBJ = ""; public static List<Map> captureErrors(List<CommandOperation> ops) { List<Map> errors = new ArrayList<>(); for (CommandOperation op : ops) { if (op.hasError()) { errors.add(op.errorDetails()); } } return errors; } /** * Parse the command operations into command objects */ public static List<CommandOperation> parse(Reader rdr) throws IOException { JSONParser parser = new JSONParser(rdr); ObjectBuilder ob = new ObjectBuilder(parser); if (parser.lastEvent() != JSONParser.OBJECT_START) { throw new RuntimeException("The JSON must be an Object of the form {\"command\": {...},..."); } List<CommandOperation> operations = new ArrayList<>(); for (; ; ) { int ev = parser.nextEvent(); if (ev == JSONParser.OBJECT_END) return operations; Object key = ob.getKey(); ev = parser.nextEvent(); Object val = ob.getVal(); if (val instanceof List) { List list = (List) val; for (Object o : list) { operations.add(new CommandOperation(String.valueOf(key), o)); } } else { operations.add(new CommandOperation(String.valueOf(key), val)); } } } public CommandOperation getCopy() { return new CommandOperation(name, commandData); } public Map getMap(String key, Map def) { Object o = getMapVal(key); if (o == null) return def; if (!(o instanceof Map)) { addError(StrUtils.formatString("''{0}'' must be a map", key)); return def; } else { return (Map) o; } } @Override public String toString() { try { return new String(ZkStateReader.toJSON(singletonMap(name, commandData)), IOUtils.UTF_8); } catch (UnsupportedEncodingException e) { //should not happen return ""; } } }
package com.kintone.client.model.space; import com.kintone.client.model.User; import java.time.ZonedDateTime; import lombok.Value; /** An object contains information of an App in a Space. */ @Value public class AttachedApp { /** The App ID. */ private final long appId; /** The App Code of the App. */ private final String code; /** The name of the App. */ private final String name; /** The description of the App. */ private final String description; /** The Thread ID of the thread that the App was created in. */ private final long threadId; /** The date of when the App was created. */ private final ZonedDateTime createdAt; /** The information of the user who created the App. */ private final User creator; /** The date of when the App was last updated. */ private final ZonedDateTime modifiedAt; /** The information of the user who last updated the App. */ private final User modifier; }
package initialization; import caller.Trainmaster; import initialization.Server; import initialization.Work; import java.util.ArrayDeque; public class GrrProgrammer extends initialization.Server { static final String kg = "ikvpk"; private java.util.ArrayDeque<GrrProcedure> ripeStandby; private int monthAdditional; private initialization.GrrProcedure grrProcedure; public GrrProgrammer() { this.ripeStandby = new java.util.ArrayDeque<>(); monthAdditional = Server.MomentAmounts; } public synchronized String plannerNominate() { double amoy = 0.006680420963777967; return "NRR:"; } public synchronized void snoTicktock() { String modicum = "mGkuIc"; if (grrProcedure != null) { grrProcedure.dictatedTrackMeter(grrProcedure.makeFlyingDay() + 1); monthAdditional--; if (grrProcedure.makeFlyingDay() == grrProcedure.obtainTimeoutLength()) { grrProcedure.fixedEscapeOpportunity(this.goPrevailingClick()); this.finalizingSystems.addLast(grrProcedure); grrProcedure = null; this.variWaving = true; } if (monthAdditional == 0 && grrProcedure != null) { if (ripeStandby.isEmpty()) { monthAdditional = grrProcedure.receiveMomentAmounts(); } else { if (grrProcedure.receiveMomentAmounts() > 2) { grrProcedure.putClockAmount(grrProcedure.receiveMomentAmounts() - 1); } ripeStandby.addLast(grrProcedure); grrProcedure = null; this.variWaving = true; } } } if (this.variWaving && prevailingProcedure == null) { this.otherDblClip--; if (otherDblClip == 0) { this.variWaving = false; this.otherDblClip = Trainmaster.OfficeJuncture; } } else { if (grrProcedure == null && !ripeStandby.isEmpty()) { grrProcedure = ripeStandby.removeFirst(); onusServe(grrProcedure); grrProcedure.readyOutsetDay(this.goPrevailingClick()); monthAdditional = grrProcedure.receiveMomentAmounts(); } } } public synchronized void treatInfluent(Work method) { double rely = 0.4147626509842125; ripeStandby.add(new initialization.GrrProcedure(method)); } }
/* * Copyright (c) 2020, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ /** * The XML Binding implementation. * * @uses jakarta.xml.bind.JAXBContextFactory * */ module cn.glassfish.jaxb.core { requires transitive jakarta.xml.bind; requires java.compiler; requires java.desktop; requires java.logging; requires transitive jakarta.activation; requires transitive java.xml; requires transitive com.sun.xml.txw2; requires transitive com.sun.istack.runtime; exports cn.glassfish.jaxb.core; exports cn.glassfish.jaxb.core.annotation; exports cn.glassfish.jaxb.core.api; exports cn.glassfish.jaxb.core.api.impl; exports cn.glassfish.jaxb.core.marshaller; exports cn.glassfish.jaxb.core.unmarshaller; exports cn.glassfish.jaxb.core.util; exports cn.glassfish.jaxb.core.v2; exports cn.glassfish.jaxb.core.v2.model.annotation; exports cn.glassfish.jaxb.core.v2.model.core; exports cn.glassfish.jaxb.core.v2.model.impl; exports cn.glassfish.jaxb.core.v2.model.nav; exports cn.glassfish.jaxb.core.v2.model.util; exports cn.glassfish.jaxb.core.v2.runtime; exports cn.glassfish.jaxb.core.v2.runtime.unmarshaller; exports cn.glassfish.jaxb.core.v2.schemagen.episode; exports cn.glassfish.jaxb.core.v2.util; opens cn.glassfish.jaxb.core.v2.model.nav to cn.glassfish.jaxb.runtime, cn.glassfish.jaxb.xjc, com.sun.xml.ws.rt, com.sun.tools.ws.wscompile; }
/* * Copyright 2006-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.springframework.security.oauth2.provider.expression; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException; /** * A convenience object for security expressions in OAuth2 protected resources, providing public methods that act on the * current authentication. * * @author Dave Syer * @author Rob Winch * @author Radek Ostrowski * */ public class OAuth2SecurityExpressionMethods { private final Authentication authentication; private Set<String> missingScopes = new LinkedHashSet<String>(); public OAuth2SecurityExpressionMethods(Authentication authentication) { this.authentication = authentication; } /** * Check if any scope decisions have been denied in the current context and throw an exception if so. This method * automatically wraps any expressions when using {@link OAuth2MethodSecurityExpressionHandler} or * {@link OAuth2WebSecurityExpressionHandler}. * * OAuth2Example usage: * * <pre> * access = &quot;#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))&quot; * </pre> * * Will automatically be wrapped to ensure that explicit errors are propagated rather than a generic error when * returning false: * * <pre> * access = &quot;#oauth2.throwOnError(#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))&quot; * </pre> * * N.B. normally this method will be automatically wrapped around all your access expressions. You could use it * explicitly to get more control, or if you have registered your own <code>ExpressionParser</code> you might need * it. * * @param decision the existing access decision * @return true if the OAuth2 token has one of these scopes * @throws InsufficientScopeException if the scope is invalid and we the flag is set to throw the exception */ public boolean throwOnError(boolean decision) { if (!decision && !missingScopes.isEmpty()) { Throwable failure = new InsufficientScopeException("Insufficient scope for this resource", missingScopes); throw new AccessDeniedException(failure.getMessage(), failure); } return decision; } /** * Check if the OAuth2 client (not the user) has the role specified. To check the user's roles see * {@link #hasRole(String)}. * * @param role the role to check * @return true if the OAuth2 client has this role */ public boolean clientHasRole(String role) { return clientHasAnyRole(role); } /** * Check if the OAuth2 client (not the user) has one of the roles specified. To check the user's roles see * {@link #hasAnyRole(String)}. * * @param roles the roles to check * @return true if the OAuth2 client has one of these roles */ public boolean clientHasAnyRole(String... roles) { return OAuth2ExpressionUtils.clientHasAnyRole(authentication, roles); } /** * Check if the current OAuth2 authentication has one of the scopes specified. * * @param scope the scope to check * @return true if the OAuth2 authentication has the required scope */ public boolean hasScope(String scope) { return hasAnyScope(scope); } /** * Check if the current OAuth2 authentication has one of the scopes specified. * * @param roles the scopes to check * @return true if the OAuth2 token has one of these scopes * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception */ public boolean hasAnyScope(String... scopes) { boolean result = OAuth2ExpressionUtils.hasAnyScope(authentication, scopes); if (!result) { missingScopes.addAll(Arrays.asList(scopes)); } return result; } /** * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression. * * <pre> * access = &quot;#oauth2.hasScopeMatching('.*_admin:manage_scopes')))&quot; * </pre> * * @param scopeRegex the scope regex to match * @return true if the OAuth2 authentication has the required scope */ public boolean hasScopeMatching(String scopeRegex) { return hasAnyScopeMatching(scopeRegex); } /** * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression. * * <pre> * access = &quot;#oauth2.hasAnyScopeMatching('admin:manage_scopes','.*_admin:manage_scopes','.*_admin:read_scopes')))&quot; * </pre> * * @param roles the scopes regex to match * @return true if the OAuth2 token has one of these scopes * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception */ public boolean hasAnyScopeMatching(String... scopesRegex) { boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex); if (!result) { missingScopes.addAll(Arrays.asList(scopesRegex)); } return result; } /** * Deny access to oauth requests, so used for example to only allow web UI users to access a resource. * * @return true if the current authentication is not an OAuth2 type */ public boolean denyOAuthClient() { return !OAuth2ExpressionUtils.isOAuth(authentication); } /** * Permit access to oauth requests, so used for example to only allow machine clients to access a resource. * * @return true if the current authentication is not an OAuth2 type */ public boolean isOAuth() { return OAuth2ExpressionUtils.isOAuth(authentication); } /** * Check if the current authentication is acting on behalf of an authenticated user. * * @return true if the current authentication represents a user */ public boolean isUser() { return OAuth2ExpressionUtils.isOAuthUserAuth(authentication); } /** * Check if the current authentication is acting as an authenticated client application not on behalf of a user. * * @return true if the current authentication represents a client application */ public boolean isClient() { return OAuth2ExpressionUtils.isOAuthClientAuth(authentication); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.cloud.config; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.endpoint.RefreshEndpoint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import com.azure.spring.cloud.config.health.AppConfigurationHealthIndicator; import com.azure.spring.cloud.config.properties.AppConfigurationProperties; import com.azure.spring.cloud.config.stores.ClientStore; /** * Setup AppConfigurationRefresh when <i>spring.cloud.azure.appconfiguration.enabled</i> is enabled. */ @Configuration @EnableAsync @ConditionalOnProperty(prefix = AppConfigurationProperties.CONFIG_PREFIX, name = "enabled", matchIfMissing = true) public class AppConfigurationAutoConfiguration { @Configuration @ConditionalOnClass(RefreshEndpoint.class) static class AppConfigurationWatchAutoConfiguration { @Bean public AppConfigurationRefresh getConfigWatch(AppConfigurationProperties properties, ClientStore clientStore) { return new AppConfigurationRefresh(properties, clientStore); } } /** * Health Indicator for Azure App Configuration store connections. */ @Configuration @ConditionalOnClass({ HealthIndicator.class }) @ConditionalOnEnabledHealthIndicator("azure-app-configuration") static class AppConfigurationtHealthConfiguration { @Bean @ConditionalOnBean AppConfigurationHealthIndicator appConfigurationHealthIndicator(AppConfigurationRefresh refresh) { return new AppConfigurationHealthIndicator(refresh); } } }
package com.armadialogcreator.expression; import com.armadialogcreator.lang.Lang; import com.armadialogcreator.util.ADCExecutors; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.IntervalSet; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; /** Evaluates simple mathematical expressions and some things of Arma 3's scripting language SQF. Order of operations is supported as well as identifier lookup.<br> All evaluations are done inside a thread pool and in new evaluators. @author Kayler @since 07/14/2016. */ public class ExpressionInterpreter { private static final String[] supportedCommands = new String[]{ "min", "max", "if", "then", "exitWith", "do", "true", "false", "select", "for", "from", "to", "step", "count", "str", "safeZoneX", "safeZoneY", "safeZoneW", "safeZoneH", "safeZoneXAbs", "safeZoneWAbs", "getResolution", "not", "or", "and", "abs", "format" }; static { Arrays.sort(supportedCommands); } /** Will return an array of all supported commands. This array is used to make sure the user isn't assigning values to these commands through {@link Env#put(String, Value)}. */ @NotNull public static String[] getSupportedCommands() { return supportedCommands; } /** Get a new instance of the interpreter */ @NotNull public static ExpressionInterpreter newInstance() { return new ExpressionInterpreter(); } /** Thread pool with all executing evaluators */ private final ExecutorService threadPool = Executors.newFixedThreadPool(2); /** Queue of all running/queued {@link ExpressionEvaluator} instances */ private final LinkedBlockingQueue<ExpressionEvaluator> evaluatorsQ = new LinkedBlockingQueue<>(); public ExpressionInterpreter() { ADCExecutors.registerExecutorService(threadPool); } /** Shutdown this interpreter and prevent reuse. Be sure to shutdown interpreters that aren't being used anymore! If you don't, the application will take serious performance hits over time. This method will also invoke {@link #terminateAll()} */ public synchronized void shutdownAndDisable() { terminateAll(); threadPool.shutdownNow(); } /** Terminate all running evaluators for this interpreter. This method is thread-safe. <br> For each evaluator: <ul> <li>If the evaluator is running and this is invoked, the {@link FutureEvaluatedValue#get()} method will throw a {@link TerminateEvaluationException}.</li> <li>If the evaluator is no longer running, nothing will happen.</li> </ul> */ public synchronized void terminateAll() { //keep this method synchronized so that evaluate() and evaluateStatements() //can't run at the same time as this method for (ExpressionEvaluator evaluator : evaluatorsQ) { evaluator.terminate(); } evaluatorsQ.clear(); } /** Evaluate the given expression String in the given environment. This method will create a new evaluator. This method will throw errors if the given string contains assignments or multiple expressions separated by semicolons.<br><br> This method is a non-blocking method and is executed on the interpreter's thread pool. @param exp expression text to evaluate @param env environment that holds information on all identifiers. Please consider thread safety of this environment as the evaluation will run on a different thread @return a {@link Future} class that contains the resulted {@link Value} instance */ @NotNull public synchronized FutureEvaluatedValue evaluate(@Nullable String exp, @NotNull Env env) { //this method is synchronized so that no new evaluators can be created if terminateAll() is invoked if (threadPool.isShutdown()) { throw new IllegalStateException("can't use a shutdown interpreter"); } ExpressionEvaluator evaluator = new ExpressionEvaluator(); evaluatorsQ.add(evaluator); Future<Value> future = threadPool.submit(new Callable<Value>() { @Override public Value call() throws Exception { if (exp == null || exp.trim().length() == 0) { throw new ExpressionEvaluationException(null, Lang.ApplicationBundle().getString("Expression.error_no_input")); } ExpressionLexer l = getLexer(exp); ExpressionParser p = getParser(new CommonTokenStream(l)); //prevent ANTLR printing to the console when the expression is invalid l.getErrorListeners().clear(); p.getErrorListeners().clear(); p.addErrorListener(ErrorListener.INSTANCE); p.setErrorHandler(ErrorStrategy.INSTANCE); l.addErrorListener(ErrorListener.INSTANCE); AST.Expr e; try { e = p.expression().ast; } catch (Exception ex) { if (ex instanceof ExpressionEvaluationException) { throw ex; } throw new ExpressionEvaluationException(null, ex.getMessage(), ex); } Value v = evaluator.evaluate(e, env); evaluatorsQ.remove(evaluator); return v; } }); return new FutureEvaluatedValue(this, evaluator, future); } /** Evaluate the given statements as a String in the given environment. This method will create a new evaluator.<br><br> This method is a blocking method. @param statements statements text to evaluate @param env environment that holds information on all identifiers. Please consider thread safety of this environment as the evaluation will run on a different thread @return a {@link Future} like class that contains the resulted {@link Value} instance from the last {@link AST.Statement} {@link #terminateAll()} or {@link FutureEvaluatedValue#cancel(boolean)} */ @NotNull public synchronized FutureEvaluatedValue evaluateStatements(@Nullable String statements, @NotNull Env env) { //this method is synchronized so that no new evaluators can be created if terminateAll() is invoked if (threadPool.isShutdown()) { throw new IllegalStateException("can't use a shutdown interpreter"); } ExpressionEvaluator evaluator = new ExpressionEvaluator(); evaluatorsQ.add(evaluator); Future<Value> future = threadPool.submit(new Callable<Value>() { @Override public Value call() throws Exception { if (statements == null || statements.trim().length() == 0) { throw new ExpressionEvaluationException(null, Lang.ApplicationBundle().getString("Expression.error_no_input")); } ExpressionLexer l = getLexer(statements); ExpressionParser p = getParser(new CommonTokenStream(l)); //prevent ANTLR printing to the console when the expression is invalid l.getErrorListeners().clear(); p.getErrorListeners().clear(); p.addErrorListener(ErrorListener.INSTANCE); p.setErrorHandler(ErrorStrategy.INSTANCE); l.addErrorListener(ErrorListener.INSTANCE); try { List<AST.Statement> statementList = p.statements().lst; Value v = evaluateStatements(statementList, env, evaluator); evaluatorsQ.remove(evaluator); return v; } catch (Exception e) { if (e instanceof ExpressionEvaluationException) { throw e; } throw new ExpressionEvaluationException(null, e.getMessage(), e); } } }); return new FutureEvaluatedValue(this, evaluator, future); } /** Evaluate the given statements as a list of {@link AST.Statement} in the given environment.<br> This will not be executed on a new thread and thus will be a blocking call. @param statements statements to evaluate @param env environment that holds information on all identifiers @param evaluator the {@link ExpressionEvaluator} instance to use. @return resulted {@link Value} instance from the last {@link AST.Statement} @throws ExpressionEvaluationException if the expression couldn't be evaluated */ @NotNull protected Value evaluateStatements(@NotNull List<AST.Statement> statements, @NotNull Env env, @NotNull ExpressionEvaluator evaluator) { try { return evaluator.evaluate(statements, env); } catch (Exception ex) { if (ex instanceof ExpressionEvaluationException) { throw ex; } throw new ExpressionEvaluationException(null, ex.getMessage(), ex); } } @NotNull private ExpressionParser getParser(CommonTokenStream stream) { return new ExpressionParser(stream); } @NotNull private ExpressionLexer getLexer(String s) { return new ExpressionLexer(new ANTLRInputStream(s)); } private static class ErrorStrategy extends DefaultErrorStrategy { public static final ANTLRErrorStrategy INSTANCE = new ErrorStrategy(); @Override public void recover(Parser recognizer, RecognitionException e) { throw e; } @Override public void reportInputMismatch(Parser recognizer, InputMismatchException e) throws RecognitionException { String msg = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()); msg += " expecting one of " + e.getExpectedTokens().toString(recognizer.getTokenNames()); RecognitionException ex = new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext()); ex.initCause(e); throw ex; } @Override public void reportMissingToken(Parser recognizer) { beginErrorCondition(recognizer); Token t = recognizer.getCurrentToken(); IntervalSet expecting = getExpectedTokens(recognizer); String msg = "missing " + expecting.toString(recognizer.getTokenNames()) + " at " + getTokenErrorDisplay(t); throw new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext()); } } private static class ErrorListener extends BaseErrorListener { public static final ErrorListener INSTANCE = new ErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg); } } }
/* * Copyright 2014-2022 TNG Technology Consulting GmbH * * 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.tngtech.archunit; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.function.Supplier; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMap; import com.tngtech.archunit.base.Suppliers; import com.tngtech.archunit.core.importer.resolvers.ClassResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkNotNull; import static com.tngtech.archunit.PublicAPI.Usage.ACCESS; import static com.tngtech.archunit.base.ClassLoaders.getCurrentClassLoader; /** * Allows access to configured properties in {@value ARCHUNIT_PROPERTIES_RESOURCE_NAME}. */ public final class ArchConfiguration { @Internal // {@value ...} does not work on non public constants outside of the package public static final String ARCHUNIT_PROPERTIES_RESOURCE_NAME = "archunit.properties"; @Internal // {@value ...} does not work on non public constants outside of the package public static final String RESOLVE_MISSING_DEPENDENCIES_FROM_CLASS_PATH = "resolveMissingDependenciesFromClassPath"; static final String CLASS_RESOLVER = "classResolver"; static final String CLASS_RESOLVER_ARGS = "classResolver.args"; @Internal public static final String ENABLE_MD5_IN_CLASS_SOURCES = "enableMd5InClassSources"; private static final String EXTENSION_PREFIX = "extension"; private static final Logger LOG = LoggerFactory.getLogger(ArchConfiguration.class); private static final Supplier<ArchConfiguration> INSTANCE = Suppliers.memoize(ArchConfiguration::new); @PublicAPI(usage = ACCESS) public static ArchConfiguration get() { return INSTANCE.get(); } private final String propertiesResourceName; private final PropertiesOverwritableBySystemProperties properties = new PropertiesOverwritableBySystemProperties(); private ArchConfiguration() { this(ARCHUNIT_PROPERTIES_RESOURCE_NAME); } private ArchConfiguration(String propertiesResourceName) { this.propertiesResourceName = propertiesResourceName; readProperties(propertiesResourceName); } private void readProperties(String propertiesResourceName) { properties.clear(); URL archUnitPropertiesUrl = getCurrentClassLoader(getClass()).getResource(propertiesResourceName); if (archUnitPropertiesUrl == null) { LOG.debug("No configuration found in classpath at {} => Using default configuration", propertiesResourceName); return; } try (InputStream inputStream = archUnitPropertiesUrl.openStream()) { LOG.info("Reading ArchUnit properties from {}", archUnitPropertiesUrl); properties.load(inputStream); } catch (IOException e) { LOG.warn("Error reading ArchUnit properties from " + archUnitPropertiesUrl, e); } } @PublicAPI(usage = ACCESS) public void reset() { readProperties(propertiesResourceName); } @PublicAPI(usage = ACCESS) public boolean resolveMissingDependenciesFromClassPath() { return Boolean.parseBoolean(properties.getProperty(RESOLVE_MISSING_DEPENDENCIES_FROM_CLASS_PATH)); } @PublicAPI(usage = ACCESS) public void setResolveMissingDependenciesFromClassPath(boolean newValue) { properties.setProperty(RESOLVE_MISSING_DEPENDENCIES_FROM_CLASS_PATH, String.valueOf(newValue)); } @PublicAPI(usage = ACCESS) public boolean md5InClassSourcesEnabled() { return Boolean.parseBoolean(properties.getProperty(ENABLE_MD5_IN_CLASS_SOURCES)); } @PublicAPI(usage = ACCESS) public void setMd5InClassSourcesEnabled(boolean enabled) { properties.setProperty(ENABLE_MD5_IN_CLASS_SOURCES, String.valueOf(enabled)); } @PublicAPI(usage = ACCESS) public Optional<String> getClassResolver() { return Optional.ofNullable(properties.getProperty(CLASS_RESOLVER)); } @PublicAPI(usage = ACCESS) public void setClassResolver(Class<? extends ClassResolver> classResolver) { properties.setProperty(CLASS_RESOLVER, classResolver.getName()); } @PublicAPI(usage = ACCESS) public void unsetClassResolver() { properties.remove(CLASS_RESOLVER); } @PublicAPI(usage = ACCESS) public List<String> getClassResolverArguments() { return Splitter.on(",").trimResults().omitEmptyStrings() .splitToList(properties.getProperty(CLASS_RESOLVER_ARGS, "")); } @PublicAPI(usage = ACCESS) public void setClassResolverArguments(String... args) { properties.setProperty(CLASS_RESOLVER_ARGS, Joiner.on(",").join(args)); } @PublicAPI(usage = ACCESS) public void setExtensionProperties(String extensionIdentifier, Properties properties) { String propertyPrefix = getFullExtensionPropertyPrefix(extensionIdentifier); clearPropertiesWithPrefix(propertyPrefix); for (String propertyName : properties.stringPropertyNames()) { String fullPropertyName = propertyPrefix + "." + propertyName; this.properties.setProperty(fullPropertyName, properties.getProperty(propertyName)); } } private void clearPropertiesWithPrefix(String propertyPrefix) { for (String propertyToRemove : filterNamesWithPrefix(properties.stringPropertyNames(), propertyPrefix)) { properties.remove(propertyToRemove); } } @PublicAPI(usage = ACCESS) public Properties getExtensionProperties(String extensionIdentifier) { String propertyPrefix = getFullExtensionPropertyPrefix(extensionIdentifier); return getSubProperties(propertyPrefix); } private String getFullExtensionPropertyPrefix(String extensionIdentifier) { return EXTENSION_PREFIX + "." + extensionIdentifier; } @PublicAPI(usage = ACCESS) public ExtensionProperties configureExtension(String extensionIdentifier) { return new ExtensionProperties(extensionIdentifier); } /** * Returns a set of properties where all keys share a common prefix. The prefix is removed from those property names. Example: * <pre><code> * some.custom.prop1=value1 * some.custom.prop2=value2 * unrelated=irrelevant</code></pre> * Then {@code getSubProperties("some.custom")} would return the properties * <pre><code> * prop1=value1 * prop2=value2</code></pre> * * @param propertyPrefix A prefix for a set of properties * @return All properties with this prefix, where the prefix is removed from the keys. */ @PublicAPI(usage = ACCESS) public Properties getSubProperties(String propertyPrefix) { return getSubProperties(propertyPrefix, properties.getMergedProperties()); } private static Properties getSubProperties(String propertyPrefix, Properties properties) { Properties result = new Properties(); for (String key : filterNamesWithPrefix(properties.stringPropertyNames(), propertyPrefix)) { String extensionPropertyKey = removePrefix(key, propertyPrefix); result.put(extensionPropertyKey, properties.getProperty(key)); } return result; } private static Iterable<String> filterNamesWithPrefix(Iterable<String> propertyNames, String prefix) { List<String> result = new ArrayList<>(); String fullPrefix = prefix + "."; for (String propertyName : propertyNames) { if (propertyName.startsWith(fullPrefix)) { result.add(propertyName); } } return result; } private static String removePrefix(String string, String prefix) { return string.substring(prefix.length() + 1); } /** * @param propertyName Full name of a property * @return true, if and only if the property is configured within the global ArchUnit configuration. * @see #getProperty(String) * @see #setProperty(String, String) */ @PublicAPI(usage = ACCESS) public boolean containsProperty(String propertyName) { return properties.containsKey(propertyName); } /** * @param propertyName Full name of a property * @return A property of the global ArchUnit configuration. This method will throw an exception if the property is not set within the configuration. * @see #containsProperty(String) * @see #setProperty(String, String) */ @PublicAPI(usage = ACCESS) public String getProperty(String propertyName) { return checkNotNull(properties.getProperty(propertyName), "Property '%s' is not configured", propertyName); } /** * Overwrites a property of the global ArchUnit configuration. Note that this change will persist for the whole life time of this JVM * unless overwritten another time. * * @param propertyName Full name of a property * @param value The new value to set. Overwrites any existing property with the same name. * @see #containsProperty(String) * @see #getProperty(String) */ @PublicAPI(usage = ACCESS) public void setProperty(String propertyName, String value) { properties.setProperty(propertyName, value); } /** * @param propertyName Full name of a property * @param defaultValue A value to return if property is not configured * @return The property of the global ArchUnit configuration with the supplied name * or {@code defaultValue} if this property is not configured. */ @PublicAPI(usage = ACCESS) public String getPropertyOrDefault(String propertyName, String defaultValue) { return properties.getProperty(propertyName, defaultValue); } private static class PropertiesOverwritableBySystemProperties { private static final Properties PROPERTY_DEFAULTS = createProperties(ImmutableMap.of( RESOLVE_MISSING_DEPENDENCIES_FROM_CLASS_PATH, Boolean.TRUE.toString(), ENABLE_MD5_IN_CLASS_SOURCES, Boolean.FALSE.toString() )); private final Properties baseProperties = createProperties(PROPERTY_DEFAULTS); private final Properties overwrittenProperties = new Properties(); void clear() { replaceProperties(baseProperties, PROPERTY_DEFAULTS); overwrittenProperties.clear(); } void load(InputStream inputStream) throws IOException { baseProperties.load(inputStream); } Set<String> stringPropertyNames() { return getMergedProperties().stringPropertyNames(); } boolean containsKey(String propertyName) { return getMergedProperties().containsKey(propertyName); } String getProperty(String propertyName) { return getMergedProperties().getProperty(propertyName); } String getProperty(String propertyName, String defaultValue) { return getMergedProperties().getProperty(propertyName, defaultValue); } void setProperty(String propertyName, String value) { baseProperties.setProperty(propertyName, value); } void remove(String propertyName) { baseProperties.remove(propertyName); } Properties getMergedProperties() { Properties result = createProperties(baseProperties); Properties currentlyOverwritten = getSubProperties("archunit", System.getProperties()); result.putAll(currentlyOverwritten); if (!overwrittenProperties.equals(currentlyOverwritten)) { replaceProperties(overwrittenProperties, currentlyOverwritten); if (!currentlyOverwritten.isEmpty()) { LOG.info("Merging properties: The following properties have been overwritten by system properties: {}", currentlyOverwritten); } } return result; } private static void replaceProperties(Properties properties, Properties newProperties) { properties.clear(); properties.putAll(newProperties); } private static Properties createProperties(Map<?, ?> entries) { Properties result = new Properties(); result.putAll(entries); return result; } } public final class ExtensionProperties { private final String extensionIdentifier; private ExtensionProperties(String extensionIdentifier) { this.extensionIdentifier = extensionIdentifier; } @PublicAPI(usage = ACCESS) public ExtensionProperties setProperty(String key, Object value) { String fullKey = Joiner.on(".").join(EXTENSION_PREFIX, extensionIdentifier, key); properties.setProperty(fullKey, String.valueOf(value)); return this; } } }
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.geo.f; import boofcv.alg.geo.MultiViewOps; import boofcv.alg.geo.PerspectiveOps; import boofcv.struct.geo.AssociatedPair; import boofcv.testing.BoofStandardJUnit; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F64; import org.ejml.data.DMatrixRMaj; import org.ejml.dense.row.CommonOps_DDRM; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Peter Abeles */ public class TestDistanceEpipolarConstraint extends BoofStandardJUnit { DMatrixRMaj K = new DMatrixRMaj(3,3,true,100,0.01,200,0,150,200,0,0,1); Se3_F64 worldToCamera = new Se3_F64(); Point3D_F64 X = new Point3D_F64(0.1,-0.04,2.3); Point2D_F64 p1,p2; DMatrixRMaj E,F; public TestDistanceEpipolarConstraint() { worldToCamera.getT().setTo(0.1,-0.1,0.2); p1 = PerspectiveOps.renderPixel(new Se3_F64(),K,X, null); p2 = PerspectiveOps.renderPixel(worldToCamera,K,X, null); E = MultiViewOps.createEssential(worldToCamera.getR(),worldToCamera.getT(), null); F = MultiViewOps.createFundamental(E,K); } /** * Give it a perfect observation and a noisy one. Perfect should have a smaller distance */ @Test void basicCheck() { DistanceEpipolarConstraint alg = new DistanceEpipolarConstraint(); alg.setModel(F); double perfect = alg.distance(new AssociatedPair(p1,p2)); p1.x += 0.2; p1.y += 0.2; double noisy = alg.distance(new AssociatedPair(p1,p2)); assertTrue( perfect < noisy*0.1 ); } /** * Scale the input and see if that changes the error */ @Test void checkScaleInvariance() { DistanceEpipolarConstraint alg = new DistanceEpipolarConstraint(); alg.setModel(F); p1.x += 0.2; p1.y += 0.2; double orig = alg.distance(new AssociatedPair(p1,p2)); // rescale the matrix and see if that changes the results CommonOps_DDRM.scale(5,F); alg.setModel(F); double after = alg.distance(new AssociatedPair(p1,p2)); assertEquals(orig,after,1e-8); } }
package pl.chelm.pwsz.techsupport.domain; import pl.chelm.pwsz.techsupport.database.*; import pl.chelm.pwsz.techsupport.services.*; final class TagFactory extends CacheFactory<Tag, TagDatasource> { TagFactory (Class<Tag> entitiesType, Class<TagDatasource> datasourceType) { super(entitiesType, datasourceType); } TagFactory ( ) { this(Tag.class, TagDatasource.class); } private long writeToDatabase (String title) { TagDatasource datasource = this.getDefaultDatasource( ); return datasource.create(title); } private Data readFromDatabase (String title) { TagDatasource datasource = this.getDefaultDatasource( ); return datasource.read(title); } public Tag newInstance (String title) { long idValue = this.writeToDatabase(title); Identificator<Tag> id = new Identificator<Tag> (idValue); Tag tag = new Tag (id, title); this.cache(tag); return tag; } public Tag getInstance (String title) { Tag tag = null; Data data = this.readFromDatabase(title); if (data != null) { tag = this.getInstance(data); } return tag; } public Tag getInstance (Data data) { Identificator<Tag> id = new Identificator<Tag> (data.<Long>get(Long.class, "id")); Tag tag = this.readFromCache(id); if (tag == null) { String title = data.<String>get(String.class, "title"); tag = new Tag (id, title); this.cache(tag); } return tag; } }
package deepDriver.dl.aml.linearReg; import deepDriver.dl.aml.cart.DataSet; public class LinearRegression { GradientDecentOptimizer gradientDecentOptimizer = new GradientDecentOptimizer(); public LinearExpression fit(DataSet ds) { LinearFunctionSubject linearFunctionSubject = new LinearFunctionSubject(); double [] thetas = gradientDecentOptimizer. optimizeFunction(linearFunctionSubject, ds.getDependentVars(), ds.getIndependentVars(), false); return new LinearExpression(thetas); } }
package br.eti.deividferreira.pontointeligente.api.security.services; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import br.eti.deividferreira.pontointeligente.api.domain.entities.Funcionario; import br.eti.deividferreira.pontointeligente.api.domain.services.FuncionarioService; import br.eti.deividferreira.pontointeligente.api.security.JwtUserFactory; @Service public class JwtUserDetailsServiceImpl implements UserDetailsService { @Autowired private FuncionarioService funcionarioService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<Funcionario> funcionario = funcionarioService.buscarPorEmail(username); if (funcionario.isPresent()) { return JwtUserFactory.create(funcionario.get()); } throw new UsernameNotFoundException("Email não encontrado."); } }
/* * Copyright 2020-2022 Stanislav Batalenkov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.stannismod.gext.api; /** * API for components designed to be selectable. This can be used to add selection box, change color, etc. * @since 1.2 */ public interface ISelectable extends IGraphicsComponent { void onSelect(); void onDeselect(); }
/* * Copyright 2017 Fondazione Istituto Italiano di Tecnologia. * * 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.iit.genomics.cru.simsearch.bundle.view.results; import javax.swing.table.DefaultTableModel; /** * @author Arnaud Ceol */ class ResultsTableModel extends DefaultTableModel { public static final int COLUMN_RESULT_ID = 0; public static final int COLUMN_SIMSCORE = 1; public static final int COLUMN_POSITION = 2; public static final int COLUMN_LENGTH = 3; public static final int COLUMN_GENE = 4; public static final int COLUMN_DISTANCE_TSS = 5; public static final int COLUMN_DISTANCE_TYPE = 6; public static final int COLUMN_SCORES = 7; public ResultsTableModel(Object[] columnNames, int rowCount) { super(columnNames, rowCount); // TODO Auto-generated constructor stub } private static final long serialVersionUID = 1L; @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case COLUMN_RESULT_ID: return Integer.class; case COLUMN_SIMSCORE: return Double.class; case COLUMN_POSITION: return String.class; case COLUMN_DISTANCE_TYPE: return String.class; default: return Integer.class; } } @Override public boolean isCellEditable(int row, int col) { return false; } }
package e.a.a.a.x0; import b.q.a.a; import e.a.a.a.l0; import e.a.l; import e.f; import e.x.c.i; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; public final class d implements InvocationHandler { public final /* synthetic */ Class a; /* renamed from: b reason: collision with root package name */ public final /* synthetic */ f f7623b; public final /* synthetic */ f c; public final /* synthetic */ b d; /* renamed from: e reason: collision with root package name */ public final /* synthetic */ Map f7624e; public d(Class cls, f fVar, l lVar, f fVar2, l lVar2, b bVar, Map map) { this.a = cls; this.f7623b = fVar; this.c = fVar2; this.d = bVar; this.f7624e = map; } public final Object invoke(Object obj, Method method, Object[] objArr) { f fVar; i.d(method, "method"); String name = method.getName(); if (name != null) { int hashCode = name.hashCode(); if (hashCode != -1776922004) { if (hashCode != 147696667) { if (hashCode == 1444986633 && name.equals("annotationType")) { return this.a; } } else if (name.equals("hashCode")) { fVar = this.c; } } else if (name.equals("toString")) { fVar = this.f7623b; } return fVar.getValue(); } if (i.a(name, "equals") && objArr != null && objArr.length == 1) { return Boolean.valueOf(this.d.a(a.U2(objArr))); } if (this.f7624e.containsKey(name)) { return this.f7624e.get(name); } StringBuilder sb = new StringBuilder(); sb.append("Method is not supported: "); sb.append(method); sb.append(" (args: "); if (objArr == null) { objArr = new Object[0]; } sb.append(a.g3(objArr)); sb.append(')'); throw new l0(sb.toString()); } }
package com.magenic.ddd.domain.user; import com.magenic.ddd.domain.address.Address; import com.magenic.ddd.domain.shared.AuditingBaseEntity; import com.magenic.ddd.domain.shared.constant.DepartmentType; import javax.persistence.Entity; import javax.persistence.OneToOne; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Entity public abstract class User extends AuditingBaseEntity { @NotEmpty private String name; @NotNull private DepartmentType department; @NotEmpty private String email; @NotNull @OneToOne(targetEntity = Address.class) private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public DepartmentType getDepartment() { return department; } public void setDepartment(DepartmentType department) { this.department = department; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
package com.itcast.rabbitmq.work; import com.itcast.rabbitmq.util.ConnectionUtil; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer1 { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = ConnectionUtil.getConnection(); //创建频道 Channel channel = connection.createChannel(); //创建队列 channel.queueDeclare(Producer.QUEUE_NAME,true,false,false,null); //创建消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("交换机:"+envelope.getExchange()); System.out.println("路由key:"+envelope.getRoutingKey()); System.out.println("消息id:"+envelope.getDeliveryTag()); System.out.println("消息:"+new String(body,"utf-8")); } }; //监听消息 channel.basicConsume(Producer.QUEUE_NAME,true,consumer); } }
/* * MIT License * * Copyright (c) 2020-present Cloudogu GmbH and 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 com.cloudogu.scm.ci.cistatus.service; import com.cloudogu.scm.ci.PermissionCheck; import com.cloudogu.scm.ci.cistatus.CIStatusStore; import sonia.scm.repository.ChangesetPagingResult; import sonia.scm.repository.InternalRepositoryException; import sonia.scm.repository.Repository; import sonia.scm.repository.api.RepositoryService; import sonia.scm.repository.api.RepositoryServiceFactory; import sonia.scm.store.DataStore; import sonia.scm.store.DataStoreFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.io.IOException; import static com.cloudogu.scm.ci.cistatus.CIStatusStore.CHANGESET_STORE; import static sonia.scm.ContextEntry.ContextBuilder.entity; import static sonia.scm.NotFoundException.notFound; @Singleton public class CIStatusService { private final DataStoreFactory dataStoreFactory; private final RepositoryServiceFactory repositoryServiceFactory; @Inject public CIStatusService(DataStoreFactory dataStoreFactory, RepositoryServiceFactory repositoryServiceFactory) { this.dataStoreFactory = dataStoreFactory; this.repositoryServiceFactory = repositoryServiceFactory; } public void put(CIStatusStore store, Repository repository, String id, CIStatus ciStatus) { PermissionCheck.checkWrite(repository); CIStatusCollection ciStatusCollection = get(store, repository, id); ciStatusCollection.put(ciStatus); getStore(store, repository).put(id, ciStatusCollection); } public CIStatusCollection get(CIStatusStore storeName, Repository repository, String id) { PermissionCheck.checkRead(repository); CIStatusCollection collection = getStore(storeName, repository).get(id); return collection != null ? collection : new CIStatusCollection(); } public CIStatusCollection getByBranch(Repository repository, String branch) { try (RepositoryService service = repositoryServiceFactory.create(repository)) { final ChangesetPagingResult changesets = service.getLogCommand().setBranch(branch).setPagingLimit(1).getChangesets(); if (changesets.getChangesets().isEmpty()) { throw notFound(entity("Branch", branch).in(repository)); } return get(CHANGESET_STORE, repository, changesets.getChangesets().get(0).getId()); } catch (IOException e) { throw new InternalRepositoryException( entity("Branch", branch).in(repository).build(), "could not read changeset for branch " + branch + " in repository " + repository, e); } } private DataStore<CIStatusCollection> getStore(CIStatusStore store, Repository repository) { return dataStoreFactory.withType(CIStatusCollection.class).withName(store.name).forRepository(repository).build(); } }
package net.b07z.sepia.server.assist.interpreters; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import net.b07z.sepia.server.assist.parameters.AbstractParameterSearch; import net.b07z.sepia.server.assist.parameters.FashionBrand; import net.b07z.sepia.server.assist.parameters.FashionItem; import net.b07z.sepia.server.assist.parameters.FashionShopping; import net.b07z.sepia.server.assist.parameters.FoodClass; import net.b07z.sepia.server.assist.parameters.FoodItem; import net.b07z.sepia.server.assist.parameters.Language; import net.b07z.sepia.server.assist.parameters.Place; import net.b07z.sepia.server.assist.server.Config; import net.b07z.sepia.server.core.assistant.CMD; import net.b07z.sepia.server.core.assistant.PARAMETERS; /** * Simple (at least from the idea) yet effective keyword analyzer for English to interpret user input.<br> * The order of checks does matter, put commands with less priority at the bottom. If commands score the same probability the first is taken.<br> * Note: Never use this as a static interpreter! Always create new instances of it when needed (compared to the sentence matchers * that can be used globally). * * @author Florian Quirin * */ public class NluKeywordAnalyzerEN implements NluInterface { double certainty_lvl = 0.0d; //how certain is ILA about a result Map<String, String> locations; //store locations in text Map<String, String> dates; //store dates in text Map<String, String> numbers; //store numbers in text Map<String, String> websearches; //store web search in text Map<String, String> controls; //store control parameters in text Map<String, String> music_parameters; //store music parameters in text Map<String, String> vehicle_parameters; //store vehicle search parameters Map<String, String> retail_parameters; //store retail search parameters public NluResult interpret(NluInput input) { //get parameters from input String text = input.text; String language = input.language; //normalize text, e.g.: // all lowerCase - remove all ',!? - handle ä ö ü ß ... trim Normalizer normalizer = Config.inputNormalizers.get(language); if (normalizer != null){ text = normalizer.normalizeText(text); input.text = text; //TODO: is this ok here? Do it before? } //first rough check for main keywords List<String> possibleCMDs = new ArrayList<>(); //make a list of possible interpretations of the text List<Map<String, String>> possibleParameters = new ArrayList<>(); //possible parameters List<Integer> possibleScore = new ArrayList<>(); //make scores to decide which one is correct command int index = -1; //track parameters //HashMap<String, String> checkedPrameters = new HashMap<String, String>(); //some small-talk stuff if (NluTools.stringContains(text, "^" + Pattern.quote(Config.assistantName.toLowerCase()) + "$")){ //String this_text = text; possibleCMDs.add(CMD.CHAT); possibleScore.add(1); index++; //type String type = "greeting"; possibleScore.set(index, possibleScore.get(index)+1); Map<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.TYPE, type); possibleParameters.add(pv); } //----- SYSTEM SERVICES ----- //TODO: We can simplify this class by moving ALL regular expressions to the getInfo method of the services //For some services this is already done: index = NluKeywordAnalyzer.runSystemServices(input, possibleCMDs, possibleScore, possibleParameters, index); //... but sometimes we want to handle some exceptions and special conditions ... //--------------------------- //What follows now is a list of regular expressions for certain commands that trigger parameter searches ... //news if (NluTools.stringContains(text, "news|whats new|whats up|whats going on|headline|headlines|" + "results|result|score|scores|baseball|hockey|basketball|football|tennis|golf|soccer|" + "did .* (play|score|win|winning|lost|losing)|^(baseball|football|soccer)(game|)\\b|" + "when .* (play|playing)|" + "bundesliga|champions( |-|)league|euro( |-|)league|europa( |-|)league|premier league|primera division|la liga|" + "(serie|seria|series) a|eredivisie|ligue 1|primeira liga|sueperlig|sueper lig(a|)|(fa|dfb)(-| )(pokal|cup)" + "")){ //String this_text = text; possibleCMDs.add(CMD.NEWS); possibleScore.add(1); index++; //double score for news if (NluTools.stringContains(text, "news")){ possibleScore.set(index, possibleScore.get(index) + 1); } Map<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.NEWS_SECTION, PARAMETERS.NEWS_TYPE, PARAMETERS.SPORTS_TEAM, PARAMETERS.SPORTS_LEAGUE, PARAMETERS.LANGUAGE) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //weather if (NluTools.stringContains(text, "weather|temperature|rain|raining|snow|snowing|be sunny|umbrella|sunscreen|" + "how (hot|cold|warm) (is|will)|degree(s|)")){ possibleCMDs.add(CMD.WEATHER); possibleScore.add(1); index++; Map<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.TIME, PARAMETERS.PLACE) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //smart device control /* -- moved to service -- if (NluTools.stringContains(text, "light(s|)|lighting|lamp(s|)|illumination|brightness|" + "heater(s|)|temperature(s|)|thermostat(s|)|" + "(smart( |)home|device|sensor) (control|stat(us|e))" )){ possibleCMDs.add(CMD.SMARTDEVICE); possibleScore.add(1); index++; Map<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.ACTION, PARAMETERS.SMART_DEVICE, PARAMETERS.SMART_DEVICE_VALUE, PARAMETERS.ROOM) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } */ //directions if (NluTools.stringContains(text, "directions|navigation|show me the way|navigate me|(?<!cheapest )way |" + "(bring|get|take) me (?!(a|the)\\b)|" + "(how do i get (to|home)\\b)|" + "(show|find) .* (from|to) .* (map|maps)\\b|" + "\\b(from) .* (to) |" + "how far |(how long |duration .*\\b(to) )(?!.*(timer|alarm|reminder)(s|))|distance |to go to |to drive to |to travel to ")){ //String this_text = text; possibleCMDs.add(CMD.DIRECTIONS); possibleScore.add(1); index++; Map<String, String> pv = new HashMap<>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.TIME, PARAMETERS.TRAVEL_TYPE, PARAMETERS.TRAVEL_REQUEST_INFO, PARAMETERS.LOCATION_END, PARAMETERS.LOCATION_WAYPOINT, PARAMETERS.LOCATION_START) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //wikipedia/knowledgebase if (NluTools.stringContains(text, "wiki|wikipedia|information|informations|knowledge base|" + "who (is|are|was|were) .*|" + "meaning of .*|what (is|was|are|were) .*|" + "when (is|was|are|were) .*|" + "do you know .*|tell me .* about|define|" + "how (high|large) (is|are|was|were) .*|how old (is|are|was|were) .*|how many .* (are|has|were|had|live|lived) ")){ String this_text = text; possibleCMDs.add(CMD.KNOWLEDGEBASE); possibleScore.add(1); index++; //score a bit extra if we start with certain words if (NluTools.stringContains(this_text, "^((search |)(the |in |at |)(wikipedia|knowledge base))")){ possibleScore.set(index, possibleScore.get(index)+1); } //kb search term String kb_search=""; if (NluTools.stringContains(this_text, "how (high|large) (is|are|was|were)|how old (is|are|was|were)|how many .* (are|has|were|had|live|lived) ")){ kb_search = this_text.replaceFirst(".*\\b(how (high|large)|how old|how many)\\b", "$1").trim(); }else{ kb_search=this_text.replaceFirst(".*?\\b((wikipedia|knowledge base) for)\\s", "").trim(); kb_search=kb_search.replaceFirst(".*?\\b(search for|search|who|what|where|when|information on|about|do you know)\\s", "").trim(); kb_search=kb_search.replaceFirst("\\b(^the meaning of|^who|^where|^what|^when)\\s", "").trim(); kb_search=kb_search.replaceFirst("\\b(^is|^was|^were|^are|^about|^on)\\s", "").trim(); kb_search=kb_search.replaceFirst("\\b(^a|^an|^the|^wiki|^wikipedia)\\s", "").trim(); kb_search=kb_search.replaceFirst("\\b(is$|was$|were$|are$|on wikipedia$|in wikipedia$)", "").trim(); } //recover original kb_search = normalizer.reconstructPhrase(input.textRaw, kb_search); //score if (!kb_search.matches("")){ possibleScore.set(index, possibleScore.get(index)+1); } //kb additional query (time, place, person, thing) String kb_add_info=""; if (NluTools.stringContains(this_text, "when|time")){ kb_add_info = "time"; }else if (NluTools.stringContains(this_text, "who|person")){ kb_add_info = "person"; }else if (NluTools.stringContains(this_text, "where|place")){ kb_add_info = "place"; } Map<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, kb_search.trim()); pv.put(PARAMETERS.TYPE, kb_add_info.trim()); possibleParameters.add(pv); } //web search //TODO: optimize exceptions if (NluTools.stringContains(text, "websearch|web search|search the web|search online|" + "^google|^bing|^yahoo|^duck duck|^duck duck go|^ecosia|^youtube|" + "^(picture(s|)|recipe(s|)|video(s|)|movie(s|)|film(s|)|share(s|)|stock(s|)|book(s|))|" + "what is the (stock|share) (value|price)|" + "(search|find|show|look|searching|looking)( | .* )((on |)the (web|internet))|" + "(search|find|show|look|searching|looking)( | .* )(with|on|via|per|over|by) (google|bing|duck duck go|duck duck|yahoo|ecosia|youtube)|" + "(search|find|show|look|searching|looking)( | .* )(picture(s|)|recipe(s|)|video(s|)|youtube|book(s|)|share(s|)|stock(s|))") //|| NLU_Tools.stringContains(text, "search|find|show|look for|searching for|looking for") //|| (NLU_Tools.stringContains(text, "search|find|show") // && !NLU_Tools.stringContains(text, "(search|find|show)\\b.*\\b(music|song(s|)|news|wikipedia|" // + "(action|fantasy|)movie(s|)|ticket(s|))")) ){ //String this_text = text; possibleCMDs.add(CMD.WEB_SEARCH); possibleScore.add(1); index++; //score a bit extra if you made it till here ^^ possibleScore.set(index, possibleScore.get(index)+1); //put some weight on the search engines and keywords for web-search: if (NluTools.stringContains(text, "websearch|web|online|internet|google|bing|yahoo|duck duck|ecosia")){ possibleScore.set(index, possibleScore.get(index)+2); } Map<String, String> pv = new HashMap<>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.WEBSEARCH_ENGINE, PARAMETERS.WEBSEARCH_REQUEST, PARAMETERS.SEARCH_SECTION) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //mobility if (NluTools.stringContains(text, "(\\b)(the |)(fastest|best|cheapest|cheap) (connection|connections|way|ways)|" + "(option|options) .*?\\b(between)\\b.*?\\b(and)|" + "(option|options) .*?\\b(from)\\b.*?\\b(to)")){ //String this_text = text; possibleCMDs.add(CMD.MOBILITY); possibleScore.add(1); index++; HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.TIME, PARAMETERS.TRAVEL_TYPE, PARAMETERS.TRAVEL_REQUEST_INFO, PARAMETERS.LOCATION_END, PARAMETERS.LOCATION_WAYPOINT, PARAMETERS.LOCATION_START) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //fashion shopping if (NluTools.stringContains(text, "(buy|fashion|shopping)") || ((NluTools.stringContains(text, FashionItem.fashionItems_en) || NluTools.stringContains(text, FashionBrand.fashionBrandsSearch)) && !NluTools.stringContains(text, "(i have |there are |my )")) ){ possibleCMDs.add(CMD.FASHION); possibleScore.add(1); index++; Map<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking FashionShopping fs = new FashionShopping().setup(input, pv); fs.getParameters(); possibleScore.set(index, possibleScore.get(index) + fs.getScore()); possibleParameters.add(pv); } //food if (NluTools.stringContains(text, "^food$|" + "(food|foodstuff|meal|breakfast|lunch|dinner|groceries|nourishments) .*\\b(order|buy|deliver|eat)|" + "(" + Language.languageClasses_en + "|" + FoodClass.foodClasses_en + ") .*\\b(order|buy|deliver|eat)|" + "(order|buy|deliver|eat|what) .*\\b(food|foodstuff|meal|breakfast|lunch|dinner|groceries|nourishments|eat)|" + "(order|buy|deliver|eat) .*\\b(" + Language.languageClasses_en + "|" + FoodClass.foodClasses_en + ")|" + "hunger|hungry|appetite|delivery|" + "(from) .*\\b(\\w*restaurant(s|))") || NluTools.stringContains(text, FoodItem.foodItems_en) ){ possibleCMDs.add(CMD.FOOD); possibleScore.add(1); index++; Map<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.FOOD_ITEM, PARAMETERS.FOOD_CLASS) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //flights if (NluTools.stringContains(text, "(flights|flight) (from|to)|flightsearch|" + "(search|searching|find|i need|show me|book|look|looking)\\b.* (flight|flights|plane|planes|fly|planeticket|flightticket)|" + "(bring |show |way ).*\\b(plane)") && !NluTools.stringContains(text, "on (the|a) map")){ String this_text = text; possibleCMDs.add(CMD.FLIGHTS); possibleScore.add(1); index++; //double score for flight 'cause the initial filter is already pretty strict if (NluTools.stringContains(this_text, "flight|flights|flying|fly|plane|planes|planeticket|flightticket")){ possibleScore.set(index, possibleScore.get(index)+1); } //analyze search_locations(this_text, language); //travel time String travel_time = locations.get("travel_time").trim(); if (!travel_time.matches("")){ possibleScore.set(index, possibleScore.get(index)+1); } //destination String travel_destination = locations.get("location_end").trim(); if (travel_destination.isEmpty()){ travel_destination = locations.get("location").trim(); //filter some stupid results travel_destination = travel_destination.replaceAll("\\b(flight(s|)|plane(s|)|planeticket|flightticket)\\b", ""); travel_destination = travel_destination.replaceAll("\\b^(a|the)\\b", "").trim(); } if (!travel_destination.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } //start String travel_start = locations.get("location_start").trim(); if (!travel_start.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); }else{ travel_start = "<user_location>"; //default is user location } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.LOCATION_START, travel_start); pv.put(PARAMETERS.LOCATION_END, travel_destination); pv.put(PARAMETERS.TIME, travel_time); possibleParameters.add(pv); } //timer - reminder if (NluTools.stringContains(text, "(\\w+(-)|)timer(s|)|(\\w+(-)|)counter(s|)|(\\w+(-)|)countdown(s|)|count down|stop watch(es|)|(\\w+(-)|)stopwatch(es|)|" + "(\\w+(-)|)alarm(s|)|wake me|out of bed|get up at|" + "(\\w+(-)|)reminder(s|)|remind (me|us)|remember|" + "(\\w+(-)|)appointment(s|)|calendar(s|)")){ possibleCMDs.add(CMD.TIMER); possibleScore.add(1); index++; HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.ACTION, PARAMETERS.TIME, PARAMETERS.CLOCK, PARAMETERS.ALARM_TYPE, PARAMETERS.ALARM_NAME) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //hotel search if (NluTools.stringContains(text, "hotel|hotels") && !NluTools.stringContains(text, "where(?! i|we|one)|map|maps")){ String this_text = text; possibleCMDs.add(CMD.HOTELS); possibleScore.add(1); index++; //analyze search_locations(this_text, language); //place to search String place = locations.get("location").trim(); //String poi = locations.get("poi"); //clean up place place = place.replaceFirst("(.*)( for )(.*)", "$1").trim(); //time to search String time_start = locations.get("travel_time").trim(); String time_end = locations.get("travel_time_end").trim(); //empty? if (!place.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!time_start.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!time_end.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.PLACE, place); pv.put(PARAMETERS.TIME, time_start); pv.put(PARAMETERS.TIME_END, time_end); possibleParameters.add(pv); } //radio if (NluTools.stringContains(text, "\\w*radio(\\.|)(fm|\\d+|)|radiochannel|radiostation|radiostream|music station|music channel") && !possibleCMDs.contains(CMD.KNOWLEDGEBASE)){ //String this_text = text; possibleCMDs.add(CMD.MUSIC_RADIO); possibleScore.add(1); index++; //it is so obvious, score again possibleScore.set(index, possibleScore.get(index)+1); HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.MUSIC_GENRE, PARAMETERS.RADIO_STATION, PARAMETERS.ACTION) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //music if (NluTools.stringContains(text, "music|play .*|(start|open|show) .*\\b(title(s|)|track(s|)|of|by)|song(s|)|playlist|" + "album|record|spotify|deezer|soundcloud|youtube|vlc") && !possibleCMDs.contains(CMD.KNOWLEDGEBASE)){ //String this_text = text; possibleCMDs.add(CMD.MUSIC); possibleScore.add(1); index++; //it is so obvious, score again //possibleScore.set(index, possibleScore.get(index)+1); HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters( PARAMETERS.MUSIC_SERVICE, PARAMETERS.MUSIC_GENRE, PARAMETERS.MUSIC_ALBUM, PARAMETERS.MUSIC_ARTIST, PARAMETERS.SONG, PARAMETERS.PLAYLIST_NAME ) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //movies if (NluTools.stringContains(text, "(action|fantasy|)(movie(s|))") && !NluTools.stringContains(text, "websearch|web search|search online|google|bing")){ String this_text = text; possibleCMDs.add(CMD.MOVIES); possibleScore.add(1); index++; //genre String movie_type = ""; movie_type = RegexParameterSearch.get_movie_genre(this_text, language); if (!movie_type.matches("")){ possibleScore.set(index, possibleScore.get(index)+1); } //info (actor, director?) String info = ""; if (this_text.matches(".*(movie |movies )(from .*|of .*|by .*)")){ info = "director"; }else if (this_text.matches(".*(movie |movies )(with .*)")){ info = "actor"; }else if (this_text.matches(".*(movie |movies )(named .*|called .*)")){ info = "title"; } //title String movie = ""; if (this_text.matches(".*(movie |movies )(named .*|called .*|from .*|of .*|by .*|with .*)")){ movie = this_text.replaceFirst(".*?(movie |movies )(named |called| from |of |by |with )", "").trim(); possibleScore.set(index, possibleScore.get(index)+1); }else{ if (this_text.matches(".*(movie |movies ).*")) movie = this_text.replaceFirst(".*?(movie |movies )", "").trim(); else { movie = this_text.replaceFirst("\\b(action|)(movies$|movie$)", "").trim(); //TODO: this is problematic for titles like scary movie! movie = movie.replaceFirst("^(show me |show |find me |find |search for |search )", "").trim(); } } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, movie); pv.put(PARAMETERS.TYPE, movie_type); pv.put(PARAMETERS.INFO, info); possibleParameters.add(pv); } //event tickets if (NluTools.stringContains(text, "ticket|tickets|entrance card|admission card|voucher")){ String this_text = text; possibleCMDs.add(CMD.TICKETS); possibleScore.add(1); index++; //type String ticket_type = RegexParameterSearch.get_event_type(this_text, language); //search event/movie/etc. ... String search = ""; if (this_text.matches(".*\\b(for ).*")){ search = this_text.replaceFirst(".*\\b(for )", "").trim(); search = search.replaceFirst("^(a|an|the)\\b", "").trim(); search = search.replaceFirst("\\b(movie|concert)$\\b", "").trim(); //search = search.replaceFirst("\\b(buy|order|get|search)\\b.*", "").trim(); //is the search actually the type? if (!ticket_type.isEmpty() && RegexParameterSearch.get_event_type(search, language).equals(ticket_type)){ search = ""; } } if (!search.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, search); pv.put(PARAMETERS.TYPE, ticket_type); possibleParameters.add(pv); } //dictionary if (NluTools.stringContains(text, "dictionary|word (search|find|look)|(search|find|look) .*\\b(word)|translation|" + "translate|" + ".* (into|in|to) (english|german|turkish|french|spanish)")){ String this_text = text; possibleCMDs.add(CMD.DICT_TRANSLATE); possibleScore.add(1); index++; //double score for translate and dictionary if (NluTools.stringContains(text, "translate|translation|dictionary")){ possibleScore.set(index, possibleScore.get(index) + 1); } //TODO: make real parameter out of that //dictionary target language String target_lang=""; if (NluTools.stringContains(this_text, "(into|to|in) german")){ target_lang = "en"; }else if (NluTools.stringContains(this_text, "(into|to|in) spanish")){ target_lang = "es"; }else if (NluTools.stringContains(this_text, "(into|to|in) turkish")){ target_lang = "tr"; }else if (NluTools.stringContains(this_text, "(into|to|in) french")){ target_lang = "fr"; }else if (NluTools.stringContains(this_text, "(into|to|in) english")){ target_lang = "en"; } if (!target_lang.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } //remove language tag this_text = this_text.replaceFirst("(into|to|in) (german|spanish|" + "turkish|french|english)", "").trim(); //dictionary search term String dict_search=this_text.replaceFirst(".*?\\b(dictionary for)\\s", "").trim(); dict_search=dict_search.replaceFirst(".*?\\b(translation of|translation for|translate)\\s", "").trim(); dict_search=dict_search.replaceFirst(".*?\\b(search for|search)\\s", "").trim(); dict_search=dict_search.replaceFirst("\\b(^can you|^what is|^show me|^what means)\\b", "").trim(); dict_search=dict_search.replaceFirst("\\b(^the|^a)\\b", "").trim(); dict_search=dict_search.replaceFirst("\\b(from the dictionary$|in the dictionary$|in dictionary$)", "").trim(); if (!dict_search.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); //let it score but remove the false search if (dict_search.matches("word|words|translation")){ dict_search = ""; } } //recover original dict_search = normalizer.reconstructPhrase(input.textRaw, dict_search); HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, dict_search.trim()); pv.put(PARAMETERS.LANGUAGE, target_lang.trim()); possibleParameters.add(pv); } //Lists if (NluTools.stringContains(text, "list(s|)|to(-| |)do(-\\w+|)|shoppinglist(s|)|note(s|)|(need|have) to buy")){ //String this_text = text; possibleCMDs.add(CMD.LISTS); possibleScore.add(1); index++; HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.ACTION, PARAMETERS.LIST_TYPE, PARAMETERS.LIST_SUBTYPE, PARAMETERS.LIST_ITEM) .setup(input, pv); aps.getParameters(); possibleScore.set(index, possibleScore.get(index) + aps.getScore()); possibleParameters.add(pv); } //TV Program if (NluTools.stringContains(text, "(tv|television) program|(whats|what is) (on the|on) (tv|telly)")){ String this_text = text; possibleCMDs.add(CMD.TV_PROGRAM); possibleScore.add(1); index++; //tv time search_dates(this_text, language); String tv_time = dates.get("date_tag"); if (!tv_time.isEmpty()){ this_text = RegexParameterSearch.remove_date(this_text, tv_time, language); possibleScore.set(index, possibleScore.get(index)+1); } //channel String channel = NluTools.stringFindFirst(this_text, "hbo|amc|abc"); if (!channel.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.TIME, tv_time.trim()); pv.put(PARAMETERS.CHANNEL, channel.trim()); possibleParameters.add(pv); } //My favorites if (NluTools.stringContains(text, "(my favorite|my personal|my private) .* (is|are)|" + "(what (is|are)|do you know|delete|forget|remove) my (favorite|private|personal)|" + "(open|show me|show|what (is|are)|do you know) my (favorites|info|favorite (stuff|things))")){ String this_text = text; possibleCMDs.add(CMD.MY_FAVORITE); possibleScore.add(1); index++; //item String info = ""; String item = RegexParameterSearch.get_my_info_item(this_text, language); //item = this_text.replaceFirst(".*?\\b(my personal|my private|my favorites|my info|my)\\b", ""); //item = item.replaceFirst("\\b(is|are)\\b.*", "").trim(); if (!item.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); //info info = this_text.replaceFirst(".*?\\b(" + item + ")\\b", ""); info = RegexParameterSearch.get_my_info(info, language); //info = info.replaceFirst(".*?\\b(is|are)\\b", "").trim(); //info = info.replaceFirst("\\b^(a|an)\\s", "").trim(); if (!info.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } //clean up some items item = item.replaceFirst("^(favorites|info)", "").trim(); } //action String action = NluTools.stringFindFirst(this_text, "^forget|^remove|^delete|^open|^show|^what is|^what are|^do you know"); if (!action.isEmpty()){ action = (action.matches("forget|remove|delete")? "remove":"open"); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.TYPE, item.trim()); pv.put(PARAMETERS.INFO, info.trim()); pv.put(PARAMETERS.ACTION, action.trim()); possibleParameters.add(pv); } //insurance if (NluTools.stringContains(text, "insurance(s|)|assurance(s|)|inssure|assure") ){ String this_text = text; possibleCMDs.add(CMD.INSURANCE); possibleScore.add(1); index++; //increase score for these if (NluTools.stringContains(this_text, "(inssure)")){ possibleScore.set(index, possibleScore.get(index)+1); } //action String action = NluTools.stringFindFirst(this_text, "help|info(s|)|information(s|)|offer|inssure|cancle|change|contract"); if (!action.isEmpty()){ //check for explicit help tags if (!action.isEmpty() && NluTools.stringContains(action, "help|info(s|)|information(s|)|cancle|change|contract")){ action = "<get_help>"; //maybe this should be default }else{ action = "<get_offer>"; //default and the only thing supported yet } possibleScore.set(index, possibleScore.get(index)+1); }else{ action = "<get_offer>"; //default and the only thing supported yet } //info - what to insure String info = NluTools.stringFindFirst(this_text, "motorcycle(s|)|motorbike(s|)|bike(s|)|auto(s|)|car(s|)|" + "house(s|)|flat(s|)|life"); if (!info.isEmpty()){ if (NluTools.stringContains(info, "motorcycle(s|)|motorbike(s|)")){ info = "<motorcycle>"; //the only thing supported yet } possibleScore.set(index, possibleScore.get(index)+1); } //type - types like "vollkasko" String type = NluTools.stringFindFirst(this_text, "(fully |partially |)comprehensive"); if (!type.isEmpty() && type.contains("fully")){ type = "<fc>"; }else if (!type.isEmpty() && type.contains("partially")){ type = "<pc>"; } //type does not score (?) HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.ACTION, action); pv.put(PARAMETERS.INFO, info); pv.put(PARAMETERS.TYPE, type); possibleParameters.add(pv); } //locations if (NluTools.stringContains(text, "where (is|lies|are|am) .*|where can (i|one) .*| where we are| where i am|where .* (is|are|live|lives|lies|lie|lay)|" + "(is there|are there|can (i|one) get) .*\\b(close|near|around|here|in)|" + "(search|show|find|look(up| for)|looking for) .*(\\b)("+ Place.getPoiRegExpList(language) +")|" + "(show|search|find|look(up| for|)) .*(\\b)on (\\w+ |)(map(s|))|" //+ "(show|search|find|look for) .*(\\b)(close|near|around)( to| by|)( me|)$|" //TODO: broken!?? //+ "(show|search|find|look for) (on |)((the|a) map|maps) .*|" + "(address|location .*)") && !possibleCMDs.contains(CMD.HOTELS)){ String this_text = text; possibleCMDs.add(CMD.LOCATION); possibleScore.add(1); index++; //TODO: make real parameter out of this! //analyze search_locations(this_text, language); //place to search String place = locations.get("location"); String poi = locations.get("poi"); if (place.isEmpty() && poi.isEmpty()){ if (NluTools.stringContains(this_text, "where am i|where are we|where we are|where i am")){ place = "<user_location>"; } } //still empty? if (!place.trim().isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!poi.trim().isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, place); //TODO: change to place instead of search? pv.put(PARAMETERS.POI, poi); possibleParameters.add(pv); } //retailer product search/buy if (NluTools.stringContains(text, "(search) (saturn|media(\\s|)(markt|market|markets)|amazon)")){ String this_text = text; possibleCMDs.add(CMD.SEARCH_RETAIL); possibleScore.add(1); index++; //increase score for these by 2 /* if (NluTools.stringContains(this_text, "(saturn|media(\\s|)(markt|market|markets)|amazon)")){ possibleScore.set(index, possibleScore.get(index)+2); //increase by 1 'cause we have to believe ^^ }else{ possibleScore.set(index, possibleScore.get(index)+1); } */ //retail parameters search_retail_parameters(this_text, language); String color = retail_parameters.get("color"); String age = retail_parameters.get("age"); String price = retail_parameters.get("price"); String price_type = retail_parameters.get("price_t"); String retail_type = ""; if (NluTools.stringContains(this_text, "saturn")){ retail_type = "<saturn>"; }else if (NluTools.stringContains(this_text, "media(\\s|)(markt|market|markets)")){ retail_type = "<media_markt>"; }else if (NluTools.stringContains(this_text, "amazon")){ retail_type = "<amazon>"; } //convert units to default - handle special chars //--price to € price = RegexParameterSearch.convert_amount_to_default("money", price_type, price, language); //search term String search = NluTools.stringFindFirst(this_text, "(a|for) .*"); search = search.replaceAll("^(a|for)\\b", ""); search = search.replaceAll("\\b(and|with|for|in|from|to|over|under|the|not|less|more|maximum|maximal|minimum|minimal|at) .*", "").trim(); String junk = NluTools.stringFindFirst(search, "saturn|media(\\s|)(markt|market|markets)|amazon"); if (!junk.isEmpty()){ search = search.replaceAll("(a |the |)" + Pattern.quote(junk), "").replaceAll("\\s+", " ").trim(); } search = search.replaceAll("^(a|the)\\b","").trim(); //score if (!color.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!age.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!price.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.TYPE, retail_type.trim()); pv.put(PARAMETERS.SEARCH, search.trim()); pv.put(PARAMETERS.COLOR, color.trim()); pv.put(PARAMETERS.AMOUNT_MONEY, price.trim()); pv.put(PARAMETERS.AGE_YEARS, age.trim()); possibleParameters.add(pv); } //vehicle search/buy if (NluTools.stringContains(text, "autoscout|autoscout24") || (NluTools.stringContains(text, "auto(s|)|automobile(s|)|car(s|)|motorcycle(s|)|motorbike(s|)|bike(s|)") && NluTools.stringContains(text, "search|find|show|look for|searching for|looking for|buy|need")) ){ String this_text = text; possibleCMDs.add(CMD.SEARCH_VEHICLE); possibleScore.add(1); index++; //increase score for these by 2 if (NluTools.stringContains(this_text, "(autoscout|autoscout24)")){ possibleScore.set(index, possibleScore.get(index)+2); //increase by 1 'cause we have to believe ^^ }else{ possibleScore.set(index, possibleScore.get(index)+1); } //vehicle parameters search_vehicle_parameters(this_text, language); String color = vehicle_parameters.get("vehicle_color"); String age = vehicle_parameters.get("vehicle_age"); String price = vehicle_parameters.get("vehicle_price"); String price_type = vehicle_parameters.get("vehicle_price_t"); String power = vehicle_parameters.get("vehicle_power"); String power_type = vehicle_parameters.get("vehicle_power_t"); String distance = vehicle_parameters.get("vehicle_distance"); String distance_type = vehicle_parameters.get("vehicle_distance_t"); String vehicle_type = ""; if (NluTools.stringContains(this_text, "motorcycle(s|)|motorbike(s|)|bike(s|)")){ vehicle_type = "B"; }else if (NluTools.stringContains(this_text, "auto(s|)|automobile(s|)|car(s|)")){ vehicle_type = "C"; } //convert units to default - handle special chars //--price to € price = RegexParameterSearch.convert_amount_to_default("money", price_type, price, language); //--power to kW power = RegexParameterSearch.convert_amount_to_default("power", power_type, power, language); //--distance to km distance = RegexParameterSearch.convert_amount_to_default("distance", distance_type, distance, language); //search term String search = NluTools.stringFindFirst(this_text, "(a|for) .*"); search = search.replaceAll("^(a|for)\\b", ""); search = search.replaceAll("\\b(and|with|for|in|from|to|over|under|the|not|less|more|maximum|maximal|minimum|minimal|at) .*", "").trim(); String junk = NluTools.stringFindFirst(search, "motorcycle(s|)|motorbike(s|)|bike(s|)|auto(s|)|automobile(s|)|car(s|)"); if (!junk.isEmpty()){ search = search.replaceAll("(a |the |)" + Pattern.quote(junk), "").replaceAll("\\s+", " ").trim(); } if (NluTools.stringContains(this_text, "(model|make|brand|lable)( is| are|) (not important|unimportant|does not matter|doesnt matter)")){ search = "<all>"; }else if (search.isEmpty() && NluTools.stringContains(this_text, "(model|make|lable|brand)( is| are|) \\w+")){ search = this_text.replaceFirst(".*\\b(model|make|lable|brand)( is| are| should be|) ((\\w+)(-\\w+|))\\b.*", "$3"); } search = search.replaceAll("^(a|the)\\b","").trim(); //score if (!color.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!age.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!price.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!power.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } if (!distance.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.SEARCH, search.trim()); pv.put(PARAMETERS.TYPE, vehicle_type.trim()); pv.put(PARAMETERS.COLOR, color.trim()); pv.put(PARAMETERS.AMOUNT_MONEY, price.trim()); pv.put(PARAMETERS.AMOUNT_POWER, power.trim()); pv.put(PARAMETERS.AMOUNT_DISTANCE, distance.trim()); pv.put(PARAMETERS.AGE_YEARS, age.trim()); possibleParameters.add(pv); } //Banking if (NluTools.stringContains(text, "bank|bankaccount|banking|banktransfer|money|transfer|payment|pay|" + "send .*(€|$|eur\\b|euro(s|)|dollar(s|)|pound(s|))|(€|$|eur\\b|euro(s|)|dollar(s|)|pound(s|)).* (send|sent)")){ String this_text = text; possibleCMDs.add(CMD.BANKING); possibleScore.add(1); index++; //currency String currency = RegexParameterSearch.get_currency(this_text, language); if (!currency.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); } //action / receiver String action = RegexParameterSearch.get_banking_action(this_text, language); String receiver = ""; if (!action.isEmpty()){ possibleScore.set(index, possibleScore.get(index)+1); //check for contact if is <send> if (action.contains("<send>")){ //TODO: find contact in text } } //numbers search_numbers(this_text, language); String num = numbers.get("value1"); if (!num.isEmpty() && !currency.isEmpty() && !action.isEmpty() && (action.contains("<send>") || action.contains("<pay>"))){ possibleScore.set(index, possibleScore.get(index)+1); } HashMap<String, String> pv = new HashMap<String, String>(); pv.put(PARAMETERS.ACTION, action); pv.put(PARAMETERS.NUMBER, num); pv.put(PARAMETERS.CURRENCY, currency); pv.put(PARAMETERS.RECEIVER, receiver); possibleParameters.add(pv); } //----- CUSTOM SERVICES ----- index = NluKeywordAnalyzer.runCustomSdkServices(input, possibleCMDs, possibleScore, possibleParameters, index); //--------------------------- //Common search fallback if (NluTools.stringContains(text, "search|find|show|look for|searching for|looking for") ){ //String this_text = text; possibleCMDs.add(CMD.WEB_SEARCH); possibleScore.add(1); index++; HashMap<String, String> pv = new HashMap<String, String>(); //TODO: pass this down to avoid additional checking AbstractParameterSearch aps = new AbstractParameterSearch() .setParameters(PARAMETERS.WEBSEARCH_ENGINE, PARAMETERS.WEBSEARCH_REQUEST, PARAMETERS.SEARCH_SECTION) .setup(input, pv); aps.getParameters(); //possibleScore.set(index, possibleScore.get(index) + aps.getScore()); //Score stays always 1 possibleParameters.add(pv); } //DEMO Mode if (input.demoMode){ //you can put stuff here for demos } //--set certainty_lvl-- int bestScoreIndex = 0; if (possibleScore.size()>0){ int bestScore = Collections.max(possibleScore); int totalScore = 0; //kind'a stupid double loop but I found no better way to first get total score for (int i=0; i<possibleScore.size(); i++){ totalScore += possibleScore.get(i); } for (int i=0; i<possibleScore.size(); i++){ if (possibleScore.get(i) == bestScore){ bestScoreIndex = i; break; //take the first if scores are equal } } certainty_lvl = Math.round(((double) bestScore)/((double) totalScore)*100.0d)/100.0d; }else{ certainty_lvl = 0.0d; } //check if there was any result - if not add the no_result API if (possibleCMDs.isEmpty()){ possibleCMDs.add(CMD.NO_RESULT); possibleScore.add(1); HashMap<String, String> pv = new HashMap<String, String>(); pv.put("text", text); possibleParameters.add(pv); certainty_lvl = 1.0d; } //create the result with default constructor and add specific variables: NluResult result = new NluResult(possibleCMDs, possibleParameters, possibleScore, bestScoreIndex); result.certaintyLvl = certainty_lvl; //copy the default variables from input (like environment, mood etc.) and add input to result: result.setInput(input); result.normalizedText = text; //input has the real text, result has the normalized text //you can set some of the default result variables manually if the interpreter changes them: result.language = language; // might well be analyzed and changed by the interpreter, in this case here it must be English //result.context = context; // is auto-set inside the constructor to best command //result.mood = mood; // typically only APIs change the mood return result; } public double getCertaintyLevel(NluResult result) { return result.certaintyLvl; } //TODO: what follows is old legacy code that should be replaced with the Parameter system soon! ... /** * Search for locations once. If it has been done already this method does nothing. * @param text - complete text to search * @param language - language code */ private void search_locations(String text, String language){ if (locations == null){ locations = RegexParameterSearch.get_locations(text, language); } } /** * Search for dates once. If it has been done already this method does nothing. * @param text - complete text to search * @param language - language code */ private void search_dates(String text, String language){ if (dates == null && locations != null){ dates = new HashMap<String, String>(); dates.put("date_tag", locations.get("travel_time")); } else if (dates == null){ dates = RegexParameterSearch.get_date(text, language); } } /** * Search for numbers once. If it has been done already this method does nothing. * @param text - complete text to search * @param language - language code */ private void search_numbers(String text, String language){ if (numbers == null){ String num = RegexParameterSearch.get_number(text); numbers = new HashMap<String, String>(); numbers.put("value1", num); } } /** * Get the vehicle search parameters price/power/age/color. * uses: vehicle_age, vehicle_color, vehicle_price, vehicle_price_t, vehicle_power, vehicle_power_t * @param text - complete text to search * @param language - language code */ private void search_vehicle_parameters(String text, String language){ if (vehicle_parameters == null){ Map<String, String> map = new HashMap<>(); String age; String price, price_t; String color; String power, power_t; String distance, distance_t; if (retail_parameters != null){ age = retail_parameters.get("age"); price = retail_parameters.get("price"); price_t = retail_parameters.get("price_t"); color = retail_parameters.get("color"); }else{ map = RegexParameterSearch.get_age(text, language); //TODO: fails for "with a price of 2000 euro made in 1999" age = map.get("age_y"); color = RegexParameterSearch.get_color(text, language).replaceFirst("\\s.*", "").trim(); map = RegexParameterSearch.get_amount_of(text, "money", language); price = map.get("amount"); price_t = map.get("type"); } map = RegexParameterSearch.get_amount_of(text, "power", language); power = map.get("amount"); power_t = map.get("type"); map = RegexParameterSearch.get_amount_of(text, "distance", language); distance = map.get("amount"); distance_t = map.get("type"); vehicle_parameters = new HashMap<String, String>(); vehicle_parameters.put("vehicle_age", age); vehicle_parameters.put("vehicle_color", color); vehicle_parameters.put("vehicle_price", price); vehicle_parameters.put("vehicle_price_t", price_t); vehicle_parameters.put("vehicle_power", power); vehicle_parameters.put("vehicle_power_t", power_t); vehicle_parameters.put("vehicle_distance", distance); vehicle_parameters.put("vehicle_distance_t", distance_t); //Debugger.printHM_SS(vehicle_parameters); //debug } } /** * Get the retail search parameters price/age/color. * uses: age, color, price, price_t * @param text - complete text to search * @param language - language code */ private void search_retail_parameters(String text, String language){ if (retail_parameters == null){ String age; String price, price_t; String color; Map<String, String> map = new HashMap<>(); if (vehicle_parameters != null){ age = vehicle_parameters.get("vehicle_age"); price = vehicle_parameters.get("vehicle_price"); price_t = vehicle_parameters.get("vehicle_price_t"); color = vehicle_parameters.get("vehicle_color"); }else{ map = RegexParameterSearch.get_age(text, language); //TODO: fails for "with a price of 2000 euro made in 1999" age = map.get("age_y"); map = RegexParameterSearch.get_amount_of(text, "money", language); price = map.get("amount"); price_t = map.get("type"); color = RegexParameterSearch.get_color(text, language).replaceFirst("\\s.*", "").trim(); } retail_parameters = new HashMap<String, String>(); retail_parameters.put("age", age); retail_parameters.put("color", color); retail_parameters.put("price", price); retail_parameters.put("price_t", price_t); //Debugger.printHM_SS(vehicle_parameters); //debug } } }
package com.ss.editor.control.transform; import static com.ss.rlib.util.ObjectUtils.notNull; import static java.util.Objects.requireNonNull; import com.jme3.collision.CollisionResult; import com.jme3.input.InputManager; import com.jme3.math.Quaternion; import com.jme3.math.Transform; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.control.AbstractControl; import com.ss.editor.Editor; import com.ss.editor.control.transform.SceneEditorControl.PickedAxis; import org.jetbrains.annotations.NotNull; import com.ss.rlib.logging.Logger; import com.ss.rlib.logging.LoggerManager; /** * The implementation of the scaling controller. * * @author JavaSaBr */ public class ScaleToolControl extends AbstractControl implements TransformControl { /** * The constant LOGGER. */ @NotNull protected static final Logger LOGGER = LoggerManager.getLogger(MoveToolControl.class); private static final String NODE_SCALE_X = "scale_x"; private static final String NODE_SCALE_Y = "scale_y"; private static final String NODE_SCALE_Z = "scale_z"; @NotNull private static final Editor EDITOR = Editor.getInstance(); /** * The scene editor controller. */ @NotNull private final SceneEditorControl editorControl; /** * The collision plane. */ @NotNull private final Node collisionPlane; /** * Instantiates a new Scale tool controller. * * @param editorControl the editor controller */ public ScaleToolControl(@NotNull final SceneEditorControl editorControl) { this.editorControl = editorControl; this.collisionPlane = notNull(editorControl.getCollisionPlane()); } /** * @return the collision plane. */ @NotNull private Node getCollisionPlane() { return collisionPlane; } /** * @return the scene editor controller. */ @NotNull private SceneEditorControl getEditorControl() { return editorControl; } @Override public void setCollisionPlane(@NotNull final CollisionResult colResult) { final Camera camera = EDITOR.getCamera(); final SceneEditorControl editorControl = getEditorControl(); final Transform transformCenter = editorControl.getTransformCenter(); if (transformCenter == null) { LOGGER.warning(this, "not found transform center for the " + editorControl); return; } // Set PickedAxis final Geometry geometry = colResult.getGeometry(); final String geometryName = geometry.getName(); if (geometryName.contains(NODE_SCALE_X)) { editorControl.setPickedAxis(PickedAxis.X); } else if (geometryName.contains(NODE_SCALE_Y)) { editorControl.setPickedAxis(PickedAxis.Y); } else if (geometryName.contains(NODE_SCALE_Z)) { editorControl.setPickedAxis(PickedAxis.Z); } // set the collision Plane location and rotation final Node collisionPlane = getCollisionPlane(); collisionPlane.setLocalTranslation(transformCenter.getTranslation()); final Quaternion rotation = collisionPlane.getLocalRotation(); rotation.lookAt(camera.getDirection(), Vector3f.UNIT_Y); //equals to angleZ collisionPlane.setLocalRotation(rotation); } @Override public void processTransform() { final SceneEditorControl editorControl = getEditorControl(); final Camera camera = EDITOR.getCamera(); final InputManager inputManager = EDITOR.getInputManager(); final Transform transformCenter = requireNonNull(editorControl.getTransformCenter()); // cursor position and selected position vectors final Vector2f cursorPos = new Vector2f(inputManager.getCursorPosition()); final Vector3f vectorScreenSelected = camera.getScreenCoordinates(transformCenter.getTranslation()); final Vector2f selectedCoords = new Vector2f(vectorScreenSelected.getX(), vectorScreenSelected.getY()); //set new deltaVector if it's not set (scale tool stores position of a cursor) if (editorControl.getDeltaVector() == null) { final Vector2f deltaVecPos = new Vector2f(cursorPos.getX(), cursorPos.getY()); editorControl.setDeltaVector(new Vector3f(deltaVecPos.getX(), deltaVecPos.getY(), 0)); } // Picked vector PickedAxis pickedAxis = editorControl.getPickedAxis(); Vector3f pickedVec = Vector3f.UNIT_X; if (pickedAxis == PickedAxis.Y) { pickedVec = Vector3f.UNIT_Y; } else if (pickedAxis == PickedAxis.Z) { pickedVec = Vector3f.UNIT_Z; } // scale according to distance final Vector3f deltaVector = editorControl.getDeltaVector(); final Vector2f delta2d = new Vector2f(deltaVector.getX(), deltaVector.getY()); final Vector3f baseScale = transformCenter.getScale().clone(); // default scale // scale object float disCursor = cursorPos.distance(selectedCoords); float disDelta = delta2d.distance(selectedCoords); float scaleValue = cursorPos.distance(delta2d); scaleValue = TransformConstraint.constraintValue(scaleValue * 0.007f, TransformConstraint.getScaleConstraint()); Vector3f scaleVector = null; if (disCursor > disDelta) { scaleVector = baseScale.add(pickedVec.mult(scaleValue)); } else { scaleValue = Math.min(scaleValue, 0.999f); // remove negateve values scaleVector = baseScale.subtract(pickedVec.mult((scaleValue))); } final Spatial toTransform = requireNonNull(editorControl.getToTransform()); toTransform.setLocalScale(scaleVector); editorControl.notifyTransformed(toTransform); } @Override protected void controlUpdate(final float tpf) { } @Override protected void controlRender(@NotNull final RenderManager renderManager, @NotNull final ViewPort viewPort) { } }
package com.salesmore.yak.integration.shopee.model.common; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum OrderStatus { UNRECOGNIZED, UNPAID, READY_TO_SHIP, RETRY_SHIP, SHIPPED, TO_CONFIRM_RECEIVE, IN_CANCEL, CANCELLED, TO_RETURN, COMPLETED; @JsonCreator public static OrderStatus value(String v) { if (v == null) return UNRECOGNIZED; try { return valueOf(v.toUpperCase()); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } } @JsonValue public String value() { return name().toUpperCase(); } }
/* * Copyright 2002-2020 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 * * 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 org.springframework.beans.factory.support; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationNotAllowedException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.core.SimpleAliasRegistry; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Generic registry for shared bean instances, implementing the * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}. * Allows for registering singleton instances that should be shared * for all callers of the registry, to be obtained via bean name. * * <p>Also supports registration of * {@link org.springframework.beans.factory.DisposableBean} instances, * (which might or might not correspond to registered singletons), * to be destroyed on shutdown of the registry. Dependencies between * beans can be registered to enforce an appropriate shutdown order. * * <p>This class mainly serves as base class for * {@link org.springframework.beans.factory.BeanFactory} implementations, * factoring out the common management of singleton bean instances. Note that * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} * interface extends the {@link SingletonBeanRegistry} interface. * * <p>Note that this class assumes neither a bean definition concept * nor a specific creation process for bean instances, in contrast to * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory} * (which inherit from it). Can alternatively also be used as a nested * helper to delegate to. * * @author Juergen Hoeller * @since 2.0 * @see #registerSingleton * @see #registerDisposableBean * @see org.springframework.beans.factory.DisposableBean * @see org.springframework.beans.factory.config.ConfigurableBeanFactory */ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { /** Maximum number of suppressed exceptions to preserve. */ private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100; /** Cache of singleton objects: bean name to bean instance. */ /** * 存放的是创建并且初始化完成的Bean吗?是,拿来就可以用的 * 这是一级缓存 * 这各级缓存是为谁服务的??? * environment : StandardServletEnvironment * systemProperties * systemEnvironment *servletContext ApplicationContextFacade *contextParameters Map 包含的值classpath:spring/spring-*.xml * messageSource DelegatingMessageSource * applicationEventMulticaster SimpleApplicationEventMulticaster * * FactoryBean 创建的Object 不会放在这里? * */ private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); /** Cache of singleton factories: bean name to ObjectFactory. */ /** * org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping :AbstractAutowireCapableBeanFactory getEarlyBeanReference() * ObjectFactory 用于创建对象 这是起到缓存的作用 提早暴露出单例,为了解决循环引用 * 在 AbstractAutowireCapableBeanFactory 的 doCreateBean 中有调用 * 这是三级缓存 */ private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16); /** Cache of early singleton objects: bean name to bean instance. * * 这是二级缓存 * 二级和三级缓存的区别是什么??? * */ private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16); /** Set of registered singletons, containing the bean names in registration order. */ /** * 保存注册了的bean 的名称 * environment * systemProperties * systemEnvironment * servletContext * contextParameters */ private final Set<String> registeredSingletons = new LinkedHashSet<>(256); /** Names of beans that are currently in creation. */ private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); /** Names of beans currently excluded from in creation checks. */ private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>(16)); /** Collection of suppressed Exceptions, available for associating related causes. */ @Nullable private Set<Exception> suppressedExceptions; /** Flag that indicates whether we're currently within destroySingletons. */ private boolean singletonsCurrentlyInDestruction = false; /** Disposable bean instances: bean name to disposable instance. */ private final Map<String, Object> disposableBeans = new LinkedHashMap<>(); /** Map between containing bean names: bean name to Set of bean names that the bean contains. */ private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16); /** Map between dependent bean names: bean name to Set of dependent bean names. */ //记录 依赖 beanName 的 dependentBeanName private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64); /** Map between depending bean names: bean name to Set of bean names for the bean's dependencies. */ //记录 dependentBeanName 依赖的 beanName private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64); @Override public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { //手动注册 singleton Assert.notNull(beanName, "Bean name must not be null"); Assert.notNull(singletonObject, "Singleton object must not be null"); synchronized (this.singletonObjects) { Object oldObject = this.singletonObjects.get(beanName); if (oldObject != null) { throw new IllegalStateException("Could not register object [" + singletonObject + "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound"); } addSingleton(beanName, singletonObject); } } /** * Add the given singleton object to the singleton cache of this factory. * <p>To be called for eager registration of singletons. * @param beanName the name of the bean * @param singletonObject the singleton object */ protected void addSingleton(String beanName, Object singletonObject) { synchronized (this.singletonObjects) { //一级缓存添加 this.singletonObjects.put(beanName, singletonObject); //三级缓存移除 this.singletonFactories.remove(beanName); //二级缓存移除 this.earlySingletonObjects.remove(beanName); // this.registeredSingletons.add(beanName); } } /** * Add the given singleton factory for building the specified singleton * if necessary. * <p>To be called for eager registration of singletons, e.g. to be able to * resolve circular references. * @param beanName the name of the bean * @param singletonFactory the factory for the singleton object */ protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { //这个方法是在 doCreateBean() 在对象已经被实例化(但还没有初始化)后调用的 Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { //没有把 beanName 放到 singletonObjects 中 if (!this.singletonObjects.containsKey(beanName)) { //一级缓存中还没有 //加入三级缓存,这个 singletonFactory 是 ObjectFactory ,逻辑上它可以对返回的对象做任何处理,比如生成一个代理对象返回 this.singletonFactories.put(beanName, singletonFactory); //earlySingletonObjects 是什么时候放进去的?从一级缓存实例化后放进去的,此处为何要移除掉???移除二级缓存 this.earlySingletonObjects.remove(beanName); //这个的作用又是什么呢??? this.registeredSingletons.add(beanName); } } } @Override @Nullable public Object getSingleton(String beanName) { return getSingleton(beanName, true); } /** * Return the (raw) singleton object registered under the given name. * <p>Checks already instantiated singletons and also allows for an early * reference to a currently created singleton (resolving a circular reference). * @param beanName the name of the bean to look for * @param allowEarlyReference whether early references should be created or not * 是否创建对象,提前暴露,此对象还不是完全体,只能从三级缓存的工厂来创建 * todo:三级缓存和这里有什么联系呢? * @return the registered singleton object, or {@code null} if none found */ @Nullable protected Object getSingleton(String beanName, boolean allowEarlyReference) { // Quick check for existing instance without full singleton lock //取完全体的bean对象 Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { //当前Bean正在创建的过程中 //从二级缓存中取,这里的对象是只调用过构造方法,还未初始化吗? singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { //二级缓存中也没有,允许提前引用? synchronized (this.singletonObjects) { // Consistent creation of early reference within full singleton lock singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null) { //调用对象构造工厂,这些工厂是怎么时候放进去的? ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { //从对象工厂获取实例 singletonObject = singletonFactory.getObject(); //将其放到二级缓存中 this.earlySingletonObjects.put(beanName, singletonObject); //将对象工厂移除掉 this.singletonFactories.remove(beanName); } } } } } } return singletonObject; } /** * Return the (raw) singleton object registered under the given name, * creating and registering a new one if none registered yet. * @param beanName the name of the bean * @param singletonFactory the ObjectFactory to lazily create the singleton * with, if necessary * @return the registered singleton object */ public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { //再次查缓存 Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); } //添加到 singletonsCurrentlyInCreation beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try { //调用 createBean singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } //从singletonsCurrentlyInCreation 中移除 afterSingletonCreation(beanName); } if (newSingleton) { //新的单例,添加到一级缓存中 这个对象是完全体的 addSingleton(beanName, singletonObject); } } return singletonObject; } } /** * Register an exception that happened to get suppressed during the creation of a * singleton bean instance, e.g. a temporary circular reference resolution problem. * <p>The default implementation preserves any given exception in this registry's * collection of suppressed exceptions, up to a limit of 100 exceptions, adding * them as related causes to an eventual top-level {@link BeanCreationException}. * @param ex the Exception to register * @see BeanCreationException#getRelatedCauses() */ protected void onSuppressedException(Exception ex) { synchronized (this.singletonObjects) { if (this.suppressedExceptions != null && this.suppressedExceptions.size() < SUPPRESSED_EXCEPTIONS_LIMIT) { this.suppressedExceptions.add(ex); } } } /** * Remove the bean with the given name from the singleton cache of this factory, * to be able to clean up eager registration of a singleton if creation failed. * @param beanName the name of the bean * @see #getSingletonMutex() */ protected void removeSingleton(String beanName) { synchronized (this.singletonObjects) { this.singletonObjects.remove(beanName); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.remove(beanName); } } @Override public boolean containsSingleton(String beanName) { return this.singletonObjects.containsKey(beanName); } @Override public String[] getSingletonNames() { synchronized (this.singletonObjects) { return StringUtils.toStringArray(this.registeredSingletons); } } @Override public int getSingletonCount() { synchronized (this.singletonObjects) { return this.registeredSingletons.size(); } } public void setCurrentlyInCreation(String beanName, boolean inCreation) { Assert.notNull(beanName, "Bean name must not be null"); if (!inCreation) { this.inCreationCheckExclusions.add(beanName); } else { this.inCreationCheckExclusions.remove(beanName); } } public boolean isCurrentlyInCreation(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName)); } protected boolean isActuallyInCreation(String beanName) { return isSingletonCurrentlyInCreation(beanName); } /** * Return whether the specified singleton bean is currently in creation * (within the entire factory). * @param beanName the name of the bean */ public boolean isSingletonCurrentlyInCreation(String beanName) { return this.singletonsCurrentlyInCreation.contains(beanName); } /** * Callback before singleton creation. * <p>The default implementation register the singleton as currently in creation. * @param beanName the name of the singleton about to be created * @see #isSingletonCurrentlyInCreation */ protected void beforeSingletonCreation(String beanName) { if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } } /** * Callback after singleton creation. * <p>The default implementation marks the singleton as not in creation anymore. * @param beanName the name of the singleton that has been created * @see #isSingletonCurrentlyInCreation */ protected void afterSingletonCreation(String beanName) { if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) { throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation"); } } /** * Add the given bean to the list of disposable beans in this registry. * <p>Disposable beans usually correspond to registered singletons, * matching the bean name but potentially being a different instance * (for example, a DisposableBean adapter for a singleton that does not * naturally implement Spring's DisposableBean interface). * @param beanName the name of the bean * @param bean the bean instance */ public void registerDisposableBean(String beanName, DisposableBean bean) { synchronized (this.disposableBeans) { this.disposableBeans.put(beanName, bean); } } /** * Register a containment relationship between two beans, * e.g. between an inner bean and its containing outer bean. * <p>Also registers the containing bean as dependent on the contained bean * in terms of destruction order. * @param containedBeanName the name of the contained (inner) bean * @param containingBeanName the name of the containing (outer) bean * @see #registerDependentBean */ public void registerContainedBean(String containedBeanName, String containingBeanName) { synchronized (this.containedBeanMap) { Set<String> containedBeans = this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8)); if (!containedBeans.add(containedBeanName)) { return; } } registerDependentBean(containedBeanName, containingBeanName); } /** * Register a dependent bean for the given bean, * to be destroyed before the given bean is destroyed. * @param beanName the name of the bean * @param dependentBeanName the name of the dependent bean */ public void registerDependentBean(String beanName, String dependentBeanName) { //是 dependentBeanName 依赖 beanName? String canonicalName = canonicalName(beanName); synchronized (this.dependentBeanMap) { //dependentBeanMap 记录 依赖 beanName 的 dependentBeanName Set<String> dependentBeans = this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8)); if (!dependentBeans.add(dependentBeanName)) { return; } } synchronized (this.dependenciesForBeanMap) { //dependenciesForBeanMap 记录 dependentBeanName 依赖的 beanName Set<String> dependenciesForBean = this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8)); dependenciesForBean.add(canonicalName); } } /** * Determine whether the specified dependent bean has been registered as * dependent on the given bean or on any of its transitive dependencies. * @param beanName the name of the bean to check * @param dependentBeanName the name of the dependent bean * @since 4.0 */ protected boolean isDependent(String beanName, String dependentBeanName) { synchronized (this.dependentBeanMap) { return isDependent(beanName, dependentBeanName, null); } } private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) { if (alreadySeen != null && alreadySeen.contains(beanName)) { return false; } String canonicalName = canonicalName(beanName); Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName); if (dependentBeans == null) { return false; } if (dependentBeans.contains(dependentBeanName)) { return true; } for (String transitiveDependency : dependentBeans) { if (alreadySeen == null) { alreadySeen = new HashSet<>(); } alreadySeen.add(beanName); if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { return true; } } return false; } /** * Determine whether a dependent bean has been registered for the given name. * @param beanName the name of the bean to check */ protected boolean hasDependentBean(String beanName) { return this.dependentBeanMap.containsKey(beanName); } /** * Return the names of all beans which depend on the specified bean, if any. * @param beanName the name of the bean * @return the array of dependent bean names, or an empty array if none */ public String[] getDependentBeans(String beanName) { Set<String> dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { return new String[0]; } synchronized (this.dependentBeanMap) { return StringUtils.toStringArray(dependentBeans); } } /** * Return the names of all beans that the specified bean depends on, if any. * @param beanName the name of the bean * @return the array of names of beans which the bean depends on, * or an empty array if none */ public String[] getDependenciesForBean(String beanName) { Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName); if (dependenciesForBean == null) { return new String[0]; } synchronized (this.dependenciesForBeanMap) { return StringUtils.toStringArray(dependenciesForBean); } } public void destroySingletons() { if (logger.isTraceEnabled()) { logger.trace("Destroying singletons in " + this); } synchronized (this.singletonObjects) { this.singletonsCurrentlyInDestruction = true; } String[] disposableBeanNames; synchronized (this.disposableBeans) { disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet()); } for (int i = disposableBeanNames.length - 1; i >= 0; i--) { destroySingleton(disposableBeanNames[i]); } this.containedBeanMap.clear(); this.dependentBeanMap.clear(); this.dependenciesForBeanMap.clear(); clearSingletonCache(); } /** * Clear all cached singleton instances in this registry. * @since 4.3.15 */ protected void clearSingletonCache() { synchronized (this.singletonObjects) { this.singletonObjects.clear(); this.singletonFactories.clear(); this.earlySingletonObjects.clear(); this.registeredSingletons.clear(); this.singletonsCurrentlyInDestruction = false; } } /** * Destroy the given bean. Delegates to {@code destroyBean} * if a corresponding disposable bean instance is found. * @param beanName the name of the bean * @see #destroyBean */ public void destroySingleton(String beanName) { // Remove a registered singleton of the given name, if any. removeSingleton(beanName); // Destroy the corresponding DisposableBean instance. DisposableBean disposableBean; synchronized (this.disposableBeans) { disposableBean = (DisposableBean) this.disposableBeans.remove(beanName); } destroyBean(beanName, disposableBean); } /** * Destroy the given bean. Must destroy beans that depend on the given * bean before the bean itself. Should not throw any exceptions. * @param beanName the name of the bean * @param bean the bean instance to destroy */ protected void destroyBean(String beanName, @Nullable DisposableBean bean) { // Trigger destruction of dependent beans first... Set<String> dependencies; synchronized (this.dependentBeanMap) { // Within full synchronization in order to guarantee a disconnected Set dependencies = this.dependentBeanMap.remove(beanName); } if (dependencies != null) { if (logger.isTraceEnabled()) { logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies); } for (String dependentBeanName : dependencies) { destroySingleton(dependentBeanName); } } // Actually destroy the bean now... if (bean != null) { try { bean.destroy(); } catch (Throwable ex) { if (logger.isWarnEnabled()) { logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex); } } } // Trigger destruction of contained beans... Set<String> containedBeans; synchronized (this.containedBeanMap) { // Within full synchronization in order to guarantee a disconnected Set containedBeans = this.containedBeanMap.remove(beanName); } if (containedBeans != null) { for (String containedBeanName : containedBeans) { destroySingleton(containedBeanName); } } // Remove destroyed bean from other beans' dependencies. synchronized (this.dependentBeanMap) { for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Set<String>> entry = it.next(); Set<String> dependenciesToClean = entry.getValue(); dependenciesToClean.remove(beanName); if (dependenciesToClean.isEmpty()) { it.remove(); } } } // Remove destroyed bean's prepared dependency information. this.dependenciesForBeanMap.remove(beanName); } /** * Exposes the singleton mutex to subclasses and external collaborators. * <p>Subclasses should synchronize on the given Object if they perform * any sort of extended singleton creation phase. In particular, subclasses * should <i>not</i> have their own mutexes involved in singleton creation, * to avoid the potential for deadlocks in lazy-init situations. */ @Override public final Object getSingletonMutex() { return this.singletonObjects; } }