text
stringlengths
7
1.01M
package br.com.zupacademy.valteir.casadocodigo.repositories; import org.springframework.data.repository.CrudRepository; import br.com.zupacademy.valteir.casadocodigo.entities.Pais; public interface PaisRepository extends CrudRepository<Pais, Long>{ }
package monetdb.mapper.monitordb; import java.util.List; import monetdb.domain.monitordb.HistoryAI; import monetdb.domain.monitordb.HistoryAIExample; import org.apache.ibatis.annotations.Param; public interface HistoryAIMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int countByExample(HistoryAIExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int deleteByExample(HistoryAIExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int insert(HistoryAI record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int insertSelective(HistoryAI record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ List<HistoryAI> selectByExample(HistoryAIExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ HistoryAI selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int updateByExampleSelective(@Param("record") HistoryAI record, @Param("example") HistoryAIExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int updateByExample(@Param("record") HistoryAI record, @Param("example") HistoryAIExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int updateByPrimaryKeySelective(HistoryAI record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table monitordb.history_ai * * @mbggenerated Mon Jan 16 10:15:35 CST 2017 */ int updateByPrimaryKey(HistoryAI record); }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.requests.extensions.IDeviceAppManagementRequest; import com.microsoft.graph.requests.extensions.IManagedEBookCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedEBookRequestBuilder; import com.microsoft.graph.requests.extensions.IMobileAppCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IMobileAppRequestBuilder; import com.microsoft.graph.requests.extensions.IMobileAppCategoryCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IMobileAppCategoryRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedDeviceMobileAppConfigurationCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedDeviceMobileAppConfigurationRequestBuilder; import com.microsoft.graph.requests.extensions.IVppTokenCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IVppTokenRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppPolicyCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppPolicyRequestBuilder; import com.microsoft.graph.requests.extensions.IIosManagedAppProtectionCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IIosManagedAppProtectionRequestBuilder; import com.microsoft.graph.requests.extensions.IAndroidManagedAppProtectionCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IAndroidManagedAppProtectionRequestBuilder; import com.microsoft.graph.requests.extensions.IDefaultManagedAppProtectionCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IDefaultManagedAppProtectionRequestBuilder; import com.microsoft.graph.requests.extensions.ITargetedManagedAppConfigurationCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.ITargetedManagedAppConfigurationRequestBuilder; import com.microsoft.graph.requests.extensions.IMdmWindowsInformationProtectionPolicyCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IMdmWindowsInformationProtectionPolicyRequestBuilder; import com.microsoft.graph.requests.extensions.IWindowsInformationProtectionPolicyCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IWindowsInformationProtectionPolicyRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppRegistrationCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppRegistrationRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppStatusCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IManagedAppStatusRequestBuilder; import com.microsoft.graph.requests.extensions.IDeviceAppManagementSyncMicrosoftStoreForBusinessAppsRequestBuilder; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.options.Option; import java.util.EnumSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Device App Management Request Builder. */ public interface IDeviceAppManagementRequestBuilder extends IRequestBuilder { /** * Creates the request * * @return the IDeviceAppManagementRequest instance */ IDeviceAppManagementRequest buildRequest(); /** * Creates the request with specific options instead of the existing options * * @param requestOptions the options for this request * @return the IDeviceAppManagementRequest instance */ IDeviceAppManagementRequest buildRequest(final java.util.List<? extends Option> requestOptions); IManagedEBookCollectionRequestBuilder managedEBooks(); IManagedEBookRequestBuilder managedEBooks(final String id); IMobileAppCollectionRequestBuilder mobileApps(); IMobileAppRequestBuilder mobileApps(final String id); IMobileAppCategoryCollectionRequestBuilder mobileAppCategories(); IMobileAppCategoryRequestBuilder mobileAppCategories(final String id); IManagedDeviceMobileAppConfigurationCollectionRequestBuilder mobileAppConfigurations(); IManagedDeviceMobileAppConfigurationRequestBuilder mobileAppConfigurations(final String id); IVppTokenCollectionRequestBuilder vppTokens(); IVppTokenRequestBuilder vppTokens(final String id); IManagedAppPolicyCollectionRequestBuilder managedAppPolicies(); IManagedAppPolicyRequestBuilder managedAppPolicies(final String id); IIosManagedAppProtectionCollectionRequestBuilder iosManagedAppProtections(); IIosManagedAppProtectionRequestBuilder iosManagedAppProtections(final String id); IAndroidManagedAppProtectionCollectionRequestBuilder androidManagedAppProtections(); IAndroidManagedAppProtectionRequestBuilder androidManagedAppProtections(final String id); IDefaultManagedAppProtectionCollectionRequestBuilder defaultManagedAppProtections(); IDefaultManagedAppProtectionRequestBuilder defaultManagedAppProtections(final String id); ITargetedManagedAppConfigurationCollectionRequestBuilder targetedManagedAppConfigurations(); ITargetedManagedAppConfigurationRequestBuilder targetedManagedAppConfigurations(final String id); IMdmWindowsInformationProtectionPolicyCollectionRequestBuilder mdmWindowsInformationProtectionPolicies(); IMdmWindowsInformationProtectionPolicyRequestBuilder mdmWindowsInformationProtectionPolicies(final String id); IWindowsInformationProtectionPolicyCollectionRequestBuilder windowsInformationProtectionPolicies(); IWindowsInformationProtectionPolicyRequestBuilder windowsInformationProtectionPolicies(final String id); IManagedAppRegistrationCollectionRequestBuilder managedAppRegistrations(); IManagedAppRegistrationRequestBuilder managedAppRegistrations(final String id); IManagedAppStatusCollectionRequestBuilder managedAppStatuses(); IManagedAppStatusRequestBuilder managedAppStatuses(final String id); IDeviceAppManagementSyncMicrosoftStoreForBusinessAppsRequestBuilder syncMicrosoftStoreForBusinessApps(); }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE129_Improper_Validation_of_Array_Index__Environment_array_write_no_check_74b.java Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml Template File: sources-sinks-74b.tmpl.java */ /* * @description * CWE: 129 Improper Validation of Array Index * BadSource: Environment Read data from an environment variable * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: array_write_no_check * GoodSink: Write to array after verifying index * BadSink : Write to array without any verification of index * Flow Variant: 74 Data flow: data passed in a HashMap from one method to another in different source files in the same package * * */ import java.util.HashMap; public class CWE129_Improper_Validation_of_Array_Index__Environment_array_write_no_check_74b { public void badSink(HashMap<Integer,Integer> dataHashMap ) throws Throwable { int data = dataHashMap.get(2); /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } /* goodG2B() - use GoodSource and BadSink */ public void goodG2BSink(HashMap<Integer,Integer> dataHashMap ) throws Throwable { int data = dataHashMap.get(2); /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } /* goodB2G() - use BadSource and GoodSink */ public void goodB2GSink(HashMap<Integer,Integer> dataHashMap ) throws Throwable { int data = dataHashMap.get(2); /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } }
package com.example.doodle.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.doodle.R; import com.example.doodle.models.ColorViewModel; import org.jetbrains.annotations.NotNull; public class ColorPickerFragment extends Fragment { public static final String TAG = "ColorPickerFragment"; // Views in the layout private Button pinkButton; private Button redButton; private Button orangeButton; private Button yellowOrangeButton; private Button yellowButton; private Button lightGreenButton; private Button darkGreenButton; private Button tealButton; private Button lightBlueButton; private Button darkBlueButton; private Button purpleButton; private Button brownButton; private Button greyButton; private Button blackButton; // Other necessary member variables private ViewModelProvider viewModelProvider; private ColorViewModel colorViewModel; private int currentColorButtonId; private int currentColorStateListId; public ColorPickerFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_color_picker, container, false); } @Override public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Initialize the views in the layout pinkButton = view.findViewById(R.id.pinkButton); redButton = view.findViewById(R.id.redButton); orangeButton = view.findViewById(R.id.orangeButton); yellowOrangeButton = view.findViewById(R.id.yellowOrangeButton); yellowButton = view.findViewById(R.id.yellowButton); lightGreenButton = view.findViewById(R.id.lightGreenButton); darkGreenButton = view.findViewById(R.id.darkGreenButton); tealButton = view.findViewById(R.id.tealButton); lightBlueButton = view.findViewById(R.id.lightBlueButton); darkBlueButton = view.findViewById(R.id.darkBlueButton); purpleButton = view.findViewById(R.id.purpleButton); brownButton = view.findViewById(R.id.brownButton); greyButton = view.findViewById(R.id.greyButton); blackButton = view.findViewById(R.id.blackButton); // Initialize other member variables // Set up view model viewModelProvider = new ViewModelProvider(requireActivity()); colorViewModel = viewModelProvider.get(ColorViewModel.class); currentColorButtonId = colorViewModel.getSelectedColorButtonId().getValue(); currentColorStateListId = colorViewModel.getSelectedColorId().getValue(); // Set up click listeners for each color button pinkButton.setOnClickListener(v -> handleClick(pinkButton, R.color.button_pink)); redButton.setOnClickListener(v -> handleClick(redButton, R.color.button_red)); orangeButton.setOnClickListener(v -> handleClick(orangeButton, R.color.button_orange)); yellowOrangeButton.setOnClickListener(v -> handleClick(yellowOrangeButton, R.color.button_yellow_orange)); yellowButton.setOnClickListener(v -> handleClick(yellowButton, R.color.button_yellow)); lightGreenButton.setOnClickListener(v -> handleClick(lightGreenButton, R.color.button_light_green)); darkGreenButton.setOnClickListener(v -> handleClick(darkGreenButton, R.color.button_dark_green)); tealButton.setOnClickListener(v -> handleClick(tealButton, R.color.button_teal)); lightBlueButton.setOnClickListener(v -> handleClick(lightBlueButton, R.color.button_light_blue)); darkBlueButton.setOnClickListener(v -> handleClick(darkBlueButton, R.color.button_dark_blue)); purpleButton.setOnClickListener(v -> handleClick(purpleButton, R.color.button_purple)); brownButton.setOnClickListener(v -> handleClick(brownButton, R.color.button_brown)); greyButton.setOnClickListener(v -> handleClick(greyButton, R.color.button_grey)); blackButton.setOnClickListener(v -> handleClick(blackButton, R.color.button_black)); // Make sure current color is selected view.findViewById(currentColorButtonId).callOnClick(); } // Makes the currently selected button have the foreground icon public void handleClick(Button button, int colorStateListId) { // Set the new values in the ViewModel colorViewModel.selectColorButton(button.getId()); colorViewModel.selectColor(colorStateListId); // Hide the icon on the previously selected button getView().findViewById(currentColorButtonId).setForeground(null); // Update the current button and color currentColorButtonId = button.getId(); currentColorStateListId = colorStateListId; // Display the icon on the newly selected button button.setForeground(getResources().getDrawable(R.drawable.transparent_circle_indicator, getActivity().getTheme())); } }
package com.mq.testbedconsumers.rabbit; import java.io.IOException; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import lombok.extern.slf4j.Slf4j; @Slf4j @Configuration @ConditionalOnProperty(prefix = "testing", value = "mq", havingValue = "rabbit") public class RabbitConfig { static final String topicExchangeName = "spring-boot-exchange"; static final String queueName = "spring-boot"; @Value("${rabbit.host}") public String hostName; @Value("${rabbit.port}") public String hostPort; @Value("${rabbit.user}") public String userName; @Value("${rabbit.password}") public String password; @Value("${rabbit.sse-enabled}") public boolean sseEnabled; /** * Establish a connection to a rabbit mq server. * @return Rabbit connection factory for rabbitmq access. * @throws IOException If wrong parameters are used for connection. */ @Bean public RabbitConnectionFactoryBean connectionFactoryBean() throws IOException { RabbitConnectionFactoryBean connectionFactoryBean = new RabbitConnectionFactoryBean(); connectionFactoryBean.setHost(hostName); connectionFactoryBean.setPort(Integer.valueOf(hostPort)); connectionFactoryBean.setUsername(userName); connectionFactoryBean.setPassword(password); return connectionFactoryBean; } /** * Connection factory which established a rabbitmq connection used from a connection factory * @param connectionFactoryBean Connection factory bean to create connection. * @return A connection factory to create connections. * @throws Exception If wrong parameters are used for connection. */ @Bean(name = "LEDGER_1") public ConnectionFactory connectionFactory(RabbitConnectionFactoryBean connectionFactoryBean) throws Exception { return new CachingConnectionFactory(connectionFactoryBean.getObject()); } @Bean SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames(queueName); container.setMessageListener(listenerAdapter); return container; } @Bean MessageListenerAdapter listenerAdapter(RabbitConsumer consumer) { return new MessageListenerAdapter(consumer, "receiveMessage"); } }
package org.apereo.cas; import org.apereo.cas.memcached.MemcachedPooledClientConnectionFactoryTests; import org.apereo.cas.memcached.MemcachedUtilsTests; import org.apereo.cas.memcached.kryo.CasKryoPoolTests; import org.apereo.cas.memcached.kryo.CasKryoTranscoderTests; import org.apereo.cas.memcached.kryo.ZonedDateTimeSerializerTests; import org.apereo.cas.memcached.kryo.serial.ImmutableNativeJavaListSerializerTests; import org.apereo.cas.memcached.kryo.serial.ImmutableNativeJavaMapSerializerTests; import org.apereo.cas.memcached.kryo.serial.ImmutableNativeJavaSetSerializerTests; import org.apereo.cas.memcached.kryo.serial.URLSerializerTests; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; /** * This is {@link MemcachedCoreTestsSuite}. * * @author Misagh Moayyed * @since 6.0.0 */ @SelectClasses({ CasKryoTranscoderTests.class, MemcachedUtilsTests.class, URLSerializerTests.class, CasKryoPoolTests.class, ImmutableNativeJavaMapSerializerTests.class, ImmutableNativeJavaListSerializerTests.class, ImmutableNativeJavaSetSerializerTests.class, MemcachedPooledClientConnectionFactoryTests.class, ZonedDateTimeSerializerTests.class }) @Suite public class MemcachedCoreTestsSuite { }
package com.mojang.blaze3d.platform; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mojang.blaze3d.systems.RenderSystem; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.LongSupplier; import java.util.function.Supplier; import net.minecraft.client.MainWindow; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlDebugTextUtils; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.Version; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWErrorCallbackI; import org.lwjgl.glfw.GLFWVidMode; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GLCapabilities; import oshi.SystemInfo; import oshi.hardware.Processor; @OnlyIn(Dist.CLIENT) public class GLX { private static final Logger LOGGER = LogManager.getLogger(); private static String capsString = ""; private static String cpuInfo; private static final Map<Integer, String> LOOKUP_MAP = make(Maps.newHashMap(), (p_229878_0_) -> { p_229878_0_.put(0, "No error"); p_229878_0_.put(1280, "Enum parameter is invalid for this function"); p_229878_0_.put(1281, "Parameter is invalid for this function"); p_229878_0_.put(1282, "Current state is invalid for this function"); p_229878_0_.put(1283, "Stack overflow"); p_229878_0_.put(1284, "Stack underflow"); p_229878_0_.put(1285, "Out of memory"); p_229878_0_.put(1286, "Operation on incomplete framebuffer"); p_229878_0_.put(1286, "Operation on incomplete framebuffer"); }); public static String getOpenGLVersionString() { RenderSystem.assertThread(RenderSystem::isOnRenderThread); return GLFW.glfwGetCurrentContext() == 0L ? "NO CONTEXT" : GlStateManager.getString(7937) + " GL version " + GlStateManager.getString(7938) + ", " + GlStateManager.getString(7936); } public static int _getRefreshRate(MainWindow p__getRefreshRate_0_) { RenderSystem.assertThread(RenderSystem::isOnRenderThread); long i = GLFW.glfwGetWindowMonitor(p__getRefreshRate_0_.getHandle()); if (i == 0L) { i = GLFW.glfwGetPrimaryMonitor(); } GLFWVidMode glfwvidmode = i == 0L ? null : GLFW.glfwGetVideoMode(i); return glfwvidmode == null ? 0 : glfwvidmode.refreshRate(); } public static String _getLWJGLVersion() { RenderSystem.assertThread(RenderSystem::isInInitPhase); return Version.getVersion(); } public static LongSupplier _initGlfw() { RenderSystem.assertThread(RenderSystem::isInInitPhase); MainWindow.checkGlfwError((p_229879_0_, p_229879_1_) -> { throw new IllegalStateException(String.format("GLFW error before init: [0x%X]%s", p_229879_0_, p_229879_1_)); }); List<String> list = Lists.newArrayList(); GLFWErrorCallback glfwerrorcallback = GLFW.glfwSetErrorCallback((p_229880_1_, p_229880_2_) -> { list.add(String.format("GLFW error during init: [0x%X]%s", p_229880_1_, p_229880_2_)); }); if (!GLFW.glfwInit()) { throw new IllegalStateException("Failed to initialize GLFW, errors: " + Joiner.on(",").join(list)); } else { LongSupplier longsupplier = () -> { return (long)(GLFW.glfwGetTime() * 1.0E9D); }; for(String s : list) { LOGGER.error("GLFW error collected during initialization: {}", (Object)s); } RenderSystem.setErrorCallback(glfwerrorcallback); return longsupplier; } } public static void _setGlfwErrorCallback(GLFWErrorCallbackI p__setGlfwErrorCallback_0_) { RenderSystem.assertThread(RenderSystem::isInInitPhase); GLFWErrorCallback glfwerrorcallback = GLFW.glfwSetErrorCallback(p__setGlfwErrorCallback_0_); if (glfwerrorcallback != null) { glfwerrorcallback.free(); } } public static boolean _shouldClose(MainWindow p__shouldClose_0_) { return GLFW.glfwWindowShouldClose(p__shouldClose_0_.getHandle()); } public static void _setupNvFogDistance() { RenderSystem.assertThread(RenderSystem::isOnRenderThread); if (GL.getCapabilities().GL_NV_fog_distance) { GlStateManager.fogi(34138, 34139); } } public static void _init(int p__init_0_, boolean p__init_1_) { RenderSystem.assertThread(RenderSystem::isInInitPhase); GLCapabilities glcapabilities = GL.getCapabilities(); capsString = "Using framebuffer using " + GlStateManager.init(glcapabilities); try { Processor[] aprocessor = (new SystemInfo()).getHardware().getProcessors(); cpuInfo = String.format("%dx %s", aprocessor.length, aprocessor[0]).replaceAll("\\s+", " "); } catch (Throwable var4) { ; } GlDebugTextUtils.setDebugVerbosity(p__init_0_, p__init_1_); } public static String _getCapsString() { return capsString; } public static String _getCpuInfo() { return cpuInfo == null ? "<unknown>" : cpuInfo; } public static void _renderCrosshair(int p__renderCrosshair_0_, boolean p__renderCrosshair_1_, boolean p__renderCrosshair_2_, boolean p__renderCrosshair_3_) { RenderSystem.assertThread(RenderSystem::isOnRenderThread); GlStateManager.disableTexture(); GlStateManager.depthMask(false); Tessellator tessellator = RenderSystem.renderThreadTesselator(); BufferBuilder bufferbuilder = tessellator.getBuffer(); GL11.glLineWidth(4.0F); bufferbuilder.begin(1, DefaultVertexFormats.POSITION_COLOR); if (p__renderCrosshair_1_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos((double)p__renderCrosshair_0_, 0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); } if (p__renderCrosshair_2_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos(0.0D, (double)p__renderCrosshair_0_, 0.0D).color(0, 0, 0, 255).endVertex(); } if (p__renderCrosshair_3_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos(0.0D, 0.0D, (double)p__renderCrosshair_0_).color(0, 0, 0, 255).endVertex(); } tessellator.draw(); GL11.glLineWidth(2.0F); bufferbuilder.begin(1, DefaultVertexFormats.POSITION_COLOR); if (p__renderCrosshair_1_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(255, 0, 0, 255).endVertex(); bufferbuilder.pos((double)p__renderCrosshair_0_, 0.0D, 0.0D).color(255, 0, 0, 255).endVertex(); } if (p__renderCrosshair_2_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(0, 255, 0, 255).endVertex(); bufferbuilder.pos(0.0D, (double)p__renderCrosshair_0_, 0.0D).color(0, 255, 0, 255).endVertex(); } if (p__renderCrosshair_3_) { bufferbuilder.pos(0.0D, 0.0D, 0.0D).color(127, 127, 255, 255).endVertex(); bufferbuilder.pos(0.0D, 0.0D, (double)p__renderCrosshair_0_).color(127, 127, 255, 255).endVertex(); } tessellator.draw(); GL11.glLineWidth(1.0F); GlStateManager.depthMask(true); GlStateManager.enableTexture(); } public static String getErrorString(int p_getErrorString_0_) { return LOOKUP_MAP.get(p_getErrorString_0_); } public static <T> T make(Supplier<T> p_make_0_) { return p_make_0_.get(); } public static <T> T make(T p_make_0_, Consumer<T> p_make_1_) { p_make_1_.accept(p_make_0_); return p_make_0_; } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.web.context.support; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.HttpRequestHandler; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.context.WebApplicationContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Simple HttpServlet that delegates to an {@link HttpRequestHandler} bean defined * in Spring's root web application context. The target bean name must match the * HttpRequestHandlerServlet servlet-name as defined in {@code web.xml}. * * <p>This can for example be used to expose a single Spring remote exporter, * such as {@link org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter} * or {@link org.springframework.remoting.caucho.HessianServiceExporter}, * per HttpRequestHandlerServlet definition. This is a minimal alternative * to defining remote exporters as beans in a DispatcherServlet context * (with advanced mapping and interception facilities being available there). * * @author Juergen Hoeller * @since 2.0 * @see org.springframework.web.HttpRequestHandler * @see org.springframework.web.servlet.DispatcherServlet */ @SuppressWarnings("serial") public class HttpRequestHandlerServlet extends HttpServlet { @Nullable private HttpRequestHandler target; @Override public void init() throws ServletException { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); this.target = wac.getBean(getServletName(), HttpRequestHandler.class); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Assert.state(this.target != null, "No HttpRequestHandler available"); LocaleContextHolder.setLocale(request.getLocale()); try { this.target.handleRequest(request, response); } catch (HttpRequestMethodNotSupportedException ex) { String[] supportedMethods = ex.getSupportedMethods(); if (supportedMethods != null) { response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); } response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); } finally { LocaleContextHolder.resetLocaleContext(); } } }
package uk.ac.ebi.ddi.ws.modules.dataset.model; /** * @author Yasset Perez-Riverol (ypriverol@gmail.com) * @date 01/06/2015 */ public enum Role { SUBMITTER, LABHEAD, COLABORATOR, ADMIN }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.organizations.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum IAMUserAccessToBilling { ALLOW("ALLOW"), DENY("DENY"); private String value; private IAMUserAccessToBilling(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return IAMUserAccessToBilling corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static IAMUserAccessToBilling fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (IAMUserAccessToBilling enumEntry : IAMUserAccessToBilling.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
package ch.bfh.bti7081.s2020.black.interfaces; public interface SignUpInterface { public void submit(String firstName, String lastName, String email, String password, String confirmPassword, String accountType); public void logIn(); }
/* Copyright 2017 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.stratumn.sdk.model.trace; import com.stratumn.sdk.TraceLink; /*** * Class to hold the traceId or prevLink used to identify the previous link. * @param <TLinkData> */ public class ParentLink<TLinkData> { private String traceId; private TraceLink<TLinkData> prevLink; public ParentLink(String traceId ) { if (traceId == null ) { throw new IllegalArgumentException("TraceId and PrevLink cannot be both null"); } this.traceId = traceId; } public ParentLink( TraceLink<TLinkData> prevLink) { if ( prevLink == null) { throw new IllegalArgumentException("TraceId and PrevLink cannot be both null"); } this.prevLink = prevLink; } public String getTraceId() { return this.traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } public TraceLink<TLinkData> getPrevLink() { return this.prevLink; } public void setPrevLink(TraceLink<TLinkData> prevLink) { this.prevLink = prevLink; } }
package com.ktz.deploy.jdbc.service.impl; import com.ktz.deploy.jdbc.entity.dto.AbsDepartmetData; import com.ktz.deploy.jdbc.entity.dto.Page; import com.ktz.deploy.jdbc.entity.dto.ProvBase; import com.ktz.deploy.jdbc.entity.dto.ProvTable; import com.ktz.deploy.jdbc.enums.DepartTableEnum; import com.ktz.deploy.jdbc.service.DepartmentDataService; import org.apache.logging.log4j.util.Strings; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; /** * @ClassName DepartmentDataServiceImpl * @Description 部门数据处理实现类 * @Author kaituozhesh * @Date 2020/3/26 11:32 * @Version V1.0 **/ @Service public class DepartmentDataServiceImpl implements DepartmentDataService { @Autowired private JdbcTemplate jdbcTemplate; /** * @param searchParsm * @return */ @Override public ProvTable getList(AbsDepartmetData searchParsm) { // 查询参数列表 List<ProvBase> provBases = provList(DepartTableEnum.getTableName(searchParsm.getMarketId())); List<String> sqlTitle = provBases.stream().map(ProvBase::getFieldName).collect(Collectors.toList()); Map<String, Object> paramsMap = getNotNullPropertyNames2(searchParsm); String sql = getListSql(paramsMap, searchParsm); List query = jdbcTemplate.query(sql, rs -> { List<Map<String, Object>> result = new ArrayList<>(); while (rs.next()) { Map<String, Object> row = new HashMap<>(16); for (String s : sqlTitle) { row.put(s, rs.getObject(s)); } result.add(row); } return result; }); return new ProvTable(provBases, this.getPage(query, searchParsm)); } /** * 查询列ID对象表要查的字段名 * * @param tableName * @return */ private List<ProvBase> provList(String tableName) { return jdbcTemplate.queryForList("select * from prov_base where table_name = " + tableName, ProvBase.class); } @Override public long findCount(String talbeName) { return jdbcTemplate.queryForObject(getCountSql(talbeName), Long.class); } private Page getPage(List list, AbsDepartmetData searchParam) { Page page = new Page(); List resultList = list; if (searchParam.getPageSize() > 0) { resultList = list.subList((searchParam.getPageNum() - 1) * searchParam.getPageSize(), searchParam.getPageSize()); } page.setList(resultList); page.setTotal(list.size()); page.setPageNum(searchParam.getPageNum()); page.setPageSize(searchParam.getPageSize()); return page; } /** * 获取对象中所有不为空的属性名 会获取父级属性 * * @param source * @return */ private static Map<String, Object> getNotNullPropertyNames(Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Map<String, Object> paramMap = new HashMap<>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (!ObjectUtils.isEmpty(srcValue)) { paramMap.put(pd.getName(), srcValue); } } paramMap.remove("class"); paramMap.remove("marketId"); return paramMap; } /** * 获取对象中所有不为空的属性名 不会获取父级的 * * @param source * @return */ private Map<String, Object> getNotNullPropertyNames2(Object source) { Map<String, Object> paramMap = new HashMap<>(); // 拿到该类 Class<?> clz = source.getClass(); // 获取实体类的所有属性,返回Field数组 Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); try { Object value = field.get(source); if (!ObjectUtils.isEmpty(value)) { paramMap.put(field.getName(), value); } } catch (IllegalAccessException e) { e.printStackTrace(); } } paramMap.remove("marketId"); return paramMap; } /** * 拼接查询列表SQL * * @param paramsMap * @param searchParam * @return */ private static String getListSql(Map<String, Object> paramsMap, AbsDepartmetData searchParam) { StringBuilder sb = new StringBuilder("select * from " + DepartTableEnum.getTableName(searchParam.getMarketId()) + " "); if (paramsMap != null && paramsMap.size() > 0) { sb.append(" where "); Iterator<String> iterator = paramsMap.keySet().iterator(); while (iterator.hasNext()) { String next = iterator.next(); sb.append(next + " like '%" + paramsMap.get(next) + "%' "); if (iterator.hasNext()) { sb.append("and "); } } } return sb.toString(); } /** * 拼接查询数量接口 * * @param tableName * @return */ private static String getCountSql(String tableName) { return Strings.isEmpty(tableName) ? "select 0" : "select count(1) from " + tableName; } }
package com.example.domain; /** * @author 小白 * @create 2021/3/22 */ public class Goods { private Integer id; private String name; private Integer amount; private float price; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Goods() { } public Goods(Integer id, String name, Integer amount, float price) { this.id = id; this.name = name; this.amount = amount; this.price = price; } @Override public String toString() { return "Goods{" + "id=" + id + ", name='" + name + '\'' + ", amount=" + amount + ", price=" + price + '}'; } }
package code401challenges.linkedList; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*; //I was a little stuck on how to test for an empty list so I did some research on testing LinkedLists //https://javarevisited.blogspot.com/2015/02/simple-junit-example-unit-tests-for-linked-list-java.html //Same shout out to James for the help! public class LinkedListTest { private LinkedList list = new LinkedList(); private LinkedList secondList = new LinkedList(); private Object IllegalAccessException; @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Before public void setup(){ //@Before <-- annotations give extra info (metadata) to things like JUnit, can annotate classes, methods, variables list.insert(29); list.insert(13); list.insert(1); list.insert(93); list.insert(723); secondList.insert(71); secondList.insert(46); secondList.insert(60); secondList.insert(14); secondList.insert(5); secondList.insert(112); } //There is an @After for after the tests to break down further, we won't be using it // Can successfully instantiate an empty linked list @Test public void testEmptyList() { LinkedList empty = new LinkedList(); assertNull( "Instantiation of the head Node creates an empty linked list.", empty.head ); } // Can properly insert single node into the linked list @Test public void testSingleNode() { list.insert(37); assertEquals( "This linked list has one node added with a value of 37", 37, list.head.value); } // Can properly insert multiple nodes into the linked list @Test public void testMultipleNodes() { list.insert(1_207); list.insert(14); assertEquals("This list will now include 14 and 1,207 at the beginning of the list.", "LinkedList: 14 1207 723 93 1 13 29", list.toString()); } // // The head property will properly point to the first node in the linked list // @Test public void findsFirstNode() { // // } // // // The head property will properly point to null when there are no inserted nodes // @Test public void findsFirstNode() { // // } // Will return true when finding a value within the linked list that exists @Test public void trueValueFound() { assertTrue(list.includes(93)); } // Will return false when searching for a value in the linked list that does not exist @Test public void falseValueMissing() { assertFalse(list.includes(26)); } // Can properly return a string collection of all the values that exist in the linked list when there is only one node @Test public void returnsValue() { LinkedList one = new LinkedList(); one.insert(8); assertEquals("LinkedList: 8", one.toString()); } // Can properly return a string collection of all the values that exist in the linked list @Test public void returnsValues() { assertEquals("This list should contain 723, 93, 1, 13, and 29", "LinkedList: 723 93 1 13 29", list.toString()); } //Utilize Single-responsibility principle: any methods you write should be clean, reusable, abstract component parts //Can successfully add a node to the end of the linked list when it already has nodes @Test public void testAppendWhenMultipleNodesExist() { list.append(8); assertEquals("Node(8) was added to the end of the list.", "LinkedList: 723 93 1 13 29 8", list.toString()); } //Can successfully add a node to the end of the linked list when it has one node @Test public void testAppendWhenOneNodeExists() { LinkedList one = new LinkedList(); one.insert(-4); one.append(73); assertEquals("LinkedList: -4 73", one.toString()); } //Can successfully add a node to the end when the list is empty @Test public void testAppendWhenEmpty() { LinkedList empty = new LinkedList(); empty.append(73); assertEquals("LinkedList: 73", empty.toString()); } //Can successfully insert multiple nodes to the end of a linked list // @Test public void testInsertAtEnd() { // LinkedList many = new LinkedList(); // Node currentNode = many.head; // // many.insert(-4); // many.insert(49); // many.insert(73); // many.insert(1); // many.insertBefore(currentNode.next.value, 8); // many.insertBefore(currentNode.next.value, 92); // // assertEquals("Node(8) should be second to last in the list.", // 8, // currentNode.next.next.next.next.value); // assertEquals("Node(92) should be last in the list.", // 92, // currentNode.next.next.next.next.next.value); // } //Can successfully insert a node before node(value) in the middle of a linked list when there are multiple nodes @Test public void testInsertInMiddle() { list.insertBefore(93, 8); assertEquals("Node(8) should be inserted before Node(93).", "LinkedList: 723 8 93 1 13 29", list.toString()); } //Can successfully insert a node before the first value node of a linked list of multiple nodes @Test public void testInsertAtBeginning() { list.insertBefore(93, 11); assertEquals("The list should now be 723, 11, 93, 1, 13, and 29", "LinkedList: 723 11 93 1 13 29", list.toString()); } //Can successfully insert after a node in the middle of linked list with multiple nodes @Test public void testInsertAfterInMiddle() { list.insertBefore(1, 49); assertEquals("Node(49) should be fourth in the list.", "LinkedList: 723 93 49 1 13 29", list.toString()); } //Can successfully insert a node after the last node of the linked list @Test public void testInsertAfterLastNode() { list.insertAfter(29, 49); assertEquals("Node(49) should be the last value.", "LinkedList: 723 93 1 13 29 49", list.toString()); } //Where k is greater than the length of the linked list @Test(expected = java.lang.IllegalArgumentException.class) public void testKGreaterThanLength() { list.runningBackwards(7); } //Where k is not a positive integer @Test(expected = java.lang.IllegalArgumentException.class) public void testNegativeK() { list.runningBackwards(-7); } //Where the linked list is of a size 1 @Test public void testKOfOne() { LinkedList one = new LinkedList(); one.insert(27); assertEquals("Input k is less than the LinkedList length.", 27, one.runningBackwards(0)); } //Happy Path where k is not at the end, but somewhere in the middle of the linked list @Test public void testKInMiddle() { LinkedList happy = new LinkedList(); happy.insert(-4); happy.insert(49); happy.insert(73); happy.insert(1); happy.insert(27); assertEquals("This should work and then we all get to snuggle kittens.", 73, happy.runningBackwards(2)); } //Test to see if lists have merged @Test public void mergedLists() { assertEquals("The lists have been merged.", "LinkedList: 723 112 93 5 1 14 13 60 29 46 71", LinkedList.mergeLinkedLists(list, secondList).toString()); } }
package com.fintech.crypto.request; import com.fintech.crypto.enums.Currency; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; @Getter @Setter public class CoinUpdateReq { @NotBlank private String ref; @NotBlank private String name; @NotBlank private String description; @NotBlank @Pattern(regexp = "[A-Za-z/]+") private String hashPowerUnit; @Min( value = 0L) private double exchangeRateToHashPower; private Currency currency; }
package pt.passarola.services.rest; import javax.inject.Inject; import javax.inject.Singleton; import retrofit.RestAdapter; /** * Created by ruigoncalo on 22/10/15. */ @Singleton public class RestApi { public static boolean DEBUG = true; private ApiServices apiServices; @Inject public RestApi() { RestAdapter restAdapter = build(Endpoints.baseUrl); apiServices = restAdapter.create(ApiServices.class); } public RestAdapter build(String baseUrl) { RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(baseUrl) .build(); if (DEBUG) { adapter.setLogLevel(RestAdapter.LogLevel.FULL); } return adapter; } public ApiServices getApiServices() { return apiServices; } }
package com.itheima.takeout.utils; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.view.animation.TranslateAnimation; /** * ============================================================ * Copyright:JackChan和他的朋友们有限公司版权所有 (c) 2017 * Author: JackChan * Email: 815712739@qq.com * GitHub: https://github.com/JackChan1999 * GitBook: https://www.gitbook.com/@alleniverson * CSDN博客: http://blog.csdn.net/axi295309066 * 个人博客: https://jackchan1999.github.io/ * 微博: AndroidDeveloper * <p> * Project_Name:Takeout * Package_Name:com.itheima.takeout * Version:1.0 * time:2017/5/30 13:52 * des :动画工具类 * gitVersion:2.12.0.windows.1 * updateAuthor:AllenIverson * updateDate:2017/5/30 13:52 * updateDes:${TODO} * ============================================================ */ public class AnimationUtils { /** * 显示动画 * @return */ public static AnimationSet getShowMinusAnimation() { AnimationSet set = new AnimationSet(false); TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 10, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); AlphaAnimation alpha = new AlphaAnimation(0, 1); set.addAnimation(translate); set.addAnimation(rotate); set.addAnimation(alpha); set.setDuration(200); return set; } /** * 隐藏动画 * @return */ public static AnimationSet getHideMinusAnimation() { AnimationSet set = new AnimationSet(false); TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 20, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0); RotateAnimation rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); AlphaAnimation alpha = new AlphaAnimation(1, 0); set.addAnimation(translate); set.addAnimation(rotate); set.addAnimation(alpha); set.setDuration(200); return set; } /** * 创建添加图片进入购物车的动画 */ public static Animation getAddAnimation(int[] destLocation, int[] srcLocation) { AnimationSet set = new AnimationSet(false); TranslateAnimation translateX = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, destLocation[0] - srcLocation[0], Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0); translateX.setInterpolator(new LinearInterpolator()); TranslateAnimation translateY = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, destLocation[1] - srcLocation[1]); translateY.setInterpolator(new AccelerateInterpolator()); AlphaAnimation alpha = new AlphaAnimation(1, 0.5f); //添加动画到集合 set.addAnimation(translateX); set.addAnimation(translateY); set.addAnimation(alpha); set.setDuration(200); return set; } public static class AnimationListenerAdapter implements Animation.AnimationListener{ @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // © 2011-2021 Telenav, 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 // // 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.telenav.kivakit.kernel.language.values.mutable; import com.telenav.kivakit.kernel.project.lexakai.diagrams.DiagramLanguageValue; import com.telenav.lexakai.annotations.LexakaiJavadoc; import com.telenav.lexakai.annotations.UmlClassDiagram; /** * An integer value that can be changed. Useful for mutating something other than a field from within a lambda * expression. * * @author jonathanl (shibo) */ @UmlClassDiagram(diagram = DiagramLanguageValue.class) @LexakaiJavadoc(complete = true) public class MutableInteger extends MutableValue<Integer> { public MutableInteger() { } public MutableInteger(Integer value) { super(value); } public void maximum(int value) { set(Math.max(get(), value)); } public void minimum(int value) { set(Math.min(get(), value)); } }
// package com.xuegao.springboot_tool.spring.schedule; // // import org.apache.ibatis.annotations.Mapper; // import org.apache.ibatis.annotations.Select; // // /** // * <p> </p> // * // * @description : // * @author : zhengqing // * @date : 2019/11/4 18:33 // */ // @Mapper // public interface CronMapper { // // @Select("select cron from cron limit 1") // String getCron(); // // }
package org.tain.kang.thomson; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.tain.kang.utils.ClassUtils; import org.tain.kang.utils.ResourcesUtils; @SuppressWarnings("unused") public class InsertDb { private static final boolean flag; private static final Boolean _mysqlEnable; private static final String _jdbcDriver; private static final String _dbUrl; private static final String _user; private static final String _pass; private static final String _charSet; private static Connection _conn = null; private static PreparedStatement _pstmt = null; private static String _sql = null; static { flag = true; _mysqlEnable = Boolean.valueOf(ResourcesUtils.getString("org.tain.kiea.thomson.mysql.enable")); _jdbcDriver = ResourcesUtils.getString("org.tain.kiea.thomson.mysql.jdbcDriver"); _dbUrl = ResourcesUtils.getString("org.tain.kiea.thomson.mysql.dbUrl"); _user = ResourcesUtils.getString("org.tain.kiea.thomson.mysql.user"); _pass = ResourcesUtils.getString("org.tain.kiea.thomson.mysql.pass"); _charSet = ResourcesUtils.getString("org.tain.kiea.thomson.mysql.charSet"); if (flag) { System.out.printf(">>>>> InsertDb._jdbcDriver = %s%n", _jdbcDriver); System.out.printf(">>>>> InsertDb._dbUrl = %s%n", _dbUrl); System.out.printf(">>>>> InsertDb._user = %s%n", _user); System.out.printf(">>>>> InsertDb._pass = %s%n", _pass); System.out.printf(">>>>> InsertDb._charSet = %s%n", _charSet); } if (flag) { if (_mysqlEnable) { try { _sql = "insert into THOMSON" + " (" + " GUID" + ", SIZE" + ", MESSAGE" + " ) values (" + " ?" // GUID varchar(100) + ", ?" // SIZE int(11) + ", ?" // MESSAGE mediumtext + ")"; Class.forName(_jdbcDriver); _conn = DriverManager.getConnection(_dbUrl, _user, _pass); _pstmt = _conn.prepareStatement(_sql); _conn.setAutoCommit(false); System.out.println(">>>>> MySQL Connection is OK!!!!!"); } catch (Exception e) { e.printStackTrace(); _conn = null; _pstmt = null; } } else { _conn = null; _pstmt = null; } } } public InsertDb() {} public static int insertMessage(String guid, String message) { if (!flag) System.out.println(">>>>> " + ClassUtils.getClassInfo()); if (_conn == null) { System.out.println(">>>>> MySQL Connection is null......."); return -1; } int length = 0; int retValue = -1; try { length = message.getBytes(_charSet).length; _pstmt.setString(1, guid); _pstmt.setInt (2, length); _pstmt.setString(3, message); retValue = _pstmt.executeUpdate(); _conn.commit(); } catch (SQLException e) { if (_conn != null) try { _conn.rollback(); } catch (Exception e2) {} _conn = null; e.printStackTrace(); } catch (Exception e) { if (_conn != null) try { _conn.rollback(); } catch (Exception e2) {} _conn = null; e.printStackTrace(); } if (flag) System.out.printf(">>>>> MySQL.insertMessage() --> SIZE=%7d, GUID=\"%s\" %n", length, guid); return retValue; } /////////////////////////////////////////////////////////////////////////// /* public static void main(String[] args) throws Exception { if (flag) System.out.println(">>>>> " + ClassUtils.getClassInfo()); if (flag) select01(args); // select if (!flag) insertTest01(args); // insert a sample data if (!flag) delete01(args); // delete the articles in table Thomson } */ private static void select01(String[] args) throws Exception { if (flag) System.out.println(">>>>> " + ClassUtils.getClassInfo()); List<Map<String, Object>> list = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet resultSet = null; try { Class.forName(_jdbcDriver); conn = DriverManager.getConnection(_dbUrl, _user, _pass); conn.setAutoCommit(false); list = new ArrayList<Map<String, Object>>(); String sql = "" + "select" + " ID" + " , GUID" + " , SIZE" + " , MESSAGE" + " from" + " THOMSON" + " where 1=1" + " and SIZE > ?" + ""; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 50000); resultSet = pstmt.executeQuery(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", resultSet.getLong("ID")); map.put("guid", resultSet.getString("GUID")); map.put("size", resultSet.getInt("SIZE")); map.put("message", resultSet.getString("MESSAGE")); list.add(map); } if (flag) System.out.printf(">>>>> list.size() = %d%n", list.size()); if (flag) conn.commit(); else conn.rollback(); } catch (SQLException e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } catch (Exception e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } finally { if (pstmt != null) try { pstmt.close(); } catch (Exception e) {} if (conn != null) try { conn.close(); } catch (Exception e) {} } } private static void insertTest01(String[] args) throws Exception { if (flag) System.out.println(">>>>> " + ClassUtils.getClassInfo()); Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(_jdbcDriver); conn = DriverManager.getConnection(_dbUrl, _user, _pass); conn.setAutoCommit(false); String sql = "insert into THOMSON" + " (" + " GUID" + ", SIZE" + ", MESSAGE" + " ) values (" + " ?" // GUID varchar(100) + ", ?" // SIZE int(11) + ", ?" // MESSAGE mediumtext + ")"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "GUID-key"); pstmt.setInt(2, 12345); pstmt.setString(3, "sender@gmail.com..sender@gmail.com..sender@gmail.com..sender@gmail.com"); int rowUpdate = pstmt.executeUpdate(); if (flag) System.out.printf(">>>>> rowUpdate = %d%n", rowUpdate); if (flag) conn.commit(); else conn.rollback(); } catch (SQLException e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } catch (Exception e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } finally { if (pstmt != null) try { pstmt.close(); } catch (Exception e) {} if (conn != null) try { conn.close(); } catch (Exception e) {} } } private static void delete01(String[] args) throws Exception { if (flag) System.out.println(">>>>> " + ClassUtils.getClassInfo()); Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(_jdbcDriver); conn = DriverManager.getConnection(_dbUrl, _user, _pass); conn.setAutoCommit(false); String sql = "delete from THOMSON " + " where 1=1" + " and id < ?" + ""; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 100); int rowUpdate = pstmt.executeUpdate(); if (flag) System.out.printf(">>>>> rowUpdate = %d%n", rowUpdate); if (flag) conn.commit(); else conn.rollback(); } catch (SQLException e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } catch (Exception e) { if (conn != null) try { conn.rollback(); } catch (Exception e2) {} e.printStackTrace(); } finally { if (pstmt != null) try { pstmt.close(); } catch (Exception e) {} if (conn != null) try { conn.close(); } catch (Exception e) {} } } }
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.autoconfigure.orm.jpa; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestDatabase.Replace; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link DataJpaTest}. * * @author Phillip Webb */ @RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) @Deprecated public class DataJpaTestWithAutoConfigureTestDatabaseReplaceNoneIntegrationTests { @Autowired private TestEntityManager entities; @Autowired private ExampleRepository repository; @Autowired private DataSource dataSource; @Test public void testRepository() throws Exception { this.entities.persist(new ExampleEntity("spring", "123")); this.entities.persist(new ExampleEntity("boot", "124")); this.entities.flush(); ExampleEntity found = this.repository.findByReference("124"); assertThat(found.getName()).isEqualTo("boot"); } @Test public void usesDefaultEmbeddedDatabase() throws Exception { // HSQL is explicitly defined and should not be replaced String product = this.dataSource.getConnection().getMetaData() .getDatabaseProductName(); assertThat(product).startsWith("HSQL"); } }
/* * Copyright 2000-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jetspeed.services.search; import java.util.Map; import java.net.URL; import org.apache.commons.collections.MultiMap; /** * Base parsed object. * * @author <a href="mailto:morciuch@apache.org">Mark Orciuch</a> * @version $Id: BaseParsedObject.java,v 1.4 2004/02/23 03:48:47 jford Exp $ */ public class BaseParsedObject implements ParsedObject { private String key; private String type; private String title; private String description; private String content; private String language; private URL url; private String[] keywords; private MultiMap multiKeywords; private Map fields; private MultiMap multiFields; private float score; private String className; /** * Returns parsed object key * * @return */ public String getKey() { return this.key; } /** * Sets parsed object key * * @param content */ public void setKey(String key) { this.key = key; } /** * Returns parsed object type * * @return */ public String getType() { return this.type; } /** * Sets parsed object type * * @param type */ public void setType(String type) { this.type = type; } /** * Returns parsed object content * * @return */ public String getContent() { return this.content; } /** * Sets parsed object content * * @param content */ public void setContent(String content) { this.content = content; } /** * Returns parsed object description * * @return */ public String getDescription() { return this.description; } /** * Sets parsed object description * * @param description */ public void setDescription(String description) { this.description = description; } /** * Returns parsed object keywords * * @return */ public String[] getKeywords() { return this.keywords; } /** * Sets parsed object keywords * * @param keywords */ public void setKeywords(String[] keywords) { this.keywords = keywords; } /** * Returns parsed object title * * @return */ public String getTitle() { return this.title; } /** * Sets parsed object title * * @param title */ public void setTitle(String title) { this.title = title; } /** * Returns parsed object language * * @return */ public String getLanguage() { return this.language; } /** * Sets parsed object language * * @param language */ public void setLanguage(String language) { this.language = language; } /** * Returns parsed object searchable fields * * @return */ public Map getFields() { return this.fields; } /** * Sets parsed object searchable fields * * @param fields */ public void setFields(Map fields) { this.fields = fields; } /** * Returns parsed object URL * * @return */ public URL getURL() { return this.url; } /** * Sets parsed object URL * * @param fields */ public void setURL(URL url) { this.url = url; } /** * Getter for property score. * * @return Value of property score. */ public float getScore() { return this.score; } /** * Setter for property score. * * @param score New value of property score. */ public void setScore(float score) { this.score = score; } /** * Getter for property className. * * @return Value of property className. */ public String getClassName() { return className; } /** * Setter for property className. * * @param score New value of property className. */ public void setClassName(String className) { this.className = className; } /** * @see org.apache.jetspeed.services.search.ParsedObject#getMultiFields() */ public MultiMap getMultiFields() { return multiFields; } /** * @see org.apache.jetspeed.services.search.ParsedObject#setMultiFields(org.apache.commons.collections.MultiMap) */ public void setMultiFields(MultiMap multiFields) { this.multiFields = multiFields; } /** * @see org.apache.jetspeed.services.search.ParsedObject#getMultiKeywords() */ public MultiMap getMultiKeywords() { return multiKeywords; } /** * @see org.apache.jetspeed.services.search.ParsedObject#setMultiKeywords(org.apache.commons.collections.MultiMap) */ public void setMultiKeywords(MultiMap multiKeywords) { this.multiKeywords = multiKeywords; } }
/* * Copyright (c) 2017, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.config; import com.google.inject.Guice; import com.google.inject.testing.fieldbinder.Bind; import com.google.inject.testing.fieldbinder.BoundFieldModule; import java.io.File; import java.time.Instant; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Inject; import javax.inject.Named; import net.runelite.api.Client; import net.runelite.client.RuneLite; import net.runelite.client.account.AccountSession; import net.runelite.client.eventbus.EventBus; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ConfigManagerTest { @Mock @Bind Client client; @Mock @Bind EventBus eventBus; @Mock @Bind ScheduledExecutorService executor; @Mock @Bind RuneLiteConfig runeliteConfig; @Mock @Bind private OpenOSRSConfig openOSRSConfig; @Bind @Named("config") private File config = RuneLite.DEFAULT_CONFIG_FILE; @Inject ConfigManager manager; @Before public void before() { Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this); } @Test public void testGetConfig() { AccountSession accountSession = new AccountSession(UUID.randomUUID(), Instant.now()); accountSession.setUsername("test"); manager.setConfiguration("test", "key", "moo"); TestConfig conf = manager.getConfig(TestConfig.class); Assert.assertEquals("moo", conf.key()); } @Test public void testGetConfigDefault() { AccountSession accountSession = new AccountSession(UUID.randomUUID(), Instant.now()); accountSession.setUsername("test"); TestConfig conf = manager.getConfig(TestConfig.class); Assert.assertEquals("default", conf.key()); } @Test public void testSetConfig() { AccountSession accountSession = new AccountSession(UUID.randomUUID(), Instant.now()); accountSession.setUsername("test"); TestConfig conf = manager.getConfig(TestConfig.class); conf.key("new value"); Assert.assertEquals("new value", conf.key()); } @Test public void testGetConfigDescriptor() { AccountSession accountSession = new AccountSession(UUID.randomUUID(), Instant.now()); accountSession.setUsername("test"); TestConfig conf = manager.getConfig(TestConfig.class); ConfigDescriptor descriptor = manager.getConfigDescriptor(conf); Assert.assertEquals(2, descriptor.getItems().size()); } @Test public void testResetNullDefaultConfig() { TestConfig conf = manager.getConfig(TestConfig.class); ConfigDescriptor descriptor = manager.getConfigDescriptor(conf); conf.nullDefaultKey("new value"); manager.unsetConfiguration(descriptor.getGroup().value(), "nullDefaultKey"); manager.setDefaultConfiguration(conf, false); Assert.assertNull(conf.nullDefaultKey()); } }
/* * Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.j_spaces.core; import com.gigaspaces.client.IPojoSpace; import com.gigaspaces.internal.client.spaceproxy.IDirectSpaceProxy; import com.j_spaces.core.client.SpaceFinder; import com.j_spaces.core.client.SpaceURL; import net.jini.core.transaction.Transaction; import net.jini.id.Uuid; import java.rmi.RemoteException; /** * <b>Notice: Since 7.0 this API is internal and subject to changes in future versions - Use {@link * org.openspaces.core.GigaSpace} instead.</b> * * @author Igor Goldenberg * @version 5.1 * @see org.openspaces.core.GigaSpace * @since 1.0 */ public interface IJSpace extends IPojoSpace { /** * Wait for no time at all. This is used as a timeout value in various read and take calls. * * @see #read * @see #readIfExists * @see #take * @see #takeIfExists */ long NO_WAIT = 0; ////////////////////////////// /// Administration methods /// ////////////////////////////// /** * Returns the name of this space. */ String getName(); String getContainerName(); /** * Returns the {@link SpaceURL} object which was used as the argument for {@link * SpaceFinder#find(SpaceURL)} while looking for the space. If a client uses this {@link * SpaceURL} when it calls to {@link SpaceFinder#find(SpaceURL)} it should be able to find that * space. * * Notice: The {@link SpaceURL} returned when calling getURL() is different since in that case * it returns the {@link SpaceURL} used to initialize the space (a java:// protocol to start an * embedded space). * * @return {@link SpaceURL} object which can be used to find the space proxy while calling * {@link SpaceFinder#find(SpaceURL)} */ public SpaceURL getFinderURL(); /** * Returns the {@link SpaceURL} instance which was used to initialize the space. */ public SpaceURL getURL(); /** * Returns the unique {@link Uuid} of this space instance. */ public Uuid getReferentUuid(); /** * Returns true if the space started within a GSC. * * @deprecated Since 8.0 - This method is reserved for internal usage. */ @Deprecated boolean isStartedWithinGSC() throws RemoteException; /** * Checks whether proxy is connected to embedded or remote space. */ public boolean isEmbedded(); /** * Returns an indication : is this space secured. If for this space defined Security Filter, the * space will be secured. * * @return boolean true if this space secured, otherwise false. **/ public boolean isSecured(); /** * Gets the proxy ReadModifiers. */ public int getReadModifiers(); /** * Sets the read mode modifiers for proxy level. <br> */ public int setReadModifiers(int readModifiers); /** * Gets the proxyUpdateModifiers. */ public int getUpdateModifiers(); /** * Sets the update mode modifiers for proxy level. */ public int setUpdateModifiers(int newModifiers); /** * Returns status of Optimistic Lock protocol. */ public boolean isOptimisticLockingEnabled(); /** * Enable/Disable Optimistic Lock protocol. */ public void setOptimisticLocking(boolean enabled); /** * Returns <code>true</code> if this proxy FIFO enabled, otherwise <code>false</code>. */ @Deprecated public boolean isFifo(); /** * Sets FIFO mode for proxy. */ @Deprecated public void setFifo(boolean enabled); /** * Returns the admin object to the remote part of this space. * <pre><code> * // get a list of classes and the number of entries of each class * {@link com.j_spaces.core.admin.IRemoteJSpaceAdmin} remoteAdmin = * (IRemoteJSpaceAdmin)serverAdmin.getAdmin(); * Object classList[] = remoteAdmin.getRuntimeInfo().m_ClassNames.toArray(); * List numOFEntries = remoteAdmin.getRuntimeInfo().m_NumOFEntries; * </code></pre> * * @return the remoteAdmin object to the remote part of this space. * @throws RemoteException if a communication error occurs */ Object getAdmin() throws java.rmi.RemoteException; /** * returns itself in case of a direct proxy or the real proxy in case of a local cache or a * view. * * @return IDirectSpaceProxy */ IDirectSpaceProxy getDirectProxy(); /** * Checks whether the space is alive and accessible. * * @throws java.rmi.RemoteException when space was unreachable */ void ping() throws java.rmi.RemoteException; /** * Drops all Class's entries and all its templates from the space. Calling this method will * remove all internal meta data related to this class stored in the space. When using * persistent spaced the relevant RDBMS table will be dropped. It is the caller responsibility * to ensure that no entries from this class are written to the space while this method is * called. * * <pre><code> * Message message = new Message("Hello"); * Lease lease = space.write(message, null, Lease.FOREVER); * * serverAdmin.dropClass( Message.class.getName()); * </code></pre> * * @param className name of class to delete. * @throws DropClassException Failed to drop desired class. * @throws RemoteException if a communication error occurs * @see com.gigaspaces.client.IPojoSpace#clear(Object, Transaction) **/ public void dropClass(String className) throws java.rmi.RemoteException, DropClassException; public String getCacheTypeName(); }
package zapsolutions.zap.lnd; import io.reactivex.rxjava3.core.Single; public interface LndWalletKitService { Single<com.github.lightningnetwork.lnd.signrpc.KeyDescriptor> deriveNextKey(com.github.lightningnetwork.lnd.walletrpc.KeyReq request); Single<com.github.lightningnetwork.lnd.signrpc.KeyDescriptor> deriveKey(com.github.lightningnetwork.lnd.signrpc.KeyLocator request); Single<com.github.lightningnetwork.lnd.walletrpc.AddrResponse> nextAddr(com.github.lightningnetwork.lnd.walletrpc.AddrRequest request); Single<com.github.lightningnetwork.lnd.walletrpc.PublishResponse> publishTransaction(com.github.lightningnetwork.lnd.walletrpc.Transaction request); Single<com.github.lightningnetwork.lnd.walletrpc.SendOutputsResponse> sendOutputs(com.github.lightningnetwork.lnd.walletrpc.SendOutputsRequest request); Single<com.github.lightningnetwork.lnd.walletrpc.EstimateFeeResponse> estimateFee(com.github.lightningnetwork.lnd.walletrpc.EstimateFeeRequest request); Single<com.github.lightningnetwork.lnd.walletrpc.PendingSweepsResponse> pendingSweeps(com.github.lightningnetwork.lnd.walletrpc.PendingSweepsRequest request); Single<com.github.lightningnetwork.lnd.walletrpc.BumpFeeResponse> bumpFee(com.github.lightningnetwork.lnd.walletrpc.BumpFeeRequest request); }
package iuniversity.view; import javafx.stage.Stage; public interface FXView extends View { /** * * @return the current stage. */ Stage getStage(); /** * * @param stage the stage to which display scenes */ void setStage(Stage stage); }
package views.admin.question; import static j2html.TagCreator.div; import static org.assertj.core.api.Assertions.assertThat; import static play.test.Helpers.stubMessagesApi; import com.google.common.collect.ImmutableSet; import forms.AddressQuestionForm; import forms.DropdownQuestionForm; import forms.EnumeratorQuestionForm; import forms.FileUploadQuestionForm; import forms.IdQuestionForm; import forms.NameQuestionForm; import forms.NumberQuestionForm; import forms.RadioButtonQuestionForm; import forms.TextQuestionForm; import j2html.tags.ContainerTag; import org.junit.Test; import play.i18n.Lang; import play.i18n.Messages; import views.admin.questions.QuestionConfig; public class QuestionConfigTest { private static final ContainerTag DEFAULT_CONFIG = div(); private final Messages messages = stubMessagesApi().preferred(ImmutableSet.of(Lang.defaultLang())); @Test public void allHandledTypesHaveCustomConfig() { assertThat(QuestionConfig.buildQuestionConfig(new TextQuestionForm(), messages)) .toString() .contains("text-question-min-length-input"); assertThat(QuestionConfig.buildQuestionConfig(new AddressQuestionForm(), messages)) .toString() .contains("address-question-default-state-select"); assertThat(QuestionConfig.buildQuestionConfig(new DropdownQuestionForm(), messages)) .toString() .contains("multi-select-question-config"); assertThat(QuestionConfig.buildQuestionConfig(new DropdownQuestionForm(), messages)) .toString() .contains("single-select-question-config"); assertThat(QuestionConfig.buildQuestionConfig(new IdQuestionForm(), messages)) .toString() .contains("id-question-min-length-input"); assertThat(QuestionConfig.buildQuestionConfig(new NumberQuestionForm(), messages)) .toString() .contains("number-question-min-value-input"); assertThat(QuestionConfig.buildQuestionConfig(new RadioButtonQuestionForm(), messages)) .toString() .contains("single-select-question-config"); assertThat(QuestionConfig.buildQuestionConfig(new EnumeratorQuestionForm(), messages)) .toString() .contains("enumerator-question-config"); } @Test public void unhandledQuestionTypes_defaultsToDefaultConfig() { assertThat(QuestionConfig.buildQuestionConfig(new FileUploadQuestionForm(), messages)) .isEqualTo(DEFAULT_CONFIG); assertThat(QuestionConfig.buildQuestionConfig(new NameQuestionForm(), messages)) .isEqualTo(DEFAULT_CONFIG); } }
package com.ruoyi.system.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.ruoyi.common.core.domain.entity.SysMenu; /** * 菜单表 数据层 * * @author ruoyi */ public interface SysMenuMapper { /** * 查询系统菜单列表 * * @param menu 菜单信息 * @return 菜单列表 */ public List<SysMenu> selectMenuList(SysMenu menu); /** * 根据用户所有权限 * * @return 权限列表 */ public List<String> selectMenuPerms(); /** * 根据用户查询系统菜单列表 * * @param menu 菜单信息 * @return 菜单列表 */ public List<SysMenu> selectMenuListByUserId(SysMenu menu); /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ public List<String> selectMenuPermsByUserId(Long userId); /** * 根据用户ID查询菜单 * * @return 菜单列表 */ public List<SysMenu> selectMenuTreeAll(); /** * 根据用户ID查询菜单 * * @param userId 用户ID * @return 菜单列表 */ public List<SysMenu> selectMenuTreeByUserId(Long userId); /** * 根据角色ID查询菜单树信息 * * @param roleId 角色ID * @param menuCheckStrictly 菜单树选择项是否关联显示 * @return 选中菜单列表 */ public List<Integer> selectMenuListByRoleId(@Param("roleId") Long roleId, @Param("menuCheckStrictly") boolean menuCheckStrictly); /** * 根据菜单ID查询信息 * * @param menuId 菜单ID * @return 菜单信息 */ public SysMenu selectMenuById(Long menuId); /** * 是否存在菜单子节点 * * @param menuId 菜单ID * @return 结果 */ public int hasChildByMenuId(Long menuId); /** * 新增菜单信息 * * @param menu 菜单信息 * @return 结果 */ public int insertMenu(SysMenu menu); /** * 修改菜单信息 * * @param menu 菜单信息 * @return 结果 */ public int updateMenu(SysMenu menu); /** * 删除菜单管理信息 * * @param menuId 菜单ID * @return 结果 */ public int deleteMenuById(Long menuId); /** * 校验菜单名称是否唯一 * * @param menuName 菜单名称 * @param parentId 父菜单ID * @return 结果 */ public SysMenu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") Long parentId); }
/* * The MIT License * * Copyright (c) 2014 Red Hat, Inc. * * 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 hudson.cli; import java.util.List; import hudson.Extension; import hudson.model.TopLevelItem; import hudson.model.DirectlyModifiableView; import hudson.model.View; import org.kohsuke.args4j.Argument; /** * @author ogondza * @since 1.570 */ @Extension public class AddJobToViewCommand extends CLICommand { @Argument(usage="Name of the view", required=true, index=0) private View view; @Argument(usage="Job names", required=true, index=1) private List<TopLevelItem> jobs; @Override public String getShortDescription() { return Messages.AddJobToViewCommand_ShortDescription(); } @Override protected int run() throws Exception { view.checkPermission(View.CONFIGURE); if (!(view instanceof DirectlyModifiableView)) throw new IllegalStateException( "'" + view.getDisplayName() + "' view can not be modified directly"); for (TopLevelItem job: jobs) { ((DirectlyModifiableView) view).add(job); } return 0; } }
import java.util.Scanner; public class bitNum { public static void main(String[] args) { Scanner a = new Scanner(System.in); int b = a.nextInt(); String c = Integer.toString(b); for (int i = 0; i < c.length(); i++){ System.out.println(c.charAt(i)); } jisuan j = new jisuan(); j.ji(25); j.sout(); } } class jisuan { int num = 1; //递归 int ji (int i){ //判断i = 0时,阶乘为0; if(i == 0){ num = 1; return 0; } num*=i; //出口 if(i == 1){ return 0; } return ji(--i); } void sout(){ System.out.println(num); num = 0; } }
package uk.dangrew.kode.textflow.model.tags; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import java.util.function.BiConsumer; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import uk.dangrew.kode.javafx.style.TextFlowBuilder; import uk.dangrew.kode.launch.TestApplication; import uk.dangrew.kode.textflow.model.TextFlowFormat; import uk.dangrew.kode.textflow.model.TextFlowSchema; public class TextFormParserTest { private TextFlowFormat format; private TextFlowSchema schema; @Mock private BiConsumer< TextFlowBuilder, String > builderFunction; private TextFlowBuilder builder; private TextFormParser systemUnderTest; @Before public void initialiseSystemUnderTest() { TestApplication.startPlatform(); MockitoAnnotations.initMocks( this ); format = new TextFlowFormat(); schema = TextFlowSchema.Bold; systemUnderTest = new TextFormParser( format, schema, builderFunction ); }//End Method @Test public void shouldParseLastEntry() { assertThat( systemUnderTest.parse( "[b]this is the text", ( "[b]this is the text" ).length(), builder ), is( "[b]this is the text" ) ); verify( builderFunction ).accept( builder, "this is the text" ); }//End Method @Test public void shouldParseIntermediate() { assertThat( systemUnderTest.parse( "[b]this is the text[n]something to not include", ( "[b]this is the text" ).length(), builder ), is( "[b]this is the text" ) ); verify( builderFunction ).accept( builder, "this is the text" ); }//End Method @Test public void shouldParseAndAccountForProgressThroughInput() { assertThat( systemUnderTest.parse( "[b]this is the text[n]something to not include", ( "[b]this is the text" ).length(), builder ), is( "[b]this is the text" ) ); verify( builderFunction ).accept( builder, "this is the text" ); }//End Method }//End Class
package com.fc; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 项目启动方法 * @author fuce * */ @SpringBootApplication @MapperScan(value = "com.fc.test.mapper") public class SpringbootStart { public static void main(String[] args) { SpringApplication.run(SpringbootStart.class, args); System.out.println("*******************************************\n" + "* 码云地址 *\n" + "* https://gitee.com/bdj/SpringBoot_v2 *\n" + "* *\n" + "*******************************************\n" + " _.._ ,-------------------.\n" + " ,' `. ( 启动成功!开启学习之旅! )\n" + " / __) __` \\ `-,-----------------'\n" + " ( (`-`(-') ) _.-'\n" + " /) \\ = / (\n" + " /' |--' . \\\n" + " ( ,---| `-.)__`\n" + " )( `-.,--' _`-.\n" + " '/,' ( Uu\",\n" + " (_ , `/,-' )\n" + " `.__, : `-'/ /`--'\n" + " | `--' |\n" + " ` `-._ /\n" + " \\ (\n" + " /\\ . \\. \n" + " / |` \\ ,-\\\n" + " / \\| .) / \\\n" + " ( ,'|\\ ,' :\n" + " | \\,`.`--\"/ }\n" + " `,' \\ |,' /\n" + " / \"-._ `-/ |\n" + " \"-. \"-.,'| ;\n" + " / _/[\"---'\"\"]\n" + " : / |\"- '\n" + " ' | /\n" + " ` |"); } }
/* * Copyright 2013-2019 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.ui.desktop.internal.textBox; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.components.fields.ExpandableTextField; import consulo.disposer.Disposable; import consulo.ui.TextBoxWithExpandAction; import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.desktop.internal.validableComponent.DocumentSwingValidator; import consulo.ui.desktop.laf.extend.LafExtendUtil; import consulo.ui.desktop.laf.extend.textBox.SupportTextBoxWithExpandActionExtender; import consulo.ui.image.Image; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.util.EventListener; import java.util.List; import java.util.function.Function; /** * @author VISTALL * @since 2019-04-26 */ public class DesktopTextBoxWithExpandAction { @RequiredUIAccess public static TextBoxWithExpandAction create(@Nullable Image editButtonImage, String dialogTitle, Function<String, List<String>> parser, Function<List<String>, String> joiner) { SupportTextBoxWithExpandActionExtender extender = LafExtendUtil.getExtender(SupportTextBoxWithExpandActionExtender.class); if (extender != null) { return new SupportedTextBoxWithExpandAction(parser, joiner, extender); } return new FallbackTextBoxWithExpandAction(editButtonImage, dialogTitle, parser, joiner); } private static class SupportedTextBoxWithExpandAction extends DocumentSwingValidator<String, ExpandableTextField> implements TextBoxWithExpandAction, TextBoxWithTextField { private SupportedTextBoxWithExpandAction(Function<String, List<String>> parser, Function<List<String>, String> joiner, SupportTextBoxWithExpandActionExtender lookAndFeel) { ExpandableTextField field = new ExpandableTextField(parser::apply, joiner::apply, lookAndFeel); TextFieldPlaceholderFunction.install(field); initialize(field); addDocumentListenerForValidator(field.getDocument()); field.getDocument().addDocumentListener(new DocumentAdapter() { @Override @SuppressWarnings("unchecked") @RequiredUIAccess protected void textChanged(DocumentEvent e) { getListenerDispatcher(ValueListener.class).valueChanged(new ValueEvent(SupportedTextBoxWithExpandAction.this, getValue())); } }); } @Nonnull @Override public JTextField getTextField() { return toAWTComponent(); } @Nullable @Override public String getValue() { return toAWTComponent().getText(); } @RequiredUIAccess @Override public void setValue(String value, boolean fireListeners) { toAWTComponent().setText(value); } @Nonnull @Override public TextBoxWithExpandAction setDialogTitle(@Nonnull String text) { return this; } @Override public void setPlaceholder(@Nullable String text) { toAWTComponent().getEmptyText().setText(text); } @Override public void setVisibleLength(int columns) { toAWTComponent().setColumns(columns); } @Override public void selectAll() { toAWTComponent().selectAll(); } @Override public void setEditable(boolean editable) { toAWTComponent().setEditable(editable); } @Override public boolean isEditable() { return toAWTComponent().isEditable(); } } private static class FallbackTextBoxWithExpandAction extends DocumentSwingValidator<String, ComponentWithBrowseButton<JComponent>> implements TextBoxWithTextField, TextBoxWithExpandAction { private DesktopTextBoxImpl myTextBox; private String myDialogTitle; @RequiredUIAccess private FallbackTextBoxWithExpandAction(Image editButtonImage, String dialogTitle, Function<String, List<String>> parser, Function<List<String>, String> joiner) { myTextBox = new DesktopTextBoxImpl(""); myDialogTitle = StringUtil.notNullize(dialogTitle); JTextField awtTextField = myTextBox.toAWTComponent(); initialize(new ComponentWithBrowseButton<>(awtTextField, e -> Messages.showTextAreaDialog(awtTextField, myDialogTitle, myDialogTitle, parser::apply, joiner::apply))); addDocumentListenerForValidator(awtTextField.getDocument()); if (editButtonImage != null) { toAWTComponent().setButtonIcon(editButtonImage); } } @Nonnull @Override public JTextField getTextField() { return myTextBox.getTextField(); } @Nonnull @Override public <T extends EventListener> Disposable addListener(@Nonnull Class<T> eventClass, @Nonnull T listener) { return myTextBox.addListener(eventClass, listener); } @Nonnull @Override public <T extends EventListener> T getListenerDispatcher(@Nonnull Class<T> eventClass) { return myTextBox.getListenerDispatcher(eventClass); } @Override public boolean hasFocus() { return myTextBox.hasFocus(); } @Nullable @Override public String getValue() { return myTextBox.getValue(); } @RequiredUIAccess @Override public void setValue(String value, boolean fireListeners) { myTextBox.setValue(value, fireListeners); } @Nonnull @Override public TextBoxWithExpandAction setDialogTitle(@Nonnull String text) { myDialogTitle = text; return this; } @Override public void setPlaceholder(@Nullable String text) { myTextBox.setPlaceholder(text); } @Override public void setVisibleLength(int columns) { myTextBox.setVisibleLength(columns); } @Override public void selectAll() { myTextBox.selectAll(); } @Override public void setEditable(boolean editable) { myTextBox.setEditable(editable); } @Override public boolean isEditable() { return myTextBox.isEditable(); } } }
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.boot.logging; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Immutable class that represents the configuration of a {@link LoggingSystem}'s logger. * * @author Ben Hale * @since 1.5.0 */ public final class LoggerConfiguration { private final String name; private final LogLevel configuredLevel; private final LogLevel effectiveLevel; /** * Create a new {@link LoggerConfiguration instance}. * @param name the name of the logger * @param configuredLevel the configured level of the logger * @param effectiveLevel the effective level of the logger */ public LoggerConfiguration(String name, LogLevel configuredLevel, LogLevel effectiveLevel) { Assert.notNull(name, "Name must not be null"); Assert.notNull(effectiveLevel, "EffectiveLevel must not be null"); this.name = name; this.configuredLevel = configuredLevel; this.effectiveLevel = effectiveLevel; } /** * Returns the configured level of the logger. * @return the configured level of the logger */ public LogLevel getConfiguredLevel() { return this.configuredLevel; } /** * Returns the effective level of the logger. * @return the effective level of the logger */ public LogLevel getEffectiveLevel() { return this.effectiveLevel; } /** * Returns the name of the logger. * @return the name of the logger */ public String getName() { return this.name; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof LoggerConfiguration) { LoggerConfiguration other = (LoggerConfiguration) obj; boolean rtn = true; rtn = rtn && ObjectUtils.nullSafeEquals(this.name, other.name); rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, other.configuredLevel); rtn = rtn && ObjectUtils.nullSafeEquals(this.effectiveLevel, other.effectiveLevel); return rtn; } return super.equals(obj); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ObjectUtils.nullSafeHashCode(this.name); result = prime * result + ObjectUtils.nullSafeHashCode(this.configuredLevel); result = prime * result + ObjectUtils.nullSafeHashCode(this.effectiveLevel); return result; } @Override public String toString() { return "LoggerConfiguration [name=" + this.name + ", configuredLevel=" + this.configuredLevel + ", effectiveLevel=" + this.effectiveLevel + "]"; } }
package com.solent.shipping_app.data.payloads.request; import com.solent.shipping_app.data.models.Service; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; public class BookingRequest { @NotBlank @NotNull private Date startDate; @NotBlank @NotNull private Date endDate; @NotBlank @NotNull private List<Service> services; public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public List<Service> getServices() { return services; } public void setServices(List<Service> services) { this.services = services; } }
package andioopp.model.system.systems; import andioopp.common.time.Time; import andioopp.model.Model; import andioopp.model.domain.tower.attack.projectiles.Projectile; import andioopp.model.system.System; /** * A class that handles updating Projectiles. */ public class UpdateProjectileSystem implements System<Model> { @Override public void update(Model model, Time time) { for (Projectile projectile : model.getWorld().getProjectiles()) { projectile.update(time); } } }
/* * Copyright 2017, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.google.api.gax.grpc; import static com.google.api.gax.grpc.testing.FakeServiceGrpc.METHOD_CLIENT_STREAMING_RECOGNIZE; import static com.google.api.gax.grpc.testing.FakeServiceGrpc.METHOD_SERVER_STREAMING_RECOGNIZE; import static com.google.api.gax.grpc.testing.FakeServiceGrpc.METHOD_STREAMING_RECOGNIZE; import static com.google.api.gax.grpc.testing.FakeServiceGrpc.METHOD_STREAMING_RECOGNIZE_ERROR; import com.google.api.gax.grpc.testing.FakeServiceImpl; import com.google.api.gax.grpc.testing.InProcessServer; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiStreamObserver; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.ClientStreamingCallable; import com.google.api.gax.rpc.EmptyRequestParamsExtractor; import com.google.api.gax.rpc.EntryPointBidiStreamingCallable; import com.google.api.gax.rpc.EntryPointClientStreamingCallable; import com.google.api.gax.rpc.EntryPointServerStreamingCallable; import com.google.api.gax.rpc.RequestUrlParamsEncoder; import com.google.api.gax.rpc.ServerStreamingCallable; import com.google.common.collect.Iterators; import com.google.common.truth.Truth; import com.google.type.Color; import com.google.type.Money; import io.grpc.CallOptions; import io.grpc.ManagedChannel; import io.grpc.Status; import io.grpc.StatusException; import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class GrpcDirectStreamingCallableTest { private InProcessServer<FakeServiceImpl> inprocessServer; private ManagedChannel channel; private FakeServiceImpl serviceImpl; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws InstantiationException, IllegalAccessException, IOException { String serverName = "fakeservice"; serviceImpl = new FakeServiceImpl(); inprocessServer = new InProcessServer<>(serviceImpl, serverName); inprocessServer.start(); channel = InProcessChannelBuilder.forName(serverName).directExecutor().usePlaintext(true).build(); } @After public void tearDown() { channel.shutdown(); inprocessServer.stop(); } @Test public void testBidiStreaming() throws Exception { GrpcDirectBidiStreamingCallable<Color, Money> callable = new GrpcDirectBidiStreamingCallable<>(METHOD_STREAMING_RECOGNIZE); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); BidiStreamingCallable<Color, Money> streamingCallable = new EntryPointBidiStreamingCallable<>(callable, callContext); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(latch); Color request = Color.newBuilder().setRed(0.5f).build(); ApiStreamObserver<Color> requestObserver = streamingCallable.bidiStreamingCall(moneyObserver); requestObserver.onNext(request); requestObserver.onCompleted(); latch.await(20, TimeUnit.SECONDS); Truth.assertThat(moneyObserver.error).isNull(); Money expected = Money.newBuilder().setCurrencyCode("USD").setUnits(127).build(); Truth.assertThat(moneyObserver.response).isEqualTo(expected); Truth.assertThat(moneyObserver.completed).isTrue(); } @Test public void testBidiStreamingServerError() throws Exception { GrpcDirectBidiStreamingCallable<Color, Money> callable = new GrpcDirectBidiStreamingCallable<>(METHOD_STREAMING_RECOGNIZE_ERROR); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); BidiStreamingCallable<Color, Money> streamingCallable = new EntryPointBidiStreamingCallable<>(callable, callContext); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(latch); Color request = Color.newBuilder().setRed(0.5f).build(); ApiStreamObserver<Color> requestObserver = streamingCallable.bidiStreamingCall(moneyObserver); requestObserver.onNext(request); latch.await(20, TimeUnit.SECONDS); Truth.assertThat(moneyObserver.error).isNotNull(); Truth.assertThat(moneyObserver.error).isInstanceOf(StatusRuntimeException.class); Truth.assertThat(((StatusRuntimeException) moneyObserver.error).getStatus()) .isEqualTo(Status.INVALID_ARGUMENT); Truth.assertThat(moneyObserver.response).isNull(); } @Test public void testBidiStreamingClientError() throws Exception { GrpcDirectBidiStreamingCallable<Color, Money> callable = new GrpcDirectBidiStreamingCallable<>(METHOD_STREAMING_RECOGNIZE_ERROR); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); BidiStreamingCallable<Color, Money> streamingCallable = new EntryPointBidiStreamingCallable<>(callable, callContext); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(latch); Color request = Color.newBuilder().setRed(0.5f).build(); ApiStreamObserver<Color> requestObserver = streamingCallable.bidiStreamingCall(moneyObserver); Throwable clientError = new StatusRuntimeException(Status.CANCELLED); requestObserver.onError(clientError); latch.await(20, TimeUnit.SECONDS); Truth.assertThat(moneyObserver.error).isNotNull(); Truth.assertThat(moneyObserver.error).isInstanceOf(StatusRuntimeException.class); Truth.assertThat(((StatusRuntimeException) moneyObserver.error).getStatus().getCode()) .isEqualTo(Status.CANCELLED.getCode()); Truth.assertThat(moneyObserver.response).isNull(); StatusException serverReceivedError = (StatusException) serviceImpl.getLastRecievedError(); Truth.assertThat(serverReceivedError.getStatus()).isEqualTo(Status.CANCELLED); } @Test public void testServerStreaming() throws Exception { GrpcDirectServerStreamingCallable<Color, Money> callable = new GrpcDirectServerStreamingCallable<>( METHOD_SERVER_STREAMING_RECOGNIZE, GrpcDirectStreamingCallableTest.<Color>getRequestEncoder()); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); ServerStreamingCallable<Color, Money> streamingCallable = new EntryPointServerStreamingCallable<>(callable, callContext); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(latch); Color request = Color.newBuilder().setRed(0.5f).build(); streamingCallable.serverStreamingCall(request, moneyObserver); latch.await(20, TimeUnit.SECONDS); Truth.assertThat(moneyObserver.error).isNull(); Money expected = Money.newBuilder().setCurrencyCode("USD").setUnits(127).build(); Truth.assertThat(moneyObserver.response).isEqualTo(expected); } @Test public void testBlockingServerStreaming() throws Exception { GrpcDirectServerStreamingCallable<Color, Money> callable = new GrpcDirectServerStreamingCallable<>( METHOD_SERVER_STREAMING_RECOGNIZE, GrpcDirectStreamingCallableTest.<Color>getRequestEncoder()); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); ServerStreamingCallable<Color, Money> streamingCallable = new EntryPointServerStreamingCallable<>(callable, callContext); Color request = Color.newBuilder().setRed(0.5f).build(); Iterator<Money> response = streamingCallable.blockingServerStreamingCall(request); List<Money> responseData = new ArrayList<>(); Iterators.addAll(responseData, response); Money expected = Money.newBuilder().setCurrencyCode("USD").setUnits(127).build(); Truth.assertThat(responseData).containsExactly(expected); } @Test public void testClientStreaming() throws Exception { GrpcDirectClientStreamingCallable<Color, Money> callable = new GrpcDirectClientStreamingCallable<>(METHOD_CLIENT_STREAMING_RECOGNIZE); GrpcCallContext callContext = GrpcCallContext.of(channel, CallOptions.DEFAULT); ClientStreamingCallable<Color, Money> streamingCallable = new EntryPointClientStreamingCallable<>(callable, callContext); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(latch); Color request = Color.newBuilder().setRed(0.5f).build(); ApiStreamObserver<Color> requestObserver = streamingCallable.clientStreamingCall(moneyObserver); requestObserver.onNext(request); requestObserver.onCompleted(); latch.await(20, TimeUnit.SECONDS); Truth.assertThat(moneyObserver.error).isNull(); Money expected = Money.newBuilder().setCurrencyCode("USD").setUnits(127).build(); Truth.assertThat(moneyObserver.response).isEqualTo(expected); Truth.assertThat(moneyObserver.completed).isTrue(); } @Test public void testBadContext() { thrown.expect(IllegalArgumentException.class); GrpcDirectServerStreamingCallable<Color, Money> callable = new GrpcDirectServerStreamingCallable<>( METHOD_SERVER_STREAMING_RECOGNIZE, GrpcDirectStreamingCallableTest.<Color>getRequestEncoder()); ServerStreamingCallable<Color, Money> streamingCallable = new EntryPointServerStreamingCallable<>(callable, new ApiCallContext() {}); Color request = Color.newBuilder().setRed(0.5f).build(); streamingCallable.blockingServerStreamingCall(request); } private static <RequestT> RequestUrlParamsEncoder<RequestT> getRequestEncoder() { return new RequestUrlParamsEncoder<>(EmptyRequestParamsExtractor.<RequestT>of(), false); } private static class MoneyObserver implements ApiStreamObserver<Money> { volatile Money response; volatile Throwable error; volatile boolean completed; CountDownLatch latch; MoneyObserver(CountDownLatch latch) { this.latch = latch; } @Override public void onNext(Money value) { response = value; latch.countDown(); } @Override public void onError(Throwable t) { error = t; latch.countDown(); } @Override public void onCompleted() { completed = true; } }; }
/* * 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.alibaba.dubbo.remoting.transport.netty; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Date: 4/26/11 * Time: 4:13 PM */ public class NettyStringTest { static ExchangeServer server; static ExchangeChannel client; @BeforeClass public static void setUp() throws Exception { //int port = (int) (1000 * Math.random() + 10000); int port = 10001; System.out.println(port); server = Exchangers.bind(URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty"), new TelnetServerHandler()); client = Exchangers.connect(URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty"), new TelnetClientHandler()); } @AfterClass public static void tearDown() throws Exception { try { if (server != null) server.close(); } finally { if (client != null) client.close(); } } @Test public void testHandler() throws Exception { //Thread.sleep(20000); /*client.request("world\r\n"); Future future = client.request("world", 10000); String result = (String)future.get(); Assert.assertEquals("Did you say 'world'?\r\n",result);*/ } }
package de.derrop.labymod.addons.server; /* * Created by derrop on 29.09.2019 */ import lombok.*; import java.util.Map; import java.util.UUID; @ToString @EqualsAndHashCode @Getter @Setter @AllArgsConstructor public class PlayerData { private UUID uniqueId; private String name; private String gamemode; private Map<String, String> stats; private String lastMatchId; private long timestamp; public int getRank() { return this.stats.containsKey("rank") ? Integer.parseInt(this.stats.get("rank")) : -1; } }
package com.packetpublishing.tddjava.ch09; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by lj1218. * Date: 2019/11/25 */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
package xyz.klenkiven.kmall.gateway; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class KmallGatewayApplicationTests { @Test void contextLoads() { } }
/* * 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.dubbo.config; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; /** * The shutdown hook thread to do the clean up stuff. * This is a singleton in order to ensure there is only one shutdown hook registered. * Because {@link ApplicationShutdownHooks} use {@link java.util.IdentityHashMap} * to store the shutdown hooks. */ public class DubboShutdownHook extends Thread { private static final Logger logger = LoggerFactory.getLogger(DubboShutdownHook.class); private static final DubboShutdownHook DUBBO_SHUTDOWN_HOOK = new DubboShutdownHook("DubboShutdownHook"); private final ShutdownHookCallbacks callbacks = ShutdownHookCallbacks.INSTANCE; /** * Has it already been registered or not? */ private final AtomicBoolean registered = new AtomicBoolean(false); /** * Has it already been destroyed or not? */ private static final AtomicBoolean destroyed = new AtomicBoolean(false); private DubboShutdownHook(String name) { super(name); } public static DubboShutdownHook getDubboShutdownHook() { return DUBBO_SHUTDOWN_HOOK; } @Override public void run() { if (destroyed.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info("Run shutdown hook now."); } callback(); doDestroy(); } } /** * For testing purpose */ void clear() { callbacks.clear(); } private void callback() { callbacks.callback(); } /** * Register the ShutdownHook */ public void register() { if (registered.compareAndSet(false, true)) { DubboShutdownHook dubboShutdownHook = getDubboShutdownHook(); Runtime.getRuntime().addShutdownHook(dubboShutdownHook); } } /** * Unregister the ShutdownHook */ public void unregister() { if (registered.compareAndSet(true, false)) { DubboShutdownHook dubboShutdownHook = getDubboShutdownHook(); Runtime.getRuntime().removeShutdownHook(dubboShutdownHook); } } /** * Destroy all the resources, including registries and protocols. */ public void doDestroy() { if (logger.isInfoEnabled()) { logger.info("Dubbo Service has been destroyed."); } } public boolean getRegistered() { return registered.get(); } }
package com.c2b.ethWallet.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.c2b.ethWallet.entity.SystemCodeGroup; import com.c2b.ethWallet.mapper.SystemCodeGroupMapper; @Service public class SystemCodeGroupService { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private SystemCodeGroupMapper systemCodeGroupMapper; public int insert(SystemCodeGroup systemCodeGroup){ return systemCodeGroupMapper.insert(systemCodeGroup); } }
package mage.cards.o; import java.util.UUID; import mage.abilities.effects.common.DrawCardTargetEffect; import mage.abilities.keyword.RetraceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.TargetPlayer; /** * * @author Plopman */ public final class OonasGrace extends CardImpl { public OonasGrace(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{2}{U}"); // Target player draws a card. this.getSpellAbility().addEffect(new DrawCardTargetEffect(1)); this.getSpellAbility().addTarget(new TargetPlayer()); // Retrace this.addAbility(new RetraceAbility(this)); } private OonasGrace(final OonasGrace card) { super(card); } @Override public OonasGrace copy() { return new OonasGrace(this); } }
package br.com.vf.pontointeligente.api.security.controllers; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.vf.pontointeligente.api.response.Response; import br.com.vf.pontointeligente.api.security.dto.JwtAuthenticationDto; import br.com.vf.pontointeligente.api.security.dto.TokenDto; import br.com.vf.pontointeligente.api.security.utils.JwtTokenUtil; @RestController @RequestMapping("/auth") @CrossOrigin(origins = "*") public class AuthenticationController { private static final Logger log = LoggerFactory.getLogger(AuthenticationController.class); private static final String TOKEN_HEADER = "Authorization"; private static final String BEARER_PREFIX = "Bearer "; @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; /* http://localhost:8080/auth { "email" : "fulano@souza.com.br", "senha" : "123456" } Authorization = Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJmdWxhbm9Ac291emEuY29tLm */ /** * Gera e retorna um novo token JWT. * * @param authenticationDto * @param result * @return ResponseEntity<Response<TokenDto>> * @throws AuthenticationException */ @PostMapping public ResponseEntity<Response<TokenDto>> gerarTokenJwt( @Valid @RequestBody JwtAuthenticationDto authenticationDto, BindingResult result) throws AuthenticationException { Response<TokenDto> response = new Response<TokenDto>(); if (result.hasErrors()) { log.error("Erro validando lançamento: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } log.info("Gerando token para o email {}.", authenticationDto.getEmail()); Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( authenticationDto.getEmail(), authenticationDto.getSenha())); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationDto.getEmail()); String token = jwtTokenUtil.obterToken(userDetails); response.setData(new TokenDto(token)); return ResponseEntity.ok(response); } /** * Gera um novo token com uma nova data de expiração. * * @param request * @return ResponseEntity<Response<TokenDto>> */ @PostMapping(value = "/refresh") public ResponseEntity<Response<TokenDto>> gerarRefreshTokenJwt(HttpServletRequest request) { log.info("Gerando refresh token JWT."); Response<TokenDto> response = new Response<TokenDto>(); Optional<String> token = Optional.ofNullable(request.getHeader(TOKEN_HEADER)); if (token.isPresent() && token.get().startsWith(BEARER_PREFIX)) { token = Optional.of(token.get().substring(7)); } if (!token.isPresent()) { response.getErrors().add("Token não informado."); } else if (!jwtTokenUtil.tokenValido(token.get())) { response.getErrors().add("Token inválido ou expirado."); } if (!response.getErrors().isEmpty()) { return ResponseEntity.badRequest().body(response); } String refreshedToken = jwtTokenUtil.refreshToken(token.get()); response.setData(new TokenDto(refreshedToken)); return ResponseEntity.ok(response); } }
package com.aerolitec.SMXL.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import com.aerolitec.SMXL.R; import com.aerolitec.SMXL.model.Blog; import com.aerolitec.SMXL.ui.SMXL; import com.aerolitec.SMXL.ui.activity.BrowserActivity; import com.aerolitec.SMXL.ui.adapter.BlogAdapter; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class ListBlogsFragment extends Fragment { private ArrayList<Blog> blogs; private GridView gridViewBlogs; private BlogAdapter adapter; public ListBlogsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); blogs = SMXL.getBlogDBManager().getAllBlogs(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_list_blogs, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); gridViewBlogs = (GridView) view.findViewById(R.id.gridViewBlogs); adapter = new BlogAdapter(getActivity(), R.layout.blog_item, blogs); gridViewBlogs.setAdapter(adapter); gridViewBlogs.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String urlBlog = blogs.get(position).getBlog_website(); if (urlBlog != null) { if (!urlBlog.startsWith("http://") && !urlBlog.startsWith("https://")) { urlBlog = "http://" + urlBlog; } Intent browserIntent = new Intent(getActivity(), BrowserActivity.class); browserIntent.putExtra("URL", urlBlog); browserIntent.putExtra("TITLE", blogs.get(position).getBlog_name()); startActivity(browserIntent); } } }); } }
/* * Minecraft Forge * Copyright (c) 2016-2020. * * 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 version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.userdev; import cpw.mods.modlauncher.api.ILaunchHandlerService; import cpw.mods.modlauncher.api.ITransformingClassLoader; import net.minecraftforge.api.distmarker.Dist; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.Callable; import static net.minecraftforge.fml.loading.LogMarkers.CORE; public class FMLUserdevDataLaunchProvider extends FMLUserdevLaunchProvider implements ILaunchHandlerService { private static final Logger LOGGER = LogManager.getLogger(); @Override public String name() { return "fmluserdevdata"; } @Override public Callable<Void> launchService(String[] arguments, ITransformingClassLoader launchClassLoader) { return () -> { LOGGER.debug(CORE, "Launching minecraft in {} with arguments {}", launchClassLoader, arguments); super.beforeStart(launchClassLoader); launchClassLoader.addTargetPackageFilter(getPackagePredicate()); Thread.currentThread().setContextClassLoader(launchClassLoader.getInstance()); Class.forName("net.minecraft.data.Main", true, launchClassLoader.getInstance()).getMethod("main", String[].class).invoke(null, (Object)arguments); return null; }; } @Override public Dist getDist() { return Dist.CLIENT; } @Override public boolean isData() { return true; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.painless.node; import org.elasticsearch.painless.CompilerSettings; import org.elasticsearch.painless.Globals; import org.elasticsearch.painless.Locals; import org.elasticsearch.painless.Location; import org.elasticsearch.painless.MethodWriter; import org.elasticsearch.painless.Operation; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import java.util.Objects; import java.util.Set; /** * Represents a boolean expression. */ public final class EBool extends AExpression { private final Operation operation; private AExpression left; private AExpression right; public EBool(Location location, Operation operation, AExpression left, AExpression right) { super(location); this.operation = Objects.requireNonNull(operation); this.left = Objects.requireNonNull(left); this.right = Objects.requireNonNull(right); } @Override void storeSettings(CompilerSettings settings) { left.storeSettings(settings); right.storeSettings(settings); } @Override void extractVariables(Set<String> variables) { left.extractVariables(variables); right.extractVariables(variables); } @Override void analyze(Locals locals) { left.expected = boolean.class; left.analyze(locals); left = left.cast(locals); right.expected = boolean.class; right.analyze(locals); right = right.cast(locals); if (left.constant != null && right.constant != null) { if (operation == Operation.AND) { constant = (boolean)left.constant && (boolean)right.constant; } else if (operation == Operation.OR) { constant = (boolean)left.constant || (boolean)right.constant; } else { throw createError(new IllegalStateException("Illegal tree structure.")); } } actual = boolean.class; } @Override void write(MethodWriter writer, Globals globals) { if (operation == Operation.AND) { Label fals = new Label(); Label end = new Label(); left.write(writer, globals); writer.ifZCmp(Opcodes.IFEQ, fals); right.write(writer, globals); writer.ifZCmp(Opcodes.IFEQ, fals); writer.push(true); writer.goTo(end); writer.mark(fals); writer.push(false); writer.mark(end); } else if (operation == Operation.OR) { Label tru = new Label(); Label fals = new Label(); Label end = new Label(); left.write(writer, globals); writer.ifZCmp(Opcodes.IFNE, tru); right.write(writer, globals); writer.ifZCmp(Opcodes.IFEQ, fals); writer.mark(tru); writer.push(true); writer.goTo(end); writer.mark(fals); writer.push(false); writer.mark(end); } else { throw createError(new IllegalStateException("Illegal tree structure.")); } } @Override public String toString() { return singleLineToString(left, operation.symbol, right); } }
/* * 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.syncope.client.console.wizards.resources; import java.io.Serializable; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.syncope.client.console.panels.ProvisionAuxClassesPanel; import org.apache.syncope.client.console.rest.ConnectorRestClient; import org.apache.syncope.client.console.wizards.BaseAjaxWizardBuilder; import org.apache.syncope.client.console.wizards.mapping.ItemTransformersTogglePanel; import org.apache.syncope.client.console.wizards.mapping.JEXLTransformersTogglePanel; import org.apache.syncope.client.ui.commons.ConnIdSpecialName; import org.apache.syncope.client.ui.commons.Constants; import org.apache.syncope.client.ui.commons.ajax.form.IndicatorAjaxFormComponentUpdatingBehavior; import org.apache.syncope.client.ui.commons.markup.html.form.AjaxCheckBoxPanel; import org.apache.syncope.client.ui.commons.markup.html.form.AjaxTextFieldPanel; import org.apache.syncope.common.lib.to.MappingTO; import org.apache.syncope.common.lib.to.ProvisionTO; import org.apache.syncope.common.lib.to.ResourceTO; import org.apache.syncope.common.lib.types.AnyTypeKind; import org.apache.wicket.PageReference; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.wizard.WizardModel; import org.apache.wicket.extensions.wizard.WizardModel.ICondition; import org.apache.wicket.extensions.wizard.WizardStep; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.model.StringResourceModel; public class ProvisionWizardBuilder extends BaseAjaxWizardBuilder<ResourceProvision> { private static final long serialVersionUID = 3739399543837732640L; private final ResourceTO resourceTO; private final String adminRealm; protected AjaxTextFieldPanel clazz; /** * The object type specification step. */ private final class ObjectType extends WizardStep { private static final long serialVersionUID = -1657800545799468278L; ObjectType(final ResourceProvision resourceProvision) { super(new ResourceModel("clazz.title", StringUtils.EMPTY), new ResourceModel("clazz.summary", StringUtils.EMPTY), new Model<>(resourceProvision)); WebMarkupContainer container = new WebMarkupContainer("container"); container.setOutputMarkupId(true); add(container); clazz = new AjaxTextFieldPanel( "clazz", "clazz", new PropertyModel<>(resourceProvision, "objectClass")); clazz.setRequired(true); clazz.setChoices(ConnectorRestClient.getObjectClasses(resourceTO.getConnector())); container.add(clazz); AjaxCheckBoxPanel ignoreCaseMatch = new AjaxCheckBoxPanel( "ignoreCaseMatch", "ignoreCaseMatch", new PropertyModel<>(resourceProvision, "ignoreCaseMatch")); container.add(ignoreCaseMatch); } } protected void setObjectClassModelObject(final String type) { if (clazz != null) { if (AnyTypeKind.USER.name().equals(type)) { clazz.setModelObject(ConnIdSpecialName.ACCOUNT); } else if (AnyTypeKind.GROUP.name().equals(type)) { clazz.setModelObject(ConnIdSpecialName.GROUP); } else { clazz.setModelObject(""); } } } /** * AuxClasses definition step. */ private static final class AuxClasses extends WizardStep implements ICondition { private static final long serialVersionUID = 5315236191866427500L; private final ResourceProvision provision; AuxClasses(final ResourceProvision resourceProvision) { this.provision = resourceProvision; setTitleModel(new ResourceModel("auxClasses.title")); setSummaryModel(new StringResourceModel("auxClasses.summary", this, new Model<>(resourceProvision))); add(new ProvisionAuxClassesPanel("auxClasses", resourceProvision.getProvisionTO())); } @Override public boolean evaluate() { return provision.getProvisionTO() != null; } } /** * Mapping definition step. */ private static final class Mapping extends WizardStep { private static final long serialVersionUID = 3454904947720856253L; Mapping() { setTitleModel(Model.of("Mapping")); setSummaryModel(Model.of(StringUtils.EMPTY)); } } /** * AccountLink specification step. */ private static final class ConnObjectLink extends WizardStep { private static final long serialVersionUID = 2359955465172450478L; ConnObjectLink(final ResourceProvision resourceProvision) { super(new ResourceModel("link.title", StringUtils.EMPTY), new ResourceModel("link.summary", StringUtils.EMPTY)); WebMarkupContainer connObjectLinkContainer = new WebMarkupContainer("connObjectLinkContainer"); connObjectLinkContainer.setOutputMarkupId(true); add(connObjectLinkContainer); boolean connObjectLinkEnabled = false; if (StringUtils.isNotBlank(resourceProvision.getConnObjectLink())) { connObjectLinkEnabled = true; } final AjaxCheckBoxPanel connObjectLinkCheckbox = new AjaxCheckBoxPanel( "connObjectLinkCheckbox", new ResourceModel("connObjectLinkCheckbox", "connObjectLinkCheckbox").getObject(), new Model<>(connObjectLinkEnabled), false); connObjectLinkCheckbox.setEnabled(true); connObjectLinkContainer.add(connObjectLinkCheckbox); final AjaxTextFieldPanel connObjectLink = new AjaxTextFieldPanel( "connObjectLink", new ResourceModel("connObjectLink", "connObjectLink").getObject(), new PropertyModel<>(resourceProvision, "connObjectLink"), false); connObjectLink.enableJexlHelp(); connObjectLink.setEnabled(connObjectLinkEnabled); connObjectLinkContainer.add(connObjectLink); connObjectLinkCheckbox.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) { private static final long serialVersionUID = -1107858522700306810L; @Override protected void onUpdate(final AjaxRequestTarget target) { connObjectLink.setEnabled(connObjectLinkCheckbox.getModelObject()); connObjectLink.setModelObject(""); target.add(connObjectLink); } }); } } /** * Construct. * * @param resourceTO external resource to be updated. * @param adminRealm admin realm * @param pageRef Caller page reference. */ public ProvisionWizardBuilder(final ResourceTO resourceTO, final String adminRealm, final PageReference pageRef) { super(new ResourceProvision(), pageRef); this.resourceTO = resourceTO; this.adminRealm = adminRealm; } @Override protected WizardModel buildModelSteps(final ResourceProvision resourceProvision, final WizardModel wizardModel) { wizardModel.add(new ObjectType(resourceProvision)); wizardModel.add(new AuxClasses(resourceProvision)); Mapping mapping = new Mapping(); mapping.setOutputMarkupId(true); ItemTransformersTogglePanel itemTransformers = new ItemTransformersTogglePanel(mapping, pageRef); addOuterObject(itemTransformers); JEXLTransformersTogglePanel jexlTransformers = new JEXLTransformersTogglePanel(mapping, pageRef); addOuterObject(jexlTransformers); if (resourceProvision.getProvisionTO() != null && resourceProvision.getProvisionTO().getMapping() == null) { resourceProvision.getProvisionTO().setMapping(new MappingTO()); } mapping.add(new ResourceMappingPanel( "mapping", resourceTO, adminRealm, resourceProvision, itemTransformers, jexlTransformers)); wizardModel.add(mapping); wizardModel.add(new ConnObjectLink(resourceProvision)); return wizardModel; } @Override protected Serializable onApplyInternal(final ResourceProvision resourceProvision) { if (resourceProvision.getOrgUnitTO() != null) { this.resourceTO.setOrgUnit(resourceProvision.getOrgUnitTO()); this.resourceTO.getOrgUnit().getItems().clear(); this.resourceTO.getOrgUnit().getItems().addAll(resourceProvision.getItems()); } else if (resourceProvision.getProvisionTO() != null) { final List<ProvisionTO> provisions; if (resourceProvision.getKey() == null) { provisions = this.resourceTO.getProvisions().stream(). filter(object -> !resourceProvision.getAnyType().equals(object.getAnyType())). collect(Collectors.toList()); } else { provisions = this.resourceTO.getProvisions().stream(). filter(object -> !resourceProvision.getKey().equals(object.getKey())). collect(Collectors.toList()); } ProvisionTO provisionTO = resourceProvision.getProvisionTO(); provisionTO.getMapping().getItems().clear(); provisionTO.getMapping().getItems().addAll(resourceProvision.getItems()); provisions.add(provisionTO); this.resourceTO.getProvisions().clear(); this.resourceTO.getProvisions().addAll(provisions); } return resourceProvision; } }
package com.bizzan.bitrade.controller.activity; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import com.bizzan.bitrade.constant.PageModel; import com.bizzan.bitrade.constant.SignStatus; import com.bizzan.bitrade.controller.common.BaseAdminController; import com.bizzan.bitrade.entity.Sign; import com.bizzan.bitrade.model.create.SignCreate; import com.bizzan.bitrade.model.screen.SignScreen; import com.bizzan.bitrade.model.update.SignUpdate; import com.bizzan.bitrade.model.vo.SignVO; import com.bizzan.bitrade.service.CoinService; import com.bizzan.bitrade.service.SignService; import com.bizzan.bitrade.util.BindingResultUtil; import com.bizzan.bitrade.util.MessageResult; import javax.validation.Valid; /** * @author Hevin QQ:390330302 E-mail:xunibidev@gmail.com * @Description: * @date 2019/5/3 */ @RestController @RequestMapping("activity/sign") public class SignController extends BaseAdminController { @Autowired private SignService service; @Autowired private CoinService coinService; //创建 @RequiresPermissions("activity:sign:post") @PostMapping public MessageResult create(@Valid SignCreate model, BindingResult bindingResult) { MessageResult result = BindingResultUtil.validate(bindingResult); if (result != null) { return result; } service.save(model.transformation(service, coinService)); return success(); } //更新 @RequiresPermissions("activity:sign:put") @PutMapping("{id}") public MessageResult update(@Valid SignUpdate model, BindingResult bindingResult, @PathVariable("id") Long id) { MessageResult result = BindingResultUtil.validate(bindingResult); if (result != null) { return result; } //校验id Sign sign = service.findById(id); Assert.notNull(sign, "validate id!"); //转化 sign = model.transformation(coinService, sign); //保存 service.save(sign); return success(); } //分页 @RequiresPermissions("activity:sign:page-query") @GetMapping("page-query") public MessageResult pageQuery(SignScreen screen, PageModel pageModel) { Page<Sign> source = service.findAllScreen(screen, pageModel); Page<SignVO> page = source.map(x -> SignVO.getSignVO(x)); return success(page); } //详情 @RequiresPermissions("activity:sign:id:get") @GetMapping("{id}") public MessageResult detail(@PathVariable("id") Long id) { //校验id Sign sign = service.findById(id); Assert.notNull(sign, "validate id!"); SignVO signVO = SignVO.getSignVO(sign); return success(signVO); } // 提前关闭 @RequiresPermissions("activity:sign:id:early-closing") @PatchMapping("{id}/early-closing") public MessageResult earlyClosing(@PathVariable("id") Long id) { //校验id Sign sign = service.findById(id); Assert.notNull(sign, "validate id!"); Assert.isTrue(sign.getStatus() == SignStatus.UNDERWAY, "validate status!"); service.earlyClosing(sign); return success(); } //判断是否存在惊醒中 @GetMapping("has-underway") public MessageResult is() { Sign sign = service.fetchUnderway(); if (sign != null) { return success(true); } else { return success(false); } } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.rest.impl.optimize; import com.fasterxml.jackson.databind.ObjectMapper; import org.camunda.bpm.engine.history.HistoricActivityInstance; import org.camunda.bpm.engine.history.HistoricDecisionInstance; import org.camunda.bpm.engine.history.HistoricIncident; import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.history.HistoricTaskInstance; import org.camunda.bpm.engine.history.HistoricVariableUpdate; import org.camunda.bpm.engine.history.UserOperationLogEntry; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.persistence.entity.HistoricIncidentEntity; import org.camunda.bpm.engine.impl.persistence.entity.optimize.OptimizeHistoricIdentityLinkLogEntity; import org.camunda.bpm.engine.rest.dto.converter.DateConverter; import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; import org.camunda.bpm.engine.rest.dto.history.HistoricIncidentDto; import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceDto; import org.camunda.bpm.engine.rest.dto.history.UserOperationLogEntryDto; import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricActivityInstanceDto; import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricIdentityLinkLogDto; import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricVariableUpdateDto; import org.camunda.bpm.engine.rest.impl.AbstractRestProcessEngineAware; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.Date; import java.util.List; @Produces(MediaType.APPLICATION_JSON) public class OptimizeRestService extends AbstractRestProcessEngineAware { public static final String PATH = "/optimize"; private final DateConverter dateConverter; public OptimizeRestService(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); dateConverter = new DateConverter(); dateConverter.setObjectMapper(objectMapper); } @GET @Path("/activity-instance/completed") public List<OptimizeHistoricActivityInstanceDto> getCompletedHistoricActivityInstances(@QueryParam("finishedAfter") String finishedAfterAsString, @QueryParam("finishedAt") String finishedAtAsString, @QueryParam("maxResults") int maxResults) { Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricActivityInstance> historicActivityInstances = config.getOptimizeService().getCompletedHistoricActivityInstances(finishedAfter, finishedAt, maxResults); List<OptimizeHistoricActivityInstanceDto> result = new ArrayList<>(); for (HistoricActivityInstance instance : historicActivityInstances) { OptimizeHistoricActivityInstanceDto dto = OptimizeHistoricActivityInstanceDto.fromHistoricActivityInstance(instance); result.add(dto); } return result; } @GET @Path("/activity-instance/running") public List<OptimizeHistoricActivityInstanceDto> getRunningHistoricActivityInstances(@QueryParam("startedAfter") String startedAfterAsString, @QueryParam("startedAt") String startedAtAsString, @QueryParam("maxResults") int maxResults) { Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricActivityInstance> historicActivityInstances = config.getOptimizeService().getRunningHistoricActivityInstances(startedAfter, startedAt, maxResults); List<OptimizeHistoricActivityInstanceDto> result = new ArrayList<>(); for (HistoricActivityInstance instance : historicActivityInstances) { OptimizeHistoricActivityInstanceDto dto = OptimizeHistoricActivityInstanceDto.fromHistoricActivityInstance(instance); result.add(dto); } return result; } @GET @Path("/task-instance/completed") public List<HistoricTaskInstanceDto> getCompletedHistoricTaskInstances(@QueryParam("finishedAfter") String finishedAfterAsString, @QueryParam("finishedAt") String finishedAtAsString, @QueryParam("maxResults") int maxResults) { Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricTaskInstance> historicTaskInstances = config.getOptimizeService().getCompletedHistoricTaskInstances(finishedAfter, finishedAt, maxResults); List<HistoricTaskInstanceDto> result = new ArrayList<>(); for (HistoricTaskInstance instance : historicTaskInstances) { HistoricTaskInstanceDto dto = HistoricTaskInstanceDto.fromHistoricTaskInstance(instance); result.add(dto); } return result; } @GET @Path("/task-instance/running") public List<HistoricTaskInstanceDto> getRunningHistoricTaskInstances(@QueryParam("startedAfter") String startedAfterAsString, @QueryParam("startedAt") String startedAtAsString, @QueryParam("maxResults") int maxResults) { Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricTaskInstance> historicTaskInstances = config.getOptimizeService().getRunningHistoricTaskInstances(startedAfter, startedAt, maxResults); List<HistoricTaskInstanceDto> result = new ArrayList<>(); for (HistoricTaskInstance instance : historicTaskInstances) { HistoricTaskInstanceDto dto = HistoricTaskInstanceDto.fromHistoricTaskInstance(instance); result.add(dto); } return result; } @GET @Path("/user-operation") public List<UserOperationLogEntryDto> getHistoricUserOperationLogs(@QueryParam("occurredAfter") String occurredAfterAsString, @QueryParam("occurredAt") String occurredAtAsString, @QueryParam("maxResults") int maxResults) { Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<UserOperationLogEntry> operationLogEntries = config.getOptimizeService().getHistoricUserOperationLogs(occurredAfter, occurredAt, maxResults); List<UserOperationLogEntryDto> result = new ArrayList<>(); for (UserOperationLogEntry logEntry : operationLogEntries) { UserOperationLogEntryDto dto = UserOperationLogEntryDto.map(logEntry); result.add(dto); } return result; } @GET @Path("/identity-link-log") public List<OptimizeHistoricIdentityLinkLogDto> getHistoricIdentityLinkLogs(@QueryParam("occurredAfter") String occurredAfterAsString, @QueryParam("occurredAt") String occurredAtAsString, @QueryParam("maxResults") int maxResults) { Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<OptimizeHistoricIdentityLinkLogEntity> operationLogEntries = config.getOptimizeService().getHistoricIdentityLinkLogs(occurredAfter, occurredAt, maxResults); List<OptimizeHistoricIdentityLinkLogDto> result = new ArrayList<>(); for (OptimizeHistoricIdentityLinkLogEntity logEntry : operationLogEntries) { OptimizeHistoricIdentityLinkLogDto dto = OptimizeHistoricIdentityLinkLogDto.fromHistoricIdentityLink(logEntry); result.add(dto); } return result; } @GET @Path("/process-instance/completed") public List<HistoricProcessInstanceDto> getCompletedHistoricProcessInstances(@QueryParam("finishedAfter") String finishedAfterAsString, @QueryParam("finishedAt") String finishedAtAsString, @QueryParam("maxResults") int maxResults) { Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricProcessInstance> historicProcessInstances = config.getOptimizeService().getCompletedHistoricProcessInstances(finishedAfter, finishedAt, maxResults); List<HistoricProcessInstanceDto> result = new ArrayList<>(); for (HistoricProcessInstance instance : historicProcessInstances) { HistoricProcessInstanceDto dto = HistoricProcessInstanceDto.fromHistoricProcessInstance(instance); result.add(dto); } return result; } @GET @Path("/process-instance/running") public List<HistoricProcessInstanceDto> getRunningHistoricProcessInstances(@QueryParam("startedAfter") String startedAfterAsString, @QueryParam("startedAt") String startedAtAsString, @QueryParam("maxResults") int maxResults) { Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricProcessInstance> historicProcessInstances = config.getOptimizeService().getRunningHistoricProcessInstances(startedAfter, startedAt, maxResults); List<HistoricProcessInstanceDto> result = new ArrayList<>(); for (HistoricProcessInstance instance : historicProcessInstances) { HistoricProcessInstanceDto dto = HistoricProcessInstanceDto.fromHistoricProcessInstance(instance); result.add(dto); } return result; } @GET @Path("/variable-update") public List<OptimizeHistoricVariableUpdateDto> getHistoricVariableUpdates(@QueryParam("occurredAfter") String occurredAfterAsString, @QueryParam("occurredAt") String occurredAtAsString, @QueryParam("maxResults") int maxResults) { Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricVariableUpdate> historicVariableUpdates = config.getOptimizeService().getHistoricVariableUpdates(occurredAfter, occurredAt, maxResults); List<OptimizeHistoricVariableUpdateDto> result = new ArrayList<>(); for (HistoricVariableUpdate instance : historicVariableUpdates) { OptimizeHistoricVariableUpdateDto dto = OptimizeHistoricVariableUpdateDto.fromHistoricVariableUpdate(instance); result.add(dto); } return result; } @GET @Path("/incident/completed") public List<HistoricIncidentDto> getCompletedHistoricIncidents(@QueryParam("finishedAfter") String finishedAfterAsString, @QueryParam("finishedAt") String finishedAtAsString, @QueryParam("maxResults") int maxResults) { Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricIncidentEntity> historicIncidents = config.getOptimizeService().getCompletedHistoricIncidents(finishedAfter, finishedAt, maxResults); List<HistoricIncidentDto> result = new ArrayList<>(); for (HistoricIncident instance : historicIncidents) { HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(instance); result.add(dto); } return result; } @GET @Path("/incident/open") public List<HistoricIncidentDto> getOpenHistoricIncidents(@QueryParam("createdAfter") String createdAfterAsString, @QueryParam("createdAt") String createdAtAsString, @QueryParam("maxResults") int maxResults) { Date createdAfter = dateConverter.convertQueryParameterToType(createdAfterAsString); Date createdAt = dateConverter.convertQueryParameterToType(createdAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricIncidentEntity> historicIncidents = config.getOptimizeService().getOpenHistoricIncidents(createdAfter, createdAt, maxResults); List<HistoricIncidentDto> result = new ArrayList<>(); for (HistoricIncident instance : historicIncidents) { HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(instance); result.add(dto); } return result; } @GET @Path("/decision-instance") public List<HistoricDecisionInstanceDto> getHistoricDecisionInstances(@QueryParam("evaluatedAfter") String evaluatedAfterAsString, @QueryParam("evaluatedAt") String evaluatedAtAsString, @QueryParam("maxResults") int maxResults) { Date evaluatedAfter = dateConverter.convertQueryParameterToType(evaluatedAfterAsString); Date evaluatedAt = dateConverter.convertQueryParameterToType(evaluatedAtAsString); maxResults = ensureValidMaxResults(maxResults); ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); List<HistoricDecisionInstance> historicDecisionInstances = config.getOptimizeService().getHistoricDecisionInstances(evaluatedAfter, evaluatedAt, maxResults); List<HistoricDecisionInstanceDto> resultList = new ArrayList<>(); for (HistoricDecisionInstance historicDecisionInstance : historicDecisionInstances) { HistoricDecisionInstanceDto dto = HistoricDecisionInstanceDto.fromHistoricDecisionInstance(historicDecisionInstance); resultList.add(dto); } return resultList; } protected int ensureValidMaxResults(int givenMaxResults) { return givenMaxResults > 0 ? givenMaxResults : Integer.MAX_VALUE; } }
package com.github.matiasvergaras.finalreality.model.Mastermind; import com.github.matiasvergaras.finalreality.controller.handlers.DeathCharacterToMMHandler; import com.github.matiasvergaras.finalreality.controller.handlers.EndTurnCharacterToMMHandler; import com.github.matiasvergaras.finalreality.controller.handlers.AddQueueCharacterToMMHandler; import com.github.matiasvergaras.finalreality.model.character.ICharacter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeSupport; import java.util.ArrayList; /** * Class to hold the common behavior of both CPUMastermind and PlayerMastermind. * @since Homework 2 * @author Matías Vergara Silva. */ public abstract class AbstractMastermind implements IMastermind{ protected ArrayList<ICharacter> party; protected String name; protected PropertyChangeSupport deadCharacter = new PropertyChangeSupport(this); protected PropertyChangeSupport endTurn = new PropertyChangeSupport(this); protected PropertyChangeSupport addQueue = new PropertyChangeSupport(this); protected DeathCharacterToMMHandler deadCharacterHandler = new DeathCharacterToMMHandler(this); protected EndTurnCharacterToMMHandler endTurnHandler = new EndTurnCharacterToMMHandler(this); protected AddQueueCharacterToMMHandler addQueueHandler = new AddQueueCharacterToMMHandler(this); protected int aliveCharacters; /** * Basic constructor for a Mastermind */ public AbstractMastermind(String name){ this.name = name; this.party = new ArrayList<>(); } /** * Adds a character to the Mastermind's Party and calls to * his waitTurn method. * @param character The ICharacter character to be added. */ @Override public void addToParty(ICharacter character){ this.aliveCharacters++; this.getParty().add(character); character.getDeadCharacter().addPropertyChangeListener(deadCharacterHandler); character.getEndTurn().addPropertyChangeListener(endTurnHandler); character.getAddQueue().addPropertyChangeListener(addQueueHandler); } /** * {@inheritDoc} * @return The number of alive characters of this mastermind. */ @Override public int getAliveCharacters(){ return this.aliveCharacters; } /** * Gives the number of characters in the mastermind's party. * @return the number of characters in the userPlayer party. */ @Override public int getPartySize(){ return party.size(); } /** * Gives the party of the mastermind's. * @return An ArrayList of ICharacter representing all the characters of the mastermind's together. */ @Override public ArrayList<ICharacter> getParty(){ return party; } /** * Removes a character from the mastermind's party. * @param character The ICharacter character to be removed. */ @Override public void removeFromParty(ICharacter character){ this.getParty().remove(character); } /** * {@inheritDoc} * <p> Controller will be in charge of avoid passing an index grater than the size-1. </p> * <p> Therefore, this method will not verify it. </p> * @param index The position of the character to be returned in the party. * @return The character in the 'index' position of the party. */ @Override public ICharacter getCharacterFromParty(int index){ return getParty().get(index); } /** * Makes a character performs a normal attack against another. * <p> Controller will be in charge of check that the characters are in different teams. * Mastermind will only check that the attacker character is in his party. </p> * @param character The character that will perform the attack. * @param target The character that will receive the attack. */ @Override public void makeNormalAttack(ICharacter character, ICharacter target){ if(this.getParty().contains(character)){ character.normalAttack(target); } } /** *{@inheritDoc} * @return The name of the PlayerMastermind. */ @Override public String getName(){ return name; } /** * Alerts the gameController that a character died. */ public void deadCharacter(ICharacter character){ this.aliveCharacters--; deadCharacter.firePropertyChange(new PropertyChangeEvent(character, "aliveCharacters Changed", aliveCharacters+1, aliveCharacters)); } /** * {@inheritDoc} */ public void endTurn(){ endTurn.firePropertyChange(new PropertyChangeEvent( this, "Active character ended his turn", "Active", "Inactive")); } /** * * @return propertyChangeSupport of Character's death, in order to be able to use it outside of this class. */ public PropertyChangeSupport getDeadCharacter(){ return deadCharacter; } /** * * @return propertyChangeSupport of Character's death, in order to be able to use it outside of this class. */ public PropertyChangeSupport getEndTurn(){ return endTurn; } /** * * @return propertyChangeSupport of Character added to queue, * in order to be able to use it outside of this class. */ public PropertyChangeSupport getAddQueue() { return addQueue;} /** * {@inheritDoc} */ public void characterAddedToQueue(){ addQueue.firePropertyChange(new PropertyChangeEvent(this, "Character added", "Out of queue", "In queue")); } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * 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 net.TheElm.project.mixins.World; import net.TheElm.project.CoreMod; import net.TheElm.project.enums.ClaimPermissions; import net.TheElm.project.enums.ClaimRanks; import net.TheElm.project.enums.ClaimSettings; import net.TheElm.project.exceptions.TranslationKeyException; import net.TheElm.project.interfaces.Claim; import net.TheElm.project.interfaces.IClaimedChunk; import net.TheElm.project.protections.claiming.ClaimantPlayer; import net.TheElm.project.protections.claiming.ClaimantTown; import net.TheElm.project.utilities.ChunkUtils; import net.TheElm.project.utilities.ChunkUtils.ClaimSlice; import net.TheElm.project.utilities.ChunkUtils.InnerClaim; import net.TheElm.project.utilities.nbt.NbtUtils; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.nbt.NbtList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; import net.minecraft.world.HeightLimitView; import net.minecraft.world.chunk.Chunk; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.UUID; @Mixin(Chunk.class) public abstract class ClaimedChunk implements BlockView, IClaimedChunk, Claim { private final ClaimSlice[] claimSlices = new ClaimSlice[256]; private WeakReference<ClaimantTown> chunkTown = null; private ClaimantPlayer chunkPlayer = null; @Shadow @Final protected HeightLimitView heightLimitView; @Shadow public native void setNeedsSaving(boolean shouldSave); @Override public ClaimantTown updateTownOwner(@Nullable UUID owner, boolean fresh) { ClaimantTown town = null; if (owner != null) town = ClaimantTown.get(owner); // Make sure we have the towns permissions cached this.chunkTown = (town == null ? null : new WeakReference<>(town)); if ( fresh ) this.setNeedsSaving(true); return this.getTown(); } private ClaimantTown loadTownReference(@NotNull ClaimantTown town) { return (this.chunkTown = new WeakReference<>(town)).get(); } @Override public ClaimantPlayer updatePlayerOwner(@Nullable UUID owner, boolean fresh) { this.chunkPlayer = ( owner == null ? null : ClaimantPlayer.get( owner )); if (fresh) this.setNeedsSaving(true); // If there is no player owner, there is no town if (owner == null) { // Reset the inner slices (SHOULD NOT RESET SPAWN) this.resetSlices(); this.updateTownOwner(null, fresh); } return this.chunkPlayer; } public void resetSlices() { ClaimSlice slice; for (int i = 0; i < this.claimSlices.length; i++) { if ((slice = this.claimSlices[i]) == null) continue; slice.reset(); } this.setNeedsSaving(true); } @Override public void updateSliceOwner(UUID owner, int slicePos, int yFrom, int yTo, boolean fresh) { // If heights are invalid if (this.heightLimitView.isOutOfHeightLimit(yFrom) || this.heightLimitView.isOutOfHeightLimit(yTo)) return; ClaimSlice slice; if ((slice = this.claimSlices[slicePos]) == null) slice = (this.claimSlices[slicePos] = new ClaimSlice(this.heightLimitView, slicePos)); // Get upper and lower positioning int yMax = Math.max(yFrom, yTo); int yMin = Math.min(yFrom, yTo); slice.insert(owner, yMax, yMin); // Make sure the chunk gets saved if ( fresh ) this.setNeedsSaving(true); } public UUID[] getSliceOwner(int slicePos, int yFrom, int yTo) { ClaimSlice slice; if ((slice = this.claimSlices[slicePos]) == null) return new UUID[0]; // Get upper and lower positioning int yMax = Math.max(yFrom, yTo); int yMin = Math.min(yFrom, yTo); // Get all owners Set<UUID> owners = new HashSet<>(); for (int y = yMin; y <= yMax; y++) { InnerClaim claim = slice.get(y); if (claim != null) owners.add(claim.getOwner()); } return owners.toArray(new UUID[0]); } @Override public @NotNull ClaimSlice[] getSlices() { return this.claimSlices; } @Override public void setSlices(@NotNull ClaimSlice[] slices) { int c = slices.length; for (int i = 0; i < c; i++) this.claimSlices[i] = slices[i]; } public @NotNull Claim getClaim(BlockPos blockPos) { int slicePos = ChunkUtils.getPositionWithinChunk( blockPos ); ClaimSlice slice; if ((slice = this.claimSlices[slicePos]) != null) { // Get inside claim InnerClaim inner = slice.get(blockPos.getY()); // If claim inner is not nobody if (inner != null && inner.getOwner() != null && inner.isWithin(blockPos.getY())) return inner; } return this; } public boolean canPlayerClaim(@NotNull ClaimantPlayer player, boolean stopIfClaimed) throws TranslationKeyException { // If the chunk is owned, return false if (this.chunkPlayer != null) { if (stopIfClaimed) throw new TranslationKeyException("claim.chunk.error.claimed"); return false; } // Check claims limit (If the player is spawn, always allow) if (!player.getId().equals(CoreMod.SPAWN_ID) && !player.canClaim((Chunk)(Object) this)) throw new TranslationKeyException("claim.chunk.error.max"); return true; } public @Nullable UUID getOwner() { if (this.chunkPlayer == null) return null; return this.chunkPlayer.getId(); } public @Nullable UUID getOwner(BlockPos pos) { int slicePos = ChunkUtils.getPositionWithinChunk( pos ); if ( this.claimSlices[slicePos] != null ) { ClaimSlice slice = claimSlices[slicePos]; // Get the players Y position InnerClaim claim = slice.get(pos); // Check that the player is within the Y if (claim != null && claim.isWithin(pos)) return claim.getOwner(); } return this.getOwner(); } public @Nullable UUID getTownId() { ClaimantTown town; if ((town = this.getTown()) == null) return null; return town.getId(); } public @Nullable ClaimantTown getTown() { if (( this.chunkPlayer == null )) return null; if (this.chunkTown == null) { ClaimantTown playerTown; if ((playerTown = this.chunkPlayer.getTown()) != null) return this.loadTownReference(playerTown); } return (this.chunkTown == null ? null : this.chunkTown.get()); } @Override public boolean canPlayerDo(@Nullable UUID player, @Nullable ClaimPermissions perm) { if (this.chunkPlayer == null || (player != null && player.equals(this.chunkPlayer.getId()))) return true; ClaimantTown town; if ( ((town = this.getTown()) != null ) && (player != null) && player.equals( town.getOwner() ) ) return true; // Get the ranks of the user and the rank required for performing ClaimRanks userRank = this.chunkPlayer.getFriendRank(player); ClaimRanks permReq = this.chunkPlayer.getPermissionRankRequirement(perm); // Return the test if the user can perform the action (If friend of chunk owner OR if friend of town and chunk owned by town owner) return permReq.canPerform(userRank) || ((town != null) && (this.chunkPlayer.getId().equals(town.getOwner())) && permReq.canPerform(town.getFriendRank(player))); } @Override public boolean canPlayerDo(@NotNull BlockPos pos, @Nullable UUID player, @Nullable ClaimPermissions perm) { return this.getClaim(pos) .canPlayerDo(player, perm); } @Override public boolean isSetting(@NotNull ClaimSettings setting) { if (this.chunkPlayer == null) return setting.getDefault( this.getOwner() ); return this.chunkPlayer.getProtectedChunkSetting( setting ); } @Override public boolean isSetting(@NotNull BlockPos pos, @NotNull ClaimSettings setting) { if ( !setting.isEnabled() ) return setting.getDefault( this.getOwner() ); else return this.getClaim( pos ) .isSetting( setting ); } @Override public @NotNull NbtList serializeSlices() { NbtList serialized = new NbtList(); ClaimSlice slice; for (int i = 0; i < this.claimSlices.length; i++) { // Slice must be defined if ((slice = this.claimSlices[i]) == null) continue; // Create a new tag to save the slice NbtCompound sliceTag = new NbtCompound(); NbtList claimsTag = new NbtList(); // For all slice claims Iterator<InnerClaim> claims = slice.getClaims(); while ( claims.hasNext() ) { InnerClaim claim = claims.next(); // If bottom of world, or no owner if ((claim.lower() == -1) || (claim.getOwner() == null)) continue; // Save data to the tag NbtCompound claimTag = new NbtCompound(); claimTag.putUuid("owner", claim.getOwner()); claimTag.putInt("upper", claim.upper()); claimTag.putInt("lower", claim.lower()); // Add tag to array claimsTag.add(claimTag); } // Save data for slice sliceTag.putInt("i", i); sliceTag.put("claims", claimsTag); // Save the tag serialized.add(sliceTag); } return serialized; } @Override public void deserializeSlices(@NotNull NbtList serialized) { for (NbtElement tag : serialized) { // Must be compound tags if (!(tag instanceof NbtCompound sliceTag)) continue; NbtList claimsTag = sliceTag.getList("claims", NbtElement.COMPOUND_TYPE); int i = sliceTag.getInt("i"); for (NbtElement claimTag : claimsTag) { UUID owner = NbtUtils.getUUID((NbtCompound) claimTag,"owner"); int upper = ((NbtCompound) claimTag).getInt("upper"); int lower = ((NbtCompound) claimTag).getInt("lower"); this.updateSliceOwner(owner, i, lower, upper, false); } } } }
package pl.modulpierwszy_java; import java.util.Random; public class NumerTelefonu { public static void main(String[] args) { Random wylosowana = new Random(); // telefon wedlug schematu 0XXX-ZXXXXX int two = wylosowana.nextInt(10); int three = wylosowana.nextInt(10); int four = wylosowana.nextInt(10); int five = wylosowana.nextInt(10) + 1; // nie moze byc wylosowane zero int six = wylosowana.nextInt(10); int seven = wylosowana.nextInt(10); int eight = wylosowana.nextInt(10); int nine = wylosowana.nextInt(10); int ten = wylosowana.nextInt(10); System.out.println("0" + two + three + four + "-" + five + six + seven + eight + nine + ten); } }
package com.admin.core.exception; /** * 自定义异常基类 * * @author fei * @date 2017/10/2 */ public class AppException extends RuntimeException { private static final long serialVersionUID = 2404372373182554123L; /** 错误码 */ private int errorCode; /** 异常信息 */ private String errorMessage; /** 异常栈 */ private Throwable throwable; /** * 设置错误信息 * * @param errorMessage 错误信息 */ public AppException(String errorMessage) { super(errorMessage); this.throwable = this; this.errorMessage = errorMessage; } /** * 设置错误信息 * * @param errorMessage 错误信息 * @param throwable 异常对象 */ public AppException(String errorMessage, Throwable throwable) { super(errorMessage); this.errorMessage = errorMessage; this.throwable = throwable; } public AppException(int errorCode, String errorMessage) { super(errorMessage); this.throwable = this; this.errorCode = errorCode; this.errorMessage = errorMessage; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public Throwable getThrowable() { return throwable; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } }
package org.robolectric.shadows; import static org.assertj.core.api.Assertions.assertThat; import android.database.AbstractCursor; import android.net.Uri; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.TestRunners; @RunWith(TestRunners.MultiApiSelfTest.class) public class ShadowAbstractCursorTest { private TestCursor cursor; @Before public void setUp() throws Exception { cursor = new TestCursor(); } @Test public void testMoveToFirst() { cursor.theTable.add("Foobar"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(1); } @Test public void testMoveToFirstEmptyList() { assertThat(cursor.moveToFirst()).isFalse(); assertThat(cursor.getCount()).isEqualTo(0); } @Test public void testMoveToLast() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToLast()).isTrue(); assertThat(cursor.getCount()).isEqualTo(2); } @Test public void testMoveToLastEmptyList() { assertThat(cursor.moveToLast()).isFalse(); assertThat(cursor.getCount()).isEqualTo(0); } @Test public void testGetPosition() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(2); assertThat(cursor.getPosition()).isEqualTo(0); } @Test public void testGetPositionSingleEntry() { cursor.theTable.add("Foobar"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(1); assertThat(cursor.getPosition()).isEqualTo(0); } @Test public void testGetPositionEmptyList() { assertThat(cursor.moveToFirst()).isFalse(); assertThat(cursor.getCount()).isEqualTo(0); assertThat(cursor.getPosition()).isEqualTo(0); } @Test public void testMoveToNext() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(2); assertThat(cursor.moveToNext()).isTrue(); assertThat(cursor.getPosition()).isEqualTo(1); } @Test public void testAttemptToMovePastEnd() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(2); assertThat(cursor.moveToNext()).isTrue(); assertThat(cursor.getPosition()).isEqualTo(1); assertThat(cursor.isLast()).isTrue(); assertThat(cursor.moveToNext()).isFalse(); assertThat(cursor.isAfterLast()).isTrue(); assertThat(cursor.getPosition()).isEqualTo(2); } @Test public void testAttemptToMovePastSingleEntry() { cursor.theTable.add("Foobar"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.getCount()).isEqualTo(1); assertThat(cursor.moveToNext()).isFalse(); assertThat(cursor.getPosition()).isEqualTo(1); } @Test public void testAttemptToMovePastEmptyList() { assertThat(cursor.moveToFirst()).isFalse(); assertThat(cursor.getCount()).isEqualTo(0); assertThat(cursor.moveToNext()).isFalse(); assertThat(cursor.getPosition()).isEqualTo(0); } @Test public void testMoveToPrevious() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.moveToNext()).isTrue(); assertThat(cursor.getPosition()).isEqualTo(1); assertThat(cursor.moveToPrevious()).isTrue(); assertThat(cursor.getPosition()).isEqualTo(0); } @Test public void testAttemptToMovePastStart() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.moveToPrevious()).isFalse(); assertThat(cursor.getPosition()).isEqualTo(-1); } @Test public void testIsFirst() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); assertThat(cursor.isFirst()).isTrue(); cursor.moveToNext(); assertThat(cursor.isFirst()).isFalse(); cursor.moveToFirst(); cursor.moveToPrevious(); assertThat(cursor.isFirst()).isFalse(); } @Test public void testIsLast() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); cursor.moveToNext(); assertThat(cursor.isLast()).isTrue(); cursor.moveToPrevious(); assertThat(cursor.isLast()).isFalse(); cursor.moveToFirst(); cursor.moveToNext(); assertThat(cursor.isLast()).isTrue(); } @Test public void testIsBeforeFirst() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); cursor.moveToNext(); assertThat(cursor.isLast()).isTrue(); cursor.moveToPrevious(); assertThat(cursor.isLast()).isFalse(); cursor.moveToPrevious(); assertThat(cursor.isFirst()).isFalse(); cursor.moveToPrevious(); assertThat(cursor.isBeforeFirst()).isTrue(); } @Test public void testIsAfterLast() { cursor.theTable.add("Foobar"); cursor.theTable.add("Bletch"); assertThat(cursor.moveToFirst()).isTrue(); cursor.moveToNext(); assertThat(cursor.isLast()).isTrue(); cursor.moveToNext(); assertThat(cursor.isAfterLast()).isTrue(); cursor.moveToPrevious(); assertThat(cursor.isLast()).isTrue(); cursor.moveToPrevious(); assertThat(cursor.isLast()).isFalse(); cursor.moveToFirst(); cursor.moveToNext(); assertThat(cursor.isAfterLast()).isFalse(); cursor.moveToNext(); assertThat(cursor.isAfterLast()).isTrue(); } @Test public void testGetNotificationUri() { Uri uri = Uri.parse("content://foo.com"); ShadowAbstractCursor shadow = Shadows.shadowOf(cursor); assertThat(shadow.getNotificationUri_Compatibility()).isNull(); cursor.setNotificationUri(RuntimeEnvironment.application.getContentResolver(), uri); assertThat(shadow.getNotificationUri_Compatibility()).isEqualTo(uri); } @Test public void testIsClosedWhenAfterCallingClose() { assertThat(cursor.isClosed()).isFalse(); cursor.close(); assertThat(cursor.isClosed()).isTrue(); } private class TestCursor extends AbstractCursor { public List<Object> theTable = new ArrayList<>(); @Override public int getCount() { return theTable.size(); } @Override public String[] getColumnNames() { throw new UnsupportedOperationException(); } @Override public double getDouble(int columnIndex) { throw new UnsupportedOperationException(); } @Override public float getFloat(int columnIndex) { throw new UnsupportedOperationException(); } @Override public int getInt(int columnIndex) { throw new UnsupportedOperationException(); } @Override public long getLong(int columnIndex) { throw new UnsupportedOperationException(); } @Override public short getShort(int columnIndex) { throw new UnsupportedOperationException(); } @Override public String getString(int columnIndex) { throw new UnsupportedOperationException(); } @Override public boolean isNull(int columnIndex) { throw new UnsupportedOperationException(); } } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.configtest; /** * Just check we manage to compile something that requires configuration and * has no dependencies to Vespa. */ public class Demo { public final String greeting; public Demo(GreetingConfig config) { greeting = config.greeting(); } }
/* * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. * * 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.kefaming.uid.buffer; /** * If cursor catches the tail it means that the ring buffer is empty, any more buffer take request will be rejected. * Specify the policy to handle the reject. This is a Lambda supported interface * * @author yutianbao */ @FunctionalInterface public interface RejectedTakeBufferHandler { /** * Reject take buffer request * * @param ringBuffer */ void rejectTakeBuffer(RingBuffer ringBuffer); }
/* * Copyright 2017-2020 original 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 io.micronaut.transaction.support; import io.micronaut.core.annotation.NonNull; import io.micronaut.core.annotation.Nullable; import io.micronaut.aop.InterceptedProxy; import io.micronaut.core.annotation.Internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Objects; /** * Utility methods for triggering specific {@link TransactionSynchronization} * callback methods on all currently registered synchronizations. * * @author Juergen Hoeller * @author graemerocher * @since 1.0 * @see TransactionSynchronization * @see TransactionSynchronizationManager#getSynchronizations() */ @Internal public abstract class TransactionSynchronizationUtils { private static final Logger LOG = LoggerFactory.getLogger(TransactionSynchronizationUtils.class); /** * Check whether the given resource transaction managers refers to the given * (underlying) resource factory. * @see ResourceTransactionManager#getResourceFactory() * @param tm the resource manager * @param resourceFactory The resource factory * @return True if the factories are the same */ public static boolean sameResourceFactory(ResourceTransactionManager tm, Object resourceFactory) { return unwrapResourceIfNecessary(tm.getResourceFactory()).equals(unwrapResourceIfNecessary(resourceFactory)); } /** * Unwrap the given resource handle if necessary; otherwise return * the given handle as-is. * @param resource The resource to unwrap * @see InterceptedProxy#interceptedTarget() * @return unwraps the resource if possible */ static Object unwrapResourceIfNecessary(Object resource) { Objects.requireNonNull(resource, "Resource must not be null"); Object resourceRef = resource; // unwrap infrastructure proxy if (resourceRef instanceof InterceptedProxy) { resourceRef = ((InterceptedProxy) resourceRef).interceptedTarget(); } return resourceRef; } /** * Trigger {@code flush} callbacks on all currently registered synchronizations. * @throws RuntimeException if thrown by a {@code flush} callback * @see TransactionSynchronization#flush() */ public static void triggerFlush() { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { synchronization.flush(); } } /** * Trigger {@code beforeCommit} callbacks on all currently registered synchronizations. * @param readOnly whether the transaction is defined as read-only transaction * @throws RuntimeException if thrown by a {@code beforeCommit} callback * @see TransactionSynchronization#beforeCommit(boolean) */ public static void triggerBeforeCommit(boolean readOnly) { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { synchronization.beforeCommit(readOnly); } } /** * Trigger {@code beforeCompletion} callbacks on all currently registered synchronizations. * @see TransactionSynchronization#beforeCompletion() */ public static void triggerBeforeCompletion() { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { try { synchronization.beforeCompletion(); } catch (Throwable tsex) { LOG.error("TransactionSynchronization.beforeCompletion threw exception", tsex); } } } /** * Trigger {@code afterCommit} callbacks on all currently registered synchronizations. * @throws RuntimeException if thrown by a {@code afterCommit} callback * @see TransactionSynchronizationManager#getSynchronizations() * @see TransactionSynchronization#afterCommit() */ public static void triggerAfterCommit() { invokeAfterCommit(TransactionSynchronizationManager.getSynchronizations()); } /** * Actually invoke the {@code afterCommit} methods of the * given Spring TransactionSynchronization objects. * @param synchronizations a List of TransactionSynchronization objects * @see TransactionSynchronization#afterCommit() */ public static void invokeAfterCommit(@Nullable List<TransactionSynchronization> synchronizations) { if (synchronizations != null) { for (TransactionSynchronization synchronization : synchronizations) { synchronization.afterCommit(); } } } /** * Trigger {@code afterCompletion} callbacks on all currently registered synchronizations. * @param completionStatus the completion status according to the * constants in the TransactionSynchronization interface * @see TransactionSynchronizationManager#getSynchronizations() * @see TransactionSynchronization#afterCompletion(TransactionSynchronization.Status) * @see TransactionSynchronization.Status#COMMITTED * @see TransactionSynchronization.Status#ROLLED_BACK * @see TransactionSynchronization.Status#UNKNOWN */ public static void triggerAfterCompletion(@NonNull TransactionSynchronization.Status completionStatus) { List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations(); invokeAfterCompletion(synchronizations, completionStatus); } /** * Actually invoke the {@code afterCompletion} methods of the * given Spring TransactionSynchronization objects. * @param synchronizations a List of TransactionSynchronization objects * @param completionStatus the completion status according to the * constants in the TransactionSynchronization interface * @see TransactionSynchronization.Status#afterCompletion(TransactionSynchronization.Status) * @see TransactionSynchronization.Status#COMMITTED * @see TransactionSynchronization.Status#ROLLED_BACK * @see TransactionSynchronization.Status#UNKNOWN */ public static void invokeAfterCompletion(@Nullable List<TransactionSynchronization> synchronizations, @NonNull TransactionSynchronization.Status completionStatus) { if (synchronizations != null) { for (TransactionSynchronization synchronization : synchronizations) { try { synchronization.afterCompletion(completionStatus); } catch (Throwable tsex) { LOG.error("TransactionSynchronization.afterCompletion threw exception", tsex); } } } } }
/* * Copyright (c) 2004, The Joust Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of the Joust Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * File created by keith @ Jan 26, 2004 * */ package net.kano.joustsim.oscar.oscar.service.icbm.secureim; import net.kano.joustsim.Screenname; import net.kano.joustsim.oscar.oscar.service.icbm.MessageInfo; import net.kano.joustsim.trust.BuddyCertificateInfo; import net.kano.joscar.snaccmd.FullUserInfo; import net.kano.joscar.snaccmd.icbm.RecvImIcbm; import java.util.Date; public class EncryptedAimMessageInfo extends MessageInfo { public static EncryptedAimMessageInfo getInstance(Screenname to, RecvImIcbm icbm, BuddyCertificateInfo certInfo, Date date) { FullUserInfo senderInfo = icbm.getSenderInfo(); if (senderInfo == null) return null; Screenname from = new Screenname(senderInfo.getScreenname()); EncryptedAimMessage message = EncryptedAimMessage.getInstance(icbm); if (message == null) return null; return new EncryptedAimMessageInfo(from, to, message, certInfo, date); } private final BuddyCertificateInfo certificateInfo; private EncryptedAimMessageInfo(Screenname from, Screenname to, EncryptedAimMessage message, BuddyCertificateInfo certInfo, Date date) { super(from, to, message, date); this.certificateInfo = certInfo; } public BuddyCertificateInfo getMessageCertificates() { return certificateInfo; } }
package parrot; public interface Parrot { double baseSpeed = 12.0; double getSpeed(); }
/* * Copyright (c) 2019 Stefan Spiska (Vitasystems GmbH) and Hannover Medical School * This file is part of Project EHRbase * * 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.ehrbase.client.openehrclient; import org.ehrbase.client.exception.ClientException; import org.ehrbase.client.exception.WrongStatusCodeException; import org.ehrbase.response.openehr.TemplatesResponseData; import org.openehr.schemas.v1.OPERATIONALTEMPLATE; import java.util.Optional; public interface TemplateEndpoint { /** * Find a template by templateId * * @param templateId * @return {@link OPERATIONALTEMPLATE} * @throws ClientException * @throws WrongStatusCodeException */ Optional<OPERATIONALTEMPLATE> findTemplate(String templateId); /** * Retrieves a list of templates * * @return */ TemplatesResponseData findAllTemplates(); /** * Ensure that the Template with {@code templateId} exists in the remote system. * * @param templateId Id of the template to check * @throws ClientException * @throws WrongStatusCodeException */ void ensureExistence(String templateId); }
/* * Copyright (c) 2013, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.python.runtime.sequence.storage; import java.io.PrintStream; import java.util.Arrays; import org.python.core.Py; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.nodes.ExplodeLoop; import edu.uci.python.runtime.PythonOptions; import edu.uci.python.runtime.sequence.SequenceUtil; public final class IntSequenceStorage extends BasicSequenceStorage { private int[] values; public IntSequenceStorage() { values = new int[]{}; } public IntSequenceStorage(int[] elements) { this.values = elements; capacity = values.length; length = elements.length; } @Override protected void increaseCapacityExactWithCopy(int newCapacity) { values = Arrays.copyOf(values, newCapacity); capacity = values.length; } @Override protected void increaseCapacityExact(int newCapacity) { values = new int[newCapacity]; capacity = values.length; } @Override public SequenceStorage copy() { return new IntSequenceStorage(Arrays.copyOf(values, length)); } @Override public Object[] getInternalArray() { /** * Have to box and copy. */ Object[] boxed = new Object[length]; for (int i = 0; i < length; i++) { boxed[i] = values[i]; } return boxed; } public int[] getInternalIntArray() { return values; } @Override public Object[] getCopyOfInternalArray() { return getInternalArray(); } @Override public Object getItemNormalized(int idx) { return getIntItemNormalized(idx); } public int getIntItemNormalized(int idx) { try { return values[idx]; } catch (ArrayIndexOutOfBoundsException e) { CompilerDirectives.transferToInterpreterAndInvalidate(); throw Py.IndexError("list index out of range"); } } @Override public void setItemNormalized(int idx, Object value) throws SequenceStoreException { if (value instanceof Integer) { setIntItemNormalized(idx, (int) value); } else { throw SequenceStoreException.INSTANCE; } } public void setIntItemNormalized(int idx, int value) { try { values[idx] = value; } catch (ArrayIndexOutOfBoundsException e) { CompilerDirectives.transferToInterpreterAndInvalidate(); throw Py.IndexError("list assignment index out of range"); } } @Override public void insertItem(int idx, Object value) throws SequenceStoreException { if (value instanceof Integer) { insertIntItem(idx, (int) value); } else { throw SequenceStoreException.INSTANCE; } } public void insertIntItem(int idx, int value) { ensureCapacity(length + 1); // shifting tail to the right by one slot for (int i = values.length - 1; i > idx; i--) { values[i] = values[i - 1]; } values[idx] = value; length++; } @Override public SequenceStorage getSliceInBound(int start, int stop, int step, int sliceLength) { int[] newArray = new int[sliceLength]; if (step == 1) { System.arraycopy(values, start, newArray, 0, sliceLength); return new IntSequenceStorage(newArray); } for (int i = start, j = 0; j < sliceLength; i += step, j++) { newArray[j] = values[i]; } return new IntSequenceStorage(newArray); } @Override public void setSliceInBound(int start, int stop, int step, SequenceStorage sequence) throws SequenceStoreException { if (sequence instanceof IntSequenceStorage) { setIntSliceInBound(start, stop, step, (IntSequenceStorage) sequence); } else { throw new SequenceStoreException(); } } public void setIntSliceInBound(int start, int stop, int step, IntSequenceStorage sequence) { int otherLength = sequence.length(); // range is the whole sequence? if (start == 0 && stop == length) { values = Arrays.copyOf(sequence.values, otherLength); length = otherLength; minimizeCapacity(); return; } ensureCapacity(stop); for (int i = start, j = 0; i < stop; i += step, j++) { values[i] = sequence.values[j]; } length = length > stop ? length : stop; } @Override public void delSlice(int start, int stop) { if (stop == SequenceUtil.MISSING_INDEX) { length = start; } } @Override public void delItemInBound(int idx) { if (values.length - 1 == idx) { popInt(); } else { popInBound(idx); } } @Override public Object popInBound(int idx) { int pop = values[idx]; for (int i = idx; i < values.length - 1; i++) { values[i] = values[i + 1]; } length--; return pop; } public int popInt() { int pop = values[capacity - 1]; length--; return pop; } @Override public int index(Object value) { if (value instanceof Integer) { return indexOfInt((int) value); } else { return super.index(value); } } @ExplodeLoop public int indexOfInt(int value) { for (int i = 0; i < length; i++) { if (values[i] == value) { return i; } } return -1; } @Override public void append(Object value) throws SequenceStoreException { if (value instanceof Integer) { appendInt((int) value); } else { throw SequenceStoreException.INSTANCE; } } public void appendInt(int value) { ensureCapacity(length + 1); values[length] = value; length++; } @Override public void extend(SequenceStorage other) throws SequenceStoreException { if (other instanceof IntSequenceStorage) { extendWithIntStorage((IntSequenceStorage) other); } else { throw SequenceStoreException.INSTANCE; } } // @ExplodeLoop public void extendWithIntStorage(IntSequenceStorage other) { int extendedLength = length + other.length(); ensureCapacity(extendedLength); int[] otherValues = other.values; for (int i = length, j = 0; i < extendedLength; i++, j++) { values[i] = otherValues[j]; } length = extendedLength; } @ExplodeLoop @Override public void reverse() { int head = 0; int tail = length - 1; int middle = (length - 1) / 2; for (; head <= middle; head++, tail--) { int temp = values[head]; values[head] = values[tail]; values[tail] = temp; } } @ExplodeLoop @Override public void sort() { int[] copy = Arrays.copyOf(values, length); Arrays.sort(copy); values = copy; minimizeCapacity(); } @Override public SequenceStorage generalizeFor(Object value) { if (value instanceof Long) { if (PythonOptions.TraceSequenceStorageGeneralization) { PrintStream ps = System.out; ps.println("[ZipPy]" + this + " generalizing to LongSequenceStorage"); } return new LongSequenceStorage(getInternalIntArray()); } if (PythonOptions.TraceSequenceStorageGeneralization) { PrintStream ps = System.out; ps.println("[ZipPy]" + this + " generalizing to ObjectSequenceStorage"); } return new ObjectSequenceStorage(getInternalArray()); } @Override public Object getIndicativeValue() { return 0; } @ExplodeLoop @Override public boolean equals(SequenceStorage other) { if (other.length() != length() || !(other instanceof IntSequenceStorage)) { return false; } int[] otherArray = ((IntSequenceStorage) other).getInternalIntArray(); for (int i = 0; i < length(); i++) { if (values[i] != otherArray[i]) { return false; } } return true; } }
package com.sequenceiq.cloudbreak.converter; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import com.sequenceiq.cloudbreak.TestUtil; import com.sequenceiq.cloudbreak.api.model.CloudbreakDetailsJson; import com.sequenceiq.cloudbreak.api.model.ClusterResponse; import com.sequenceiq.cloudbreak.api.model.FailurePolicyJson; import com.sequenceiq.cloudbreak.api.model.ImageJson; import com.sequenceiq.cloudbreak.api.model.InstanceGroupJson; import com.sequenceiq.cloudbreak.api.model.OrchestratorResponse; import com.sequenceiq.cloudbreak.api.model.StackResponse; import com.sequenceiq.cloudbreak.cloud.model.CloudbreakDetails; import com.sequenceiq.cloudbreak.cloud.model.Image; import com.sequenceiq.cloudbreak.core.CloudbreakImageNotFoundException; import com.sequenceiq.cloudbreak.domain.Cluster; import com.sequenceiq.cloudbreak.domain.FailurePolicy; import com.sequenceiq.cloudbreak.domain.Network; import com.sequenceiq.cloudbreak.domain.Orchestrator; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.service.ComponentConfigProvider; import com.sequenceiq.cloudbreak.service.image.ImageService; public class StackToJsonConverterTest extends AbstractEntityConverterTest<Stack> { @InjectMocks private StackToJsonConverter underTest; @Mock private ConversionService conversionService; @Mock private ImageService imageService; @Mock private ComponentConfigProvider componentConfigProvider; @Before public void setUp() throws CloudbreakImageNotFoundException { underTest = new StackToJsonConverter(); MockitoAnnotations.initMocks(this); when(imageService.getImage(anyLong())).thenReturn(new Image("testimage", new HashMap<>())); when(componentConfigProvider.getCloudbreakDetails(anyLong())).thenReturn(new CloudbreakDetails("version")); } @Test public void testConvert() { // GIVEN given(conversionService.convert(any(Object.class), any(Class.class))) .willReturn(new ImageJson()) .willReturn(new ClusterResponse()) .willReturn(new FailurePolicyJson()) .willReturn(new OrchestratorResponse()) .willReturn(new CloudbreakDetailsJson()); given(conversionService.convert(any(Object.class), any(TypeDescriptor.class), any(TypeDescriptor.class))) .willReturn(new HashSet<InstanceGroupJson>()); // WHEN StackResponse result = underTest.convert(getSource()); // THEN assertAllFieldsNotNull(result, Collections.singletonList("platformVariant")); } @Test public void testConvertWithoutCredential() { // GIVEN given(conversionService.convert(any(Object.class), any(Class.class))) .willReturn(new ImageJson()) .willReturn(new ClusterResponse()) .willReturn(new FailurePolicyJson()) .willReturn(new OrchestratorResponse()) .willReturn(new CloudbreakDetailsJson()); given(conversionService.convert(any(Object.class), any(TypeDescriptor.class), any(TypeDescriptor.class))) .willReturn(new HashSet<InstanceGroupJson>()); // WHEN StackResponse result = underTest.convert(getSource()); // THEN assertAllFieldsNotNull(result, Arrays.asList("credentialId", "cloudPlatform", "platformVariant")); } @Test public void testConvertWithoutCluster() { // GIVEN getSource().setCluster(null); given(conversionService.convert(any(Object.class), any(Class.class))) .willReturn(new ImageJson()) .willReturn(new FailurePolicyJson()) .willReturn(new OrchestratorResponse()) .willReturn(new CloudbreakDetailsJson()); given(conversionService.convert(any(Object.class), any(TypeDescriptor.class), any(TypeDescriptor.class))) .willReturn(new HashSet<InstanceGroupJson>()); getSource().setCluster(null); // WHEN StackResponse result = underTest.convert(getSource()); // THEN assertAllFieldsNotNull(result, Arrays.asList("cluster", "platformVariant")); } @Test public void testConvertWithoutFailurePolicy() { // GIVEN getSource().setFailurePolicy(null); given(conversionService.convert(any(Object.class), any(Class.class))) .willReturn(new ImageJson()) .willReturn(new ClusterResponse()) .willReturn(new OrchestratorResponse()) .willReturn(new CloudbreakDetailsJson()); given(conversionService.convert(any(Object.class), any(TypeDescriptor.class), any(TypeDescriptor.class))) .willReturn(new HashSet<InstanceGroupJson>()); // WHEN StackResponse result = underTest.convert(getSource()); // THEN assertAllFieldsNotNull(result, Arrays.asList("failurePolicy", "platformVariant")); } @Test public void testConvertWithoutNetwork() { // GIVEN getSource().setNetwork(null); given(conversionService.convert(any(Object.class), any(Class.class))) .willReturn(new ImageJson()) .willReturn(new ClusterResponse()) .willReturn(new FailurePolicyJson()) .willReturn(new OrchestratorResponse()) .willReturn(new CloudbreakDetailsJson()); given(conversionService.convert(any(Object.class), any(TypeDescriptor.class), any(TypeDescriptor.class))) .willReturn(new HashSet<InstanceGroupJson>()); // WHEN StackResponse result = underTest.convert(getSource()); // THEN assertAllFieldsNotNull(result, Arrays.asList("networkId", "platformVariant")); } @Override public Stack createSource() { Stack stack = TestUtil.stack(); Cluster cluster = TestUtil.cluster(TestUtil.blueprint(), stack, 1L); stack.setCluster(cluster); stack.setAvailabilityZone("avZone"); Network network = new Network(); network.setId(1L); stack.setNetwork(network); stack.setFailurePolicy(new FailurePolicy()); Orchestrator orchestrator = new Orchestrator(); orchestrator.setId(1L); orchestrator.setApiEndpoint("endpoint"); orchestrator.setType("type"); stack.setOrchestrator(orchestrator); stack.setParameters(new HashMap<>()); stack.setCloudPlatform("OPENSTACK"); stack.setGatewayPort(9443); return stack; } }
package org.apache.cayenne.testdo.testmap.auto; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigDecimal; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.exp.property.EntityProperty; import org.apache.cayenne.exp.property.NumericProperty; import org.apache.cayenne.exp.property.PropertyFactory; import org.apache.cayenne.exp.property.StringProperty; import org.apache.cayenne.testdo.testmap.ArtDataObject; import org.apache.cayenne.testdo.testmap.Artist; import org.apache.cayenne.testdo.testmap.Gallery; import org.apache.cayenne.testdo.testmap.PaintingInfo; /** * Class _Painting was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _Painting extends ArtDataObject { private static final long serialVersionUID = 1L; public static final NumericProperty<Integer> PAINTING_ID_PK_PROPERTY = PropertyFactory.createNumeric(ExpressionFactory.dbPathExp("PAINTING_ID"), Integer.class); public static final String PAINTING_ID_PK_COLUMN = "PAINTING_ID"; public static final NumericProperty<BigDecimal> ESTIMATED_PRICE = PropertyFactory.createNumeric("estimatedPrice", BigDecimal.class); public static final StringProperty<String> PAINTING_DESCRIPTION = PropertyFactory.createString("paintingDescription", String.class); public static final StringProperty<String> PAINTING_TITLE = PropertyFactory.createString("paintingTitle", String.class); public static final EntityProperty<Artist> TO_ARTIST = PropertyFactory.createEntity("toArtist", Artist.class); public static final EntityProperty<Gallery> TO_GALLERY = PropertyFactory.createEntity("toGallery", Gallery.class); public static final EntityProperty<PaintingInfo> TO_PAINTING_INFO = PropertyFactory.createEntity("toPaintingInfo", PaintingInfo.class); protected BigDecimal estimatedPrice; protected String paintingDescription; protected String paintingTitle; protected Object toArtist; protected Object toGallery; protected Object toPaintingInfo; public void setEstimatedPrice(BigDecimal estimatedPrice) { beforePropertyWrite("estimatedPrice", this.estimatedPrice, estimatedPrice); this.estimatedPrice = estimatedPrice; } public BigDecimal getEstimatedPrice() { beforePropertyRead("estimatedPrice"); return this.estimatedPrice; } public void setPaintingDescription(String paintingDescription) { beforePropertyWrite("paintingDescription", this.paintingDescription, paintingDescription); this.paintingDescription = paintingDescription; } public String getPaintingDescription() { beforePropertyRead("paintingDescription"); return this.paintingDescription; } public void setPaintingTitle(String paintingTitle) { beforePropertyWrite("paintingTitle", this.paintingTitle, paintingTitle); this.paintingTitle = paintingTitle; } public String getPaintingTitle() { beforePropertyRead("paintingTitle"); return this.paintingTitle; } public void setToArtist(Artist toArtist) { setToOneTarget("toArtist", toArtist, true); } public Artist getToArtist() { return (Artist)readProperty("toArtist"); } public void setToGallery(Gallery toGallery) { setToOneTarget("toGallery", toGallery, true); } public Gallery getToGallery() { return (Gallery)readProperty("toGallery"); } public void setToPaintingInfo(PaintingInfo toPaintingInfo) { setToOneTarget("toPaintingInfo", toPaintingInfo, true); } public PaintingInfo getToPaintingInfo() { return (PaintingInfo)readProperty("toPaintingInfo"); } @Override public Object readPropertyDirectly(String propName) { if(propName == null) { throw new IllegalArgumentException(); } switch(propName) { case "estimatedPrice": return this.estimatedPrice; case "paintingDescription": return this.paintingDescription; case "paintingTitle": return this.paintingTitle; case "toArtist": return this.toArtist; case "toGallery": return this.toGallery; case "toPaintingInfo": return this.toPaintingInfo; default: return super.readPropertyDirectly(propName); } } @Override public void writePropertyDirectly(String propName, Object val) { if(propName == null) { throw new IllegalArgumentException(); } switch (propName) { case "estimatedPrice": this.estimatedPrice = (BigDecimal)val; break; case "paintingDescription": this.paintingDescription = (String)val; break; case "paintingTitle": this.paintingTitle = (String)val; break; case "toArtist": this.toArtist = val; break; case "toGallery": this.toGallery = val; break; case "toPaintingInfo": this.toPaintingInfo = val; break; default: super.writePropertyDirectly(propName, val); } } private void writeObject(ObjectOutputStream out) throws IOException { writeSerialized(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readSerialized(in); } @Override protected void writeState(ObjectOutputStream out) throws IOException { super.writeState(out); out.writeObject(this.estimatedPrice); out.writeObject(this.paintingDescription); out.writeObject(this.paintingTitle); out.writeObject(this.toArtist); out.writeObject(this.toGallery); out.writeObject(this.toPaintingInfo); } @Override protected void readState(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readState(in); this.estimatedPrice = (BigDecimal)in.readObject(); this.paintingDescription = (String)in.readObject(); this.paintingTitle = (String)in.readObject(); this.toArtist = in.readObject(); this.toGallery = in.readObject(); this.toPaintingInfo = in.readObject(); } }
package com.natanloterio.moviedb.data.video; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by natanloterio on 25/11/16. */ public class Video implements Serializable { @SerializedName("id") private String id; @SerializedName("iso_639_1") private String iso6391; @SerializedName("iso_3166_1") private String iso31661; @SerializedName("key") private String key; @SerializedName("name") private String name; @SerializedName("site") private String site; @SerializedName("size") private Integer size; @SerializedName("type") private String type; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIso6391() { return iso6391; } public void setIso6391(String iso6391) { this.iso6391 = iso6391; } public String getIso31661() { return iso31661; } public void setIso31661(String iso31661) { this.iso31661 = iso31661; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package com.josedab.interviewbit.linkedLists; import com.josedab.interviewbit.model.ListNode; import com.josedab.interviewbit.utils.ListNodeUtils; /** * Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. */ public class SwapListNodesInPairs { public ListNode swapPairs(ListNode ln) { ListNode result = ln; ListNode pointer = ln; ListNode previous = null; while (pointer != null && pointer.next != null) { ListNode tail = pointer.next.next; ListNode swapAux = pointer.next; pointer.next = tail; swapAux.next = pointer; // First element of the array if (previous == null) { result = swapAux; } else { // Processing elements within the array (except first couple) previous.next = swapAux; } previous = swapAux.next; pointer = tail; } return result; } public static void main(String[] args) { SwapListNodesInPairs solution = new SwapListNodesInPairs(); ListNodeUtils.printListNodes( solution.swapPairs( ListNodeUtils.createListNodeListFromIntegers(1, 2, 3, 4))); } }
package com.Geddy; public class Main { public static void main(String[] args) { Program pr = new Program(); pr.runProgram(); } }
package com.mapbox.api.tilequery; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.mapbox.core.MapboxService; import com.mapbox.core.constants.Constants; import com.mapbox.core.exceptions.ServicesException; import com.mapbox.core.utils.MapboxUtils; import com.mapbox.core.utils.TextUtils; import com.mapbox.geojson.FeatureCollection; import com.mapbox.geojson.GeometryAdapterFactory; import com.mapbox.geojson.Point; import com.mapbox.geojson.gson.GeoJsonAdapterFactory; import java.io.IOException; import java.util.List; import java.util.Locale; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * The Mapbox Tilequery API allows you to retrieve data about specific features from a * vector tileset, based on a given latitude and longitude. * * @see <a href="https://www.mapbox.com/api-documentation/maps/#tilequery">Tilequery API * documentation</a> * * @since 3.5.0 */ @AutoValue public abstract class MapboxTilequery extends MapboxService<FeatureCollection, TilequeryService> { private Call<List<FeatureCollection>> batchCall; protected MapboxTilequery() { super(TilequeryService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(GeoJsonAdapterFactory.create()) .registerTypeAdapterFactory(GeometryAdapterFactory.create()); } @Override protected Call<FeatureCollection> initializeCall() { return getService().getCall( tilesetIds(), query(), accessToken(), radius(), limit(), dedupe(), geometry(), layers()); } private Call<List<FeatureCollection>> getBatchCall() { // No need to recreate it if (batchCall != null) { return batchCall; } batchCall = getService().getBatchCall( tilesetIds(), query(), accessToken(), radius(), limit(), dedupe(), geometry(), layers()); return batchCall; } /** * Wrapper method for Retrofit's {@link Call#execute()} call returning a batch response * specific to the Tilequery API. * * @return the Tilequery batch response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred. * @since 3.5.0 */ public Response<List<FeatureCollection>> executeBatchCall() throws IOException { return getBatchCall().execute(); } /** * Wrapper method for Retrofit's {@link Call#enqueue(Callback)} call returning a batch response * specific to the Tilequery batch API. Use this method to make a tilequery request on the Main * Thread. * * @param callback a {@link Callback} which is used once the {@link FeatureCollection} is created. * @since 3.5.0 */ public void enqueueBatchCall(Callback<List<FeatureCollection>> callback) { getBatchCall().enqueue(callback); } /** * Wrapper method for Retrofit's {@link Call#cancel()} call, important to manually cancel call if * the user dismisses the calling activity or no longer needs the returned results. * * @since 3.5.0 */ public void cancelBatchCall() { getBatchCall().cancel(); } /** * Wrapper method for Retrofit's {@link Call#clone()} call, useful for getting call information. * * @return cloned call * @since 3.5.0 */ public Call<List<FeatureCollection>> cloneBatchCall() { return getBatchCall().clone(); } /** * Build a new {@link MapboxTilequery} object with the initial value set for * {@link #baseUrl()}. * * @return a {@link MapboxTilequery.Builder} object for creating this object * @since 3.5.0 */ public static Builder builder() { return new AutoValue_MapboxTilequery.Builder() .baseUrl(Constants.BASE_API_URL); } @NonNull @Override protected abstract String baseUrl(); @NonNull abstract String accessToken(); @NonNull abstract String tilesetIds(); @NonNull abstract String query(); @Nullable abstract Integer radius(); @Nullable abstract Integer limit(); @Nullable abstract Boolean dedupe(); @Nullable abstract @TilequeryCriteria.TilequeryGeometry String geometry(); @Nullable abstract String layers(); /** * This builder is used to create a new request to the Mapbox Tilequery API. At a bare minimum, * your request must include an access token, a tileset ID, and a query of some kind. All other * fields can be left alone in order to use the default behaviour of the API. * <p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 3.5.0 */ @AutoValue.Builder public abstract static class Builder { /** * Optionally change the APIs base URL to something other then the default Mapbox one. * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Mapbox access token * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * The ID of the tileset being queried. If you need to composite multiple layers, the Tilequery * API endpoint can also support a comma-separated list of tileset IDs. * * @param tilesetIds tile set ID(s) * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder tilesetIds(String tilesetIds); /** * The longitude and latitude to be queried. * * @param point query point * @return this builder for chaining options together * @since 3.5.0 */ public Builder query(@NonNull Point point) { query(String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(point.longitude()), TextUtils.formatCoordinate(point.latitude()))); String str = String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(point.longitude()), TextUtils.formatCoordinate(point.latitude())); return this; } /** * The longitude and latitude to be queried. * * @param query query point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder query(@NonNull String query); /** * The approximate distance in meters to query for features. Defaults to 0. Has no upper * bound. Required for queries against point and line data. Due to the nature of tile * buffering, a query with a large radius made against equally large point or line data may * not include all possible features in the results. Queries will use tiles from the * maximum zoom of the tileset, and will only include the intersecting tile plus 8 * surrounding tiles when searching for nearby features. * * @param radius distance in meters to query for features * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder radius(@Nullable Integer radius); /** * The number of features between 1 - 50 to return. Defaults to 5. * * @param limit the number of features * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder limit(@Nullable Integer limit); /** * Determines whether results will be deduplicated or not. Defaults to true. * * @param dedupe whether results will be deduplicated * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder dedupe(@Nullable Boolean dedupe); /** * Queries for a specific geometry type. Options are polygon, linestring, or point. * * @param geometry polygon, linestring, or point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder geometry( @Nullable @TilequeryCriteria.TilequeryGeometry String geometry); /** * A comma-separated list of layers to query, rather than querying all layers. If a * specified layer does not exist, it is skipped. If no layers exist, returns an * empty FeatureCollection. * * @param layers list of layers to query * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder layers(@Nullable String layers); /** * * @return this builder for chaining options together * @since 3.5.0 */ abstract MapboxTilequery autoBuild(); /** * Build a new {@link MapboxTilequery} object. * * @return this builder for chaining options together * @since 3.5.0 */ public MapboxTilequery build() { MapboxTilequery tilequery = autoBuild(); if (!MapboxUtils.isAccessTokenValid(tilequery.accessToken())) { throw new ServicesException("Using Mapbox Services requires setting a valid access token."); } if (tilequery.query().isEmpty()) { throw new ServicesException("A query with latitude and longitude values is required."); } return tilequery; } } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE470_Unsafe_Reflection__database_03.java Label Definition File: CWE470_Unsafe_Reflection.label.xml Template File: sources-sink-03.tmpl.java */ /* * @description * CWE: 470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') * BadSource: database Read data from a database * GoodSource: Set data to a hardcoded class name * BadSink: Instantiate class named in data * Flow Variant: 03 Control flow: if(5==5) and if(5!=5) * * */ package testcases.CWE470_Unsafe_Reflection; import testcasesupport.*; import javax.servlet.http.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; public class CWE470_Unsafe_Reflection__database_03 extends AbstractTestCase { /* uses badsource and badsink */ public void bad() throws Throwable { String data; if (5 == 5) { data = ""; /* Initialize data */ /* Read data from a database */ { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /* setup the connection */ connection = IO.getDBConnection(); /* prepare and execute a (hardcoded) query */ preparedStatement = connection.prepareStatement("select name from users where id=0"); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: Read data from a database query resultset */ data = resultSet.getString(1); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error with SQL statement", exceptSql); } finally { /* Close database objects */ try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql); } try { if (connection != null) { connection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql); } } } } 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; } /* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */ Class<?> tempClass = Class.forName(data); Object tempClassObject = tempClass.newInstance(); IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */ } /* goodG2B1() - use goodsource and badsink by changing 5==5 to 5!=5 */ private void goodG2B1() throws Throwable { String data; if (5 != 5) { /* 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 class name */ data = "Testing.test"; } /* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */ Class<?> tempClass = Class.forName(data); Object tempClassObject = tempClass.newInstance(); IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */ } /* goodG2B2() - use goodsource and badsink by reversing statements in if */ private void goodG2B2() throws Throwable { String data; if (5 == 5) { /* FIX: Use a hardcoded class name */ data = "Testing.test"; } 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; } /* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */ Class<?> tempClass = Class.forName(data); Object tempClassObject = tempClass.newInstance(); IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */ } public void good() throws Throwable { goodG2B1(); goodG2B2(); } /* 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); } }
package org.levainservice.service; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class AbstractResource { private Gson gson; public AbstractResource() { gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss") .create(); } public Gson getGson() { return gson; } public void setGson(Gson gson) { this.gson = gson; } }
package com.atguigu.gulimall.product.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.product.entity.AttrGroupEntity; import com.atguigu.gulimall.product.service.AttrGroupService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * ���Է��� * * @author katrinani * @email lichenkatrinani@gmail.com * @date 2021-02-12 19:19:03 */ @RestController @RequestMapping("product/attrgroup") public class AttrGroupController { @Autowired private AttrGroupService attrGroupService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = attrGroupService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{attrGroupId}") public R info(@PathVariable("attrGroupId") Long attrGroupId){ AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId); return R.ok().put("attrGroup", attrGroup); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody AttrGroupEntity attrGroup){ attrGroupService.save(attrGroup); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody AttrGroupEntity attrGroup){ attrGroupService.updateById(attrGroup); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] attrGroupIds){ attrGroupService.removeByIds(Arrays.asList(attrGroupIds)); return R.ok(); } }
package com.appsmata.qtoa.adapters; import android.annotation.SuppressLint; import android.content.Context; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Build; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.TextView; import com.balysv.materialripple.MaterialRippleLayout; import com.appsmata.qtoa.models.*; import java.util.ArrayList; import java.util.List; import com.appsmata.qtoa.retrofitconfig.BaseUrlConfig; import com.appsmata.qtoa.R; public class ListsQuestionsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<PostModel> thisPost; public OnItemClickListener onItemClickListener; public OnLoadMoreListener onLoadMoreListener; public boolean loading; private int VIEW_PROGRES = 0; private int VIEW_ITEM = 1; private final int tagcolor = 0; private final Context context; public interface OnItemClickListener{ void onItemClick(View view, PostModel thisPost); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; } public ListsQuestionsAdapter(List<PostModel> thisPost, Context context){ this.thisPost = thisPost; this.context = context; } public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener){ this.onLoadMoreListener = onLoadMoreListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView.ViewHolder viewHolder; if (viewType == VIEW_ITEM){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listing_posts, parent, false); viewHolder = new MyViewHolder(view); }else{ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.loading_data, parent, false); viewHolder = new MyViewHolder(view); } return viewHolder; } @SuppressWarnings("deprecation") public static Spanned fromHtml(String source) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY); } else { return Html.fromHtml(source); } } @SuppressLint("NewApi") @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { final PostModel Question = thisPost.get(position); MyViewHolder view = (MyViewHolder) holder; String details = Question.what + " " + Question.when + " " + Question.where + " " + Question.who; view.post_title.setText(Question.title); view.post_netvotes.setText(Question.netvotes); view.post_acount.setText(Question.acount); view.post_details.setText(fromHtml(details)); //view.post_details.setText(Html.fromHtml(details, Html.FROM_HTML_MODE_COMPACT)); Build.VERSION_CODES.N //view.post_details.setText(Html.fromHtml(details, Html.FROM_HTML_MODE_LEGACY)); // if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { view.post_details.setText(Html.fromHtml(details, Html.FROM_HTML_MODE_LEGACY)); } // else { view.post_details.setText(Html.fromHtml(details, Html.FROM_HTML_MODE_COMPACT)); } if (!Question.tags.isEmpty()) { String[] MyTags = TextUtils.split(Question.tags, ","); for (int i = 0; i < MyTags.length; i++) { TextView tagView = new TextView(context); tagView.setText(MyTags[i]); tagView.setTextColor(context.getResources().getColor(R.color.white_color)); tagView.setBackground(context.getResources().getDrawable(R.drawable.custom_tag_view)); tagView.setPadding(20, 5, 20, 5); tagView.setTextSize(15); view.post_tags.addView(tagView); } } view.layout_parent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onItemClickListener != null){ onItemClickListener.onItemClick(view, Question); } } }); Log.d("MyAdapter", "position: " + position); } public class MyViewHolder extends RecyclerView.ViewHolder { public MaterialRippleLayout layout_parent; public TextView post_title, post_netvotes, post_acount, post_details; public GridLayout post_tags; public MyViewHolder(View itemView) { super(itemView); layout_parent = itemView.findViewById(R.id.material_ripple); post_title = itemView.findViewById(R.id.post_title); post_netvotes = itemView.findViewById(R.id.post_netvotes); post_acount = itemView.findViewById(R.id.post_acount); post_details = itemView.findViewById(R.id.post_details); post_tags = itemView.findViewById(R.id.post_tags); } } @Override public int getItemCount() { return thisPost.size(); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return this.thisPost.get(position) != null ? VIEW_ITEM : VIEW_PROGRES; } public void resetData(){ this.thisPost = new ArrayList<PostModel>(); notifyDataSetChanged(); } public void insertData(List<PostModel> thisPost){ setLoaded(); int itemStart = getItemCount(); int itemCount = thisPost.size(); this.thisPost.addAll(thisPost); notifyItemRangeInserted(itemStart, itemCount); } public void setLoaded(){ loading = false; for (int pl = 0; pl<getItemCount(); pl++){ if (thisPost.get(pl) == null){ thisPost.remove(pl); notifyItemRemoved(pl); } } } public void setLoading(){ if (getItemCount() != 0){ this.thisPost.add(null); notifyItemInserted(getItemCount() - 1); loading = true; } } private void lastPostsView(RecyclerView recyclerView){ if (recyclerView.getLayoutManager() instanceof LinearLayoutManager){ final LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int lastPosts = layoutManager.findLastVisibleItemPosition(); if (!loading && lastPosts == getItemCount() - 1 && onLoadMoreListener != null){ if (onLoadMoreListener != null){ int get = getItemCount() / BaseUrlConfig.RequestLoadMore; onLoadMoreListener.onLoadMore(get); } loading = true; } } }); } } public interface OnLoadMoreListener{ void onLoadMore(int page); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * */ package com.microsoft.azure.management.network.v2020_07_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.network.v2020_07_01.LoadBalancerNetworkInterfaces; import rx.Observable; import rx.functions.Func1; import com.microsoft.azure.Page; import com.microsoft.azure.management.network.v2020_07_01.LoadBalancerNetworkInterface; class LoadBalancerNetworkInterfacesImpl extends WrapperImpl<LoadBalancerNetworkInterfacesInner> implements LoadBalancerNetworkInterfaces { private final NetworkManager manager; LoadBalancerNetworkInterfacesImpl(NetworkManager manager) { super(manager.inner().loadBalancerNetworkInterfaces()); this.manager = manager; } public NetworkManager manager() { return this.manager; } private LoadBalancerNetworkInterfaceImpl wrapModel(NetworkInterfaceInner inner) { return new LoadBalancerNetworkInterfaceImpl(inner, manager()); } @Override public Observable<LoadBalancerNetworkInterface> listAsync(final String resourceGroupName, final String loadBalancerName) { LoadBalancerNetworkInterfacesInner client = this.inner(); return client.listAsync(resourceGroupName, loadBalancerName) .flatMapIterable(new Func1<Page<NetworkInterfaceInner>, Iterable<NetworkInterfaceInner>>() { @Override public Iterable<NetworkInterfaceInner> call(Page<NetworkInterfaceInner> page) { return page.items(); } }) .map(new Func1<NetworkInterfaceInner, LoadBalancerNetworkInterface>() { @Override public LoadBalancerNetworkInterface call(NetworkInterfaceInner inner) { return wrapModel(inner); } }); } }
package org.ititandev.controller; import java.util.List; import org.ititandev.Application; import org.ititandev.dao.ChatDAO; import org.ititandev.model.Message; import org.ititandev.model.MessageType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.stereotype.Component; import org.springframework.web.socket.messaging.SessionConnectedEvent; import org.springframework.web.socket.messaging.SessionDisconnectEvent; @Component public class WebSocketEventListener { private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class); @Autowired private SimpMessageSendingOperations messagingTemplate; static ChatDAO chatDAO = Application.context.getBean("ChatDAO", ChatDAO.class); @EventListener public void handleWebSocketConnectListener(SessionConnectedEvent event) { logger.info("[WS] Received a new web socket connection"); } @EventListener public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) { StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage()); String username = (String) headerAccessor.getSessionAttributes().get("username"); if (username != null) { logger.info("[WS] User Disconnected : " + username); Message message = new Message(); message.setType(MessageType.LEAVE); message.setUsername(username); List<String> revUser = chatDAO.getRevUserJoin(username, 0); revUser.forEach(u -> messagingTemplate.convertAndSend("/topic/" + u, message)); } } }
package ru.job4j.jdbc; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.IOException; /** * @author Nikolay Meleshkin (sol.of.f@mail.ru) * @version 0.1 */ public class ParserXML { private int totalCount; ParserXML(File dest) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); Handler handler = new Handler(); parser.parse(dest, handler); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } } public int getTotalCount() { return this.totalCount; } class Handler extends DefaultHandler { @Override public void startDocument() throws SAXException { super.startDocument(); System.out.println("Start parse XML..."); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if (qName.equals("entry")) { totalCount += Integer.valueOf(attributes.getValue("field")); } } @Override public void endDocument() throws SAXException { super.endDocument(); System.out.println("End parse XML."); } } }
package org.hl7.fhir.r4.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Thu, Sep 13, 2018 09:04-0400 for FHIR v3.5.0 import org.hl7.fhir.exceptions.FHIRException; public enum BindingStrength { /** * To be conformant, the concept in this element SHALL be from the specified value set. */ REQUIRED, /** * To be conformant, the concept in this element SHALL be from the specified value set if any of the codes within the value set can apply to the concept being communicated. If the value set does not cover the concept (based on human review), alternate codings (or, data type allowing, text) may be included instead. */ EXTENSIBLE, /** * Instances are encouraged to draw from the specified codes for interoperability purposes but are not required to do so to be considered conformant. */ PREFERRED, /** * Instances are not expected or even encouraged to draw from the specified value set. The value set merely provides examples of the types of concepts intended to be included. */ EXAMPLE, /** * added to help the parsers */ NULL; public static BindingStrength fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("required".equals(codeString)) return REQUIRED; if ("extensible".equals(codeString)) return EXTENSIBLE; if ("preferred".equals(codeString)) return PREFERRED; if ("example".equals(codeString)) return EXAMPLE; throw new FHIRException("Unknown BindingStrength code '"+codeString+"'"); } public String toCode() { switch (this) { case REQUIRED: return "required"; case EXTENSIBLE: return "extensible"; case PREFERRED: return "preferred"; case EXAMPLE: return "example"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/binding-strength"; } public String getDefinition() { switch (this) { case REQUIRED: return "To be conformant, the concept in this element SHALL be from the specified value set."; case EXTENSIBLE: return "To be conformant, the concept in this element SHALL be from the specified value set if any of the codes within the value set can apply to the concept being communicated. If the value set does not cover the concept (based on human review), alternate codings (or, data type allowing, text) may be included instead."; case PREFERRED: return "Instances are encouraged to draw from the specified codes for interoperability purposes but are not required to do so to be considered conformant."; case EXAMPLE: return "Instances are not expected or even encouraged to draw from the specified value set. The value set merely provides examples of the types of concepts intended to be included."; default: return "?"; } } public String getDisplay() { switch (this) { case REQUIRED: return "Required"; case EXTENSIBLE: return "Extensible"; case PREFERRED: return "Preferred"; case EXAMPLE: return "Example"; default: return "?"; } } }
package com.pertamina.tbbm.rewulu.ecodriving.listener; public interface OnPickedDate { public void pickedDate(int year, int month, int day); }
package com.solarexsoft.solarexokhttp; import android.text.TextUtils; import java.net.MalformedURLException; import java.net.URL; /** * <pre> * Author: houruhou * CreatAt: 11:28/2020-02-28 * Desc: * </pre> */ public class HttpUrl { String protocol; String host; String file; int port; public HttpUrl(String urlStr) throws MalformedURLException { URL url = new URL(urlStr); host = url.getHost(); file = url.getFile(); file = TextUtils.isEmpty(file) ? "/" : file; protocol = url.getProtocol(); port = url.getPort(); port = port == -1 ? url.getDefaultPort() : port; } public String getProtocol() { return protocol; } public String getHost() { return host; } public String getFile() { return file; } public int getPort() { return port; } }
package com.booknara.problem.twopointers; /** * 283. Move Zeroes (Easy) * https://leetcode.com/problems/move-zeroes/ */ public class MoveZeroes { // T:O(n), S:O(1) public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) return; int l = 0, r = 0; while (r < nums.length) { if (nums[r] != 0) { swap(nums, l, r); l++; } r++; } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
/* * 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.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; /** * ReferenceConfig * * @export */ public abstract class ReferenceConfigBase<T> extends AbstractReferenceConfig { private static final long serialVersionUID = -5864351140409987595L; /** * The interface name of the reference service */ protected String interfaceName; /** * The interface class of the reference service */ protected Class<?> interfaceClass; /** * client type */ protected String client; /** * The url for peer-to-peer invocation * * 直连服务提供者地址 */ protected String url; /** * The consumer config (default) */ protected ConsumerConfig consumer; /** * Only the service provider of the specified protocol is invoked, and other protocols are ignored. */ protected String protocol; protected ServiceMetadata serviceMetadata; public ReferenceConfigBase() { serviceMetadata = new ServiceMetadata(); serviceMetadata.addAttribute("ORIGIN_CONFIG", this); } public ReferenceConfigBase(Reference reference) { serviceMetadata = new ServiceMetadata(); serviceMetadata.addAttribute("ORIGIN_CONFIG", this); appendAnnotation(Reference.class, reference); setMethods(MethodConfig.constructMethodConfig(reference.methods())); } public boolean shouldCheck() { Boolean shouldCheck = isCheck(); if (shouldCheck == null && getConsumer() != null) { shouldCheck = getConsumer().isCheck(); } if (shouldCheck == null) { // default true shouldCheck = true; } return shouldCheck; } public boolean shouldInit() { Boolean shouldInit = isInit(); if (shouldInit == null && getConsumer() != null) { shouldInit = getConsumer().isInit(); } if (shouldInit == null) { // default is true, spring will still init lazily by setting init's default value to false, // the def default setting happens in {@link ReferenceBean#afterPropertiesSet}. return true; } return shouldInit; } //设置 ConsumerConfig public void checkDefault() throws IllegalStateException { if (consumer == null) { consumer = ApplicationModel.getConfigManager() .getDefaultConsumer() .orElse(new ConsumerConfig()); } } public Class<?> getActualInterface() { Class actualInterface = interfaceClass; if (interfaceClass == GenericService.class) { try { actualInterface = Class.forName(interfaceName); } catch (ClassNotFoundException e) { // ignore } } return actualInterface; } public Class<?> getInterfaceClass() { if (interfaceClass != null) { return interfaceClass; } if (ProtocolUtils.isGeneric(getGeneric()) || (getConsumer() != null && ProtocolUtils.isGeneric(getConsumer().getGeneric()))) { return GenericService.class; } try { if (interfaceName != null && interfaceName.length() > 0) { interfaceClass = Class.forName(interfaceName, true, ClassUtils.getClassLoader()); } } catch (ClassNotFoundException t) { throw new IllegalStateException(t.getMessage(), t); } return interfaceClass; } /** * @param interfaceClass * @see #setInterface(Class) * @deprecated */ @Deprecated public void setInterfaceClass(Class<?> interfaceClass) { setInterface(interfaceClass); } public String getInterface() { return interfaceName; } public void setInterface(String interfaceName) { this.interfaceName = interfaceName; // FIXME, add id strategy in ConfigManager // if (StringUtils.isEmpty(id)) { // id = interfaceName; // } } public void setInterface(Class<?> interfaceClass) { if (interfaceClass != null && !interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } this.interfaceClass = interfaceClass; setInterface(interfaceClass == null ? null : interfaceClass.getName()); } public String getClient() { return client; } public void setClient(String client) { this.client = client; } @Parameter(excluded = true) public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public ConsumerConfig getConsumer() { return consumer; } public void setConsumer(ConsumerConfig consumer) { this.consumer = consumer; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public ServiceMetadata getServiceMetadata() { return serviceMetadata; } @Override @Parameter(excluded = true) public String getPrefix() { return DUBBO + ".reference." + interfaceName; } //直连提供者 public void resolveFile() { // 直连提供者,参见文档《直连提供者》http://dubbo.apache.org/zh-cn/docs/user/demos/explicit-target.html // 【直连提供者】第一优先级,通过 -D 参数指定 ,例如 java -Dcom.alibaba.xxx.XxxService=dubbo://localhost:20890 String resolve = System.getProperty(interfaceName); String resolveFile = null; // 【直连提供者】第二优先级,通过文件映射,例如 com.alibaba.xxx.XxxService=dubbo://localhost:20890 if (StringUtils.isEmpty(resolve)) { //读取 dubbo.resolve.file 属性 获取文件名 resolveFile = System.getProperty("dubbo.resolve.file"); if (StringUtils.isEmpty(resolveFile)) { // `${user.home}/dubbo-resolve.properties` 文件 ,无需配置 File userResolveFile = new File(new File(System.getProperty("user.home")), "dubbo-resolve.properties"); if (userResolveFile.exists()) { resolveFile = userResolveFile.getAbsolutePath(); } } // 存在 resolveFile ,则进行文件读取加载。 if (resolveFile != null && resolveFile.length() > 0) { Properties properties = new Properties(); try (FileInputStream fis = new FileInputStream(new File(resolveFile))) { properties.load(fis);//加载属性 } catch (IOException e) { throw new IllegalStateException("Failed to load " + resolveFile + ", cause: " + e.getMessage(), e); } resolve = properties.getProperty(interfaceName); } } if (resolve != null && resolve.length() > 0) { url = resolve; if (logger.isWarnEnabled()) { if (resolveFile != null) { logger.warn("Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); } else { logger.warn("Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); } } } } @Override protected void computeValidRegistryIds() { super.computeValidRegistryIds(); if (StringUtils.isEmpty(getRegistryIds())) { if (getConsumer() != null && StringUtils.isNotEmpty(getConsumer().getRegistryIds())) { setRegistryIds(getConsumer().getRegistryIds()); } } } @Parameter(excluded = true) public String getUniqueServiceName() { return URL.buildKey(interfaceName, getGroup(), getVersion()); } @Override public String getVersion() { return StringUtils.isEmpty(this.version) ? (consumer != null ? consumer.getVersion() : this.version) : this.version; } @Override public String getGroup() { return StringUtils.isEmpty(this.group) ? (consumer != null ? consumer.getGroup() : this.group) : this.group; } public abstract T get(); public abstract void destroy(); }
package com.easypreference; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
/* * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /** * Service-provider classes for the {@link java.nio.channels} * package. * * <p> Only developers who are defining new selector providers or * asynchronous channel providers should need to make direct use of * this package. </p> * * <p> Unless otherwise noted, passing a {@code null} argument to a * constructor or method in any class or interface in this package * will cause a {@link java.lang.NullPointerException * NullPointerException} to be thrown. * * * @since 1.4 * @author Mark Reinhold * @author JSR-51 Expert Group */ package java.nio.channels.spi;
package com.example.karan.traffikill.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class ResultData implements Parcelable { public static final Parcelable.Creator<ResultData> CREATOR = new Parcelable.Creator<ResultData>() { public ResultData createFromParcel(Parcel in) { return new ResultData(in); } public ResultData[] newArray(int size) { return new ResultData[size]; } }; private ResultData(Parcel parcel) { this.name = parcel.readString(); this.rating = parcel.readFloat(); this.geometry = parcel.readParcelable(GeometryData.class.getClassLoader()); parcel.readTypedList(this.photos, PhotoDetails.CREATOR); } @SerializedName("geometry") @Expose private GeometryData geometry; @SerializedName("name") @Expose private String name; @SerializedName("rating") @Expose private float rating; @SerializedName("vicinty") @Expose private String vicinity; @SerializedName("photos") @Expose private ArrayList<PhotoDetails> photos; public ArrayList<PhotoDetails> getPhotosData() { return photos; } public GeometryData getGeometry() { return geometry; } public String getName() { return name; } public float getRating() { return rating; } public String getVicinity() { return vicinity; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeParcelable(this.geometry, flags); dest.writeFloat(this.rating); dest.writeTypedList(this.photos); } }
/* * Copyright 2014-2015 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.docksidestage.dockside.dbflute.bsentity.customize; import java.util.List; import java.util.ArrayList; import org.dbflute.dbmeta.DBMeta; import org.dbflute.dbmeta.AbstractEntity; import org.dbflute.dbmeta.accessory.CustomizeEntity; import org.docksidestage.dockside.dbflute.exentity.customize.*; /** * The entity of SimpleVendorCheck. <br> * <pre> * [primary-key] * * * [column] * VENDOR_CHECK_ID, TYPE_OF_TEXT, TYPE_OF_BOOLEAN, TYPE_OF_NUMERIC_INTEGER, TYPE_OF_NUMERIC_BIGINT, TYPE_OF_NUMERIC_DECIMAL, TYPE_OF_NUMERIC_INTEGER_MIN, TYPE_OF_NUMERIC_INTEGER_MAX, TYPE_OF_NUMERIC_BIGINT_MIN, TYPE_OF_NUMERIC_BIGINT_MAX, TYPE_OF_NUMERIC_SUPERINT_MIN, TYPE_OF_NUMERIC_SUPERINT_MAX, TYPE_OF_NUMERIC_MAXDECIMAL, TYPE_OF_BLOB * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * * * [foreign property] * * * [referrer property] * * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * Long vendorCheckId = entity.getVendorCheckId(); * String typeOfText = entity.getTypeOfText(); * Boolean typeOfBoolean = entity.getTypeOfBoolean(); * Integer typeOfNumericInteger = entity.getTypeOfNumericInteger(); * Long typeOfNumericBigint = entity.getTypeOfNumericBigint(); * java.math.BigDecimal typeOfNumericDecimal = entity.getTypeOfNumericDecimal(); * Integer typeOfNumericIntegerMin = entity.getTypeOfNumericIntegerMin(); * Integer typeOfNumericIntegerMax = entity.getTypeOfNumericIntegerMax(); * Long typeOfNumericBigintMin = entity.getTypeOfNumericBigintMin(); * Long typeOfNumericBigintMax = entity.getTypeOfNumericBigintMax(); * java.math.BigDecimal typeOfNumericSuperintMin = entity.getTypeOfNumericSuperintMin(); * java.math.BigDecimal typeOfNumericSuperintMax = entity.getTypeOfNumericSuperintMax(); * java.math.BigDecimal typeOfNumericMaxdecimal = entity.getTypeOfNumericMaxdecimal(); * byte[] typeOfBlob = entity.getTypeOfBlob(); * entity.setVendorCheckId(vendorCheckId); * entity.setTypeOfText(typeOfText); * entity.setTypeOfBoolean(typeOfBoolean); * entity.setTypeOfNumericInteger(typeOfNumericInteger); * entity.setTypeOfNumericBigint(typeOfNumericBigint); * entity.setTypeOfNumericDecimal(typeOfNumericDecimal); * entity.setTypeOfNumericIntegerMin(typeOfNumericIntegerMin); * entity.setTypeOfNumericIntegerMax(typeOfNumericIntegerMax); * entity.setTypeOfNumericBigintMin(typeOfNumericBigintMin); * entity.setTypeOfNumericBigintMax(typeOfNumericBigintMax); * entity.setTypeOfNumericSuperintMin(typeOfNumericSuperintMin); * entity.setTypeOfNumericSuperintMax(typeOfNumericSuperintMax); * entity.setTypeOfNumericMaxdecimal(typeOfNumericMaxdecimal); * entity.setTypeOfBlob(typeOfBlob); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsSimpleVendorCheck extends AbstractEntity implements CustomizeEntity { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** VENDOR_CHECK_ID: {DECIMAL(16), refers to VENDOR_CHECK.VENDOR_CHECK_ID} */ protected Long _vendorCheckId; /** TYPE_OF_TEXT: {CLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_TEXT} */ protected String _typeOfText; /** TYPE_OF_BOOLEAN: {BOOLEAN(1), refers to VENDOR_CHECK.TYPE_OF_BOOLEAN} */ protected Boolean _typeOfBoolean; /** TYPE_OF_NUMERIC_INTEGER: {DECIMAL(5), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER} */ protected Integer _typeOfNumericInteger; /** TYPE_OF_NUMERIC_BIGINT: {DECIMAL(12), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT} */ protected Long _typeOfNumericBigint; /** TYPE_OF_NUMERIC_DECIMAL: {DECIMAL(5, 3), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_DECIMAL} */ protected java.math.BigDecimal _typeOfNumericDecimal; /** TYPE_OF_NUMERIC_INTEGER_MIN: {DECIMAL(1), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MIN} */ protected Integer _typeOfNumericIntegerMin; /** TYPE_OF_NUMERIC_INTEGER_MAX: {DECIMAL(9), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MAX} */ protected Integer _typeOfNumericIntegerMax; /** TYPE_OF_NUMERIC_BIGINT_MIN: {DECIMAL(10), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MIN} */ protected Long _typeOfNumericBigintMin; /** TYPE_OF_NUMERIC_BIGINT_MAX: {DECIMAL(18), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MAX} */ protected Long _typeOfNumericBigintMax; /** TYPE_OF_NUMERIC_SUPERINT_MIN: {DECIMAL(19), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MIN} */ protected java.math.BigDecimal _typeOfNumericSuperintMin; /** TYPE_OF_NUMERIC_SUPERINT_MAX: {DECIMAL(38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MAX} */ protected java.math.BigDecimal _typeOfNumericSuperintMax; /** TYPE_OF_NUMERIC_MAXDECIMAL: {DECIMAL(38, 38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_MAXDECIMAL} */ protected java.math.BigDecimal _typeOfNumericMaxdecimal; /** TYPE_OF_BLOB: {BLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_BLOB} */ protected byte[] _typeOfBlob; // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public DBMeta asDBMeta() { return org.docksidestage.dockside.dbflute.bsentity.customize.dbmeta.SimpleVendorCheckDbm.getInstance(); } /** {@inheritDoc} */ public String asTableDbName() { return "SimpleVendorCheck"; } // =================================================================================== // Key Handling // ============ /** {@inheritDoc} */ public boolean hasPrimaryKeyValue() { return false; } // =================================================================================== // Foreign Property // ================ // =================================================================================== // Referrer Property // ================= protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import return new ArrayList<ELEMENT>(); } // =================================================================================== // Basic Override // ============== @Override protected boolean doEquals(Object obj) { if (obj instanceof BsSimpleVendorCheck) { BsSimpleVendorCheck other = (BsSimpleVendorCheck)obj; if (!xSV(_vendorCheckId, other._vendorCheckId)) { return false; } if (!xSV(_typeOfText, other._typeOfText)) { return false; } if (!xSV(_typeOfBoolean, other._typeOfBoolean)) { return false; } if (!xSV(_typeOfNumericInteger, other._typeOfNumericInteger)) { return false; } if (!xSV(_typeOfNumericBigint, other._typeOfNumericBigint)) { return false; } if (!xSV(_typeOfNumericDecimal, other._typeOfNumericDecimal)) { return false; } if (!xSV(_typeOfNumericIntegerMin, other._typeOfNumericIntegerMin)) { return false; } if (!xSV(_typeOfNumericIntegerMax, other._typeOfNumericIntegerMax)) { return false; } if (!xSV(_typeOfNumericBigintMin, other._typeOfNumericBigintMin)) { return false; } if (!xSV(_typeOfNumericBigintMax, other._typeOfNumericBigintMax)) { return false; } if (!xSV(_typeOfNumericSuperintMin, other._typeOfNumericSuperintMin)) { return false; } if (!xSV(_typeOfNumericSuperintMax, other._typeOfNumericSuperintMax)) { return false; } if (!xSV(_typeOfNumericMaxdecimal, other._typeOfNumericMaxdecimal)) { return false; } if (!xSV(_typeOfBlob, other._typeOfBlob)) { return false; } return true; } else { return false; } } @Override protected int doHashCode(int initial) { int hs = initial; hs = xCH(hs, asTableDbName()); hs = xCH(hs, _vendorCheckId); hs = xCH(hs, _typeOfText); hs = xCH(hs, _typeOfBoolean); hs = xCH(hs, _typeOfNumericInteger); hs = xCH(hs, _typeOfNumericBigint); hs = xCH(hs, _typeOfNumericDecimal); hs = xCH(hs, _typeOfNumericIntegerMin); hs = xCH(hs, _typeOfNumericIntegerMax); hs = xCH(hs, _typeOfNumericBigintMin); hs = xCH(hs, _typeOfNumericBigintMax); hs = xCH(hs, _typeOfNumericSuperintMin); hs = xCH(hs, _typeOfNumericSuperintMax); hs = xCH(hs, _typeOfNumericMaxdecimal); hs = xCH(hs, _typeOfBlob); return hs; } @Override protected String doBuildStringWithRelation(String li) { return ""; } @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(xfND(_vendorCheckId)); sb.append(dm).append(xfND(_typeOfText)); sb.append(dm).append(xfND(_typeOfBoolean)); sb.append(dm).append(xfND(_typeOfNumericInteger)); sb.append(dm).append(xfND(_typeOfNumericBigint)); sb.append(dm).append(xfND(_typeOfNumericDecimal)); sb.append(dm).append(xfND(_typeOfNumericIntegerMin)); sb.append(dm).append(xfND(_typeOfNumericIntegerMax)); sb.append(dm).append(xfND(_typeOfNumericBigintMin)); sb.append(dm).append(xfND(_typeOfNumericBigintMax)); sb.append(dm).append(xfND(_typeOfNumericSuperintMin)); sb.append(dm).append(xfND(_typeOfNumericSuperintMax)); sb.append(dm).append(xfND(_typeOfNumericMaxdecimal)); sb.append(dm).append(xfBA(_typeOfBlob)); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } @Override protected String doBuildRelationString(String dm) { return ""; } @Override public SimpleVendorCheck clone() { return (SimpleVendorCheck)super.clone(); } // =================================================================================== // Accessor // ======== /** * [get] VENDOR_CHECK_ID: {DECIMAL(16), refers to VENDOR_CHECK.VENDOR_CHECK_ID} <br> * @return The value of the column 'VENDOR_CHECK_ID'. (NullAllowed even if selected: for no constraint) */ public Long getVendorCheckId() { checkSpecifiedProperty("vendorCheckId"); return _vendorCheckId; } /** * [set] VENDOR_CHECK_ID: {DECIMAL(16), refers to VENDOR_CHECK.VENDOR_CHECK_ID} <br> * @param vendorCheckId The value of the column 'VENDOR_CHECK_ID'. (NullAllowed: null update allowed for no constraint) */ public void setVendorCheckId(Long vendorCheckId) { registerModifiedProperty("vendorCheckId"); _vendorCheckId = vendorCheckId; } /** * [get] TYPE_OF_TEXT: {CLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_TEXT} <br> * @return The value of the column 'TYPE_OF_TEXT'. (NullAllowed even if selected: for no constraint) */ public String getTypeOfText() { checkSpecifiedProperty("typeOfText"); return _typeOfText; } /** * [set] TYPE_OF_TEXT: {CLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_TEXT} <br> * @param typeOfText The value of the column 'TYPE_OF_TEXT'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfText(String typeOfText) { registerModifiedProperty("typeOfText"); _typeOfText = typeOfText; } /** * [get] TYPE_OF_BOOLEAN: {BOOLEAN(1), refers to VENDOR_CHECK.TYPE_OF_BOOLEAN} <br> * @return The value of the column 'TYPE_OF_BOOLEAN'. (NullAllowed even if selected: for no constraint) */ public Boolean getTypeOfBoolean() { checkSpecifiedProperty("typeOfBoolean"); return _typeOfBoolean; } /** * [set] TYPE_OF_BOOLEAN: {BOOLEAN(1), refers to VENDOR_CHECK.TYPE_OF_BOOLEAN} <br> * @param typeOfBoolean The value of the column 'TYPE_OF_BOOLEAN'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfBoolean(Boolean typeOfBoolean) { registerModifiedProperty("typeOfBoolean"); _typeOfBoolean = typeOfBoolean; } /** * [get] TYPE_OF_NUMERIC_INTEGER: {DECIMAL(5), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER} <br> * @return The value of the column 'TYPE_OF_NUMERIC_INTEGER'. (NullAllowed even if selected: for no constraint) */ public Integer getTypeOfNumericInteger() { checkSpecifiedProperty("typeOfNumericInteger"); return _typeOfNumericInteger; } /** * [set] TYPE_OF_NUMERIC_INTEGER: {DECIMAL(5), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER} <br> * @param typeOfNumericInteger The value of the column 'TYPE_OF_NUMERIC_INTEGER'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericInteger(Integer typeOfNumericInteger) { registerModifiedProperty("typeOfNumericInteger"); _typeOfNumericInteger = typeOfNumericInteger; } /** * [get] TYPE_OF_NUMERIC_BIGINT: {DECIMAL(12), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT} <br> * @return The value of the column 'TYPE_OF_NUMERIC_BIGINT'. (NullAllowed even if selected: for no constraint) */ public Long getTypeOfNumericBigint() { checkSpecifiedProperty("typeOfNumericBigint"); return _typeOfNumericBigint; } /** * [set] TYPE_OF_NUMERIC_BIGINT: {DECIMAL(12), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT} <br> * @param typeOfNumericBigint The value of the column 'TYPE_OF_NUMERIC_BIGINT'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericBigint(Long typeOfNumericBigint) { registerModifiedProperty("typeOfNumericBigint"); _typeOfNumericBigint = typeOfNumericBigint; } /** * [get] TYPE_OF_NUMERIC_DECIMAL: {DECIMAL(5, 3), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_DECIMAL} <br> * @return The value of the column 'TYPE_OF_NUMERIC_DECIMAL'. (NullAllowed even if selected: for no constraint) */ public java.math.BigDecimal getTypeOfNumericDecimal() { checkSpecifiedProperty("typeOfNumericDecimal"); return _typeOfNumericDecimal; } /** * [set] TYPE_OF_NUMERIC_DECIMAL: {DECIMAL(5, 3), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_DECIMAL} <br> * @param typeOfNumericDecimal The value of the column 'TYPE_OF_NUMERIC_DECIMAL'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericDecimal(java.math.BigDecimal typeOfNumericDecimal) { registerModifiedProperty("typeOfNumericDecimal"); _typeOfNumericDecimal = typeOfNumericDecimal; } /** * [get] TYPE_OF_NUMERIC_INTEGER_MIN: {DECIMAL(1), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MIN} <br> * @return The value of the column 'TYPE_OF_NUMERIC_INTEGER_MIN'. (NullAllowed even if selected: for no constraint) */ public Integer getTypeOfNumericIntegerMin() { checkSpecifiedProperty("typeOfNumericIntegerMin"); return _typeOfNumericIntegerMin; } /** * [set] TYPE_OF_NUMERIC_INTEGER_MIN: {DECIMAL(1), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MIN} <br> * @param typeOfNumericIntegerMin The value of the column 'TYPE_OF_NUMERIC_INTEGER_MIN'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericIntegerMin(Integer typeOfNumericIntegerMin) { registerModifiedProperty("typeOfNumericIntegerMin"); _typeOfNumericIntegerMin = typeOfNumericIntegerMin; } /** * [get] TYPE_OF_NUMERIC_INTEGER_MAX: {DECIMAL(9), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MAX} <br> * @return The value of the column 'TYPE_OF_NUMERIC_INTEGER_MAX'. (NullAllowed even if selected: for no constraint) */ public Integer getTypeOfNumericIntegerMax() { checkSpecifiedProperty("typeOfNumericIntegerMax"); return _typeOfNumericIntegerMax; } /** * [set] TYPE_OF_NUMERIC_INTEGER_MAX: {DECIMAL(9), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_INTEGER_MAX} <br> * @param typeOfNumericIntegerMax The value of the column 'TYPE_OF_NUMERIC_INTEGER_MAX'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericIntegerMax(Integer typeOfNumericIntegerMax) { registerModifiedProperty("typeOfNumericIntegerMax"); _typeOfNumericIntegerMax = typeOfNumericIntegerMax; } /** * [get] TYPE_OF_NUMERIC_BIGINT_MIN: {DECIMAL(10), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MIN} <br> * @return The value of the column 'TYPE_OF_NUMERIC_BIGINT_MIN'. (NullAllowed even if selected: for no constraint) */ public Long getTypeOfNumericBigintMin() { checkSpecifiedProperty("typeOfNumericBigintMin"); return _typeOfNumericBigintMin; } /** * [set] TYPE_OF_NUMERIC_BIGINT_MIN: {DECIMAL(10), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MIN} <br> * @param typeOfNumericBigintMin The value of the column 'TYPE_OF_NUMERIC_BIGINT_MIN'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericBigintMin(Long typeOfNumericBigintMin) { registerModifiedProperty("typeOfNumericBigintMin"); _typeOfNumericBigintMin = typeOfNumericBigintMin; } /** * [get] TYPE_OF_NUMERIC_BIGINT_MAX: {DECIMAL(18), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MAX} <br> * @return The value of the column 'TYPE_OF_NUMERIC_BIGINT_MAX'. (NullAllowed even if selected: for no constraint) */ public Long getTypeOfNumericBigintMax() { checkSpecifiedProperty("typeOfNumericBigintMax"); return _typeOfNumericBigintMax; } /** * [set] TYPE_OF_NUMERIC_BIGINT_MAX: {DECIMAL(18), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_BIGINT_MAX} <br> * @param typeOfNumericBigintMax The value of the column 'TYPE_OF_NUMERIC_BIGINT_MAX'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericBigintMax(Long typeOfNumericBigintMax) { registerModifiedProperty("typeOfNumericBigintMax"); _typeOfNumericBigintMax = typeOfNumericBigintMax; } /** * [get] TYPE_OF_NUMERIC_SUPERINT_MIN: {DECIMAL(19), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MIN} <br> * @return The value of the column 'TYPE_OF_NUMERIC_SUPERINT_MIN'. (NullAllowed even if selected: for no constraint) */ public java.math.BigDecimal getTypeOfNumericSuperintMin() { checkSpecifiedProperty("typeOfNumericSuperintMin"); return _typeOfNumericSuperintMin; } /** * [set] TYPE_OF_NUMERIC_SUPERINT_MIN: {DECIMAL(19), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MIN} <br> * @param typeOfNumericSuperintMin The value of the column 'TYPE_OF_NUMERIC_SUPERINT_MIN'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericSuperintMin(java.math.BigDecimal typeOfNumericSuperintMin) { registerModifiedProperty("typeOfNumericSuperintMin"); _typeOfNumericSuperintMin = typeOfNumericSuperintMin; } /** * [get] TYPE_OF_NUMERIC_SUPERINT_MAX: {DECIMAL(38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MAX} <br> * @return The value of the column 'TYPE_OF_NUMERIC_SUPERINT_MAX'. (NullAllowed even if selected: for no constraint) */ public java.math.BigDecimal getTypeOfNumericSuperintMax() { checkSpecifiedProperty("typeOfNumericSuperintMax"); return _typeOfNumericSuperintMax; } /** * [set] TYPE_OF_NUMERIC_SUPERINT_MAX: {DECIMAL(38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_SUPERINT_MAX} <br> * @param typeOfNumericSuperintMax The value of the column 'TYPE_OF_NUMERIC_SUPERINT_MAX'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericSuperintMax(java.math.BigDecimal typeOfNumericSuperintMax) { registerModifiedProperty("typeOfNumericSuperintMax"); _typeOfNumericSuperintMax = typeOfNumericSuperintMax; } /** * [get] TYPE_OF_NUMERIC_MAXDECIMAL: {DECIMAL(38, 38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_MAXDECIMAL} <br> * @return The value of the column 'TYPE_OF_NUMERIC_MAXDECIMAL'. (NullAllowed even if selected: for no constraint) */ public java.math.BigDecimal getTypeOfNumericMaxdecimal() { checkSpecifiedProperty("typeOfNumericMaxdecimal"); return _typeOfNumericMaxdecimal; } /** * [set] TYPE_OF_NUMERIC_MAXDECIMAL: {DECIMAL(38, 38), refers to VENDOR_CHECK.TYPE_OF_NUMERIC_MAXDECIMAL} <br> * @param typeOfNumericMaxdecimal The value of the column 'TYPE_OF_NUMERIC_MAXDECIMAL'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfNumericMaxdecimal(java.math.BigDecimal typeOfNumericMaxdecimal) { registerModifiedProperty("typeOfNumericMaxdecimal"); _typeOfNumericMaxdecimal = typeOfNumericMaxdecimal; } /** * [get] TYPE_OF_BLOB: {BLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_BLOB} <br> * @return The value of the column 'TYPE_OF_BLOB'. (NullAllowed even if selected: for no constraint) */ public byte[] getTypeOfBlob() { checkSpecifiedProperty("typeOfBlob"); return _typeOfBlob; } /** * [set] TYPE_OF_BLOB: {BLOB(2147483647), refers to VENDOR_CHECK.TYPE_OF_BLOB} <br> * @param typeOfBlob The value of the column 'TYPE_OF_BLOB'. (NullAllowed: null update allowed for no constraint) */ public void setTypeOfBlob(byte[] typeOfBlob) { registerModifiedProperty("typeOfBlob"); _typeOfBlob = typeOfBlob; } }
package com.jayqqaa12.abase.kit.io; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.jayqqaa12.abase.kit.common.TAG; import android.content.Context; import android.util.Log; /** * 文件 工具栏 * */ public class FileKit { /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The file copy buffer size (10 MB) (原为30MB,为更适合在手机上使用,将其改为10MB, */ private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 10; /** * <p> * 将一个目录下的文件全部拷贝到另一个目录里面,并且保留文件日期。 * </p> * <p> * 如果目标目录不存在,则被创建。 如果目标目录已经存在,则将会合并两个文件夹的内容,若有冲突则替换掉目标目录中的文件。 * </p> * * @param srcDir * 源目录,不能为null且必须存在。 * @param destDir * 目标目录,不能为null。 * @throws NullPointerException * 如果源目录或目标目录为null。 * @throws IOException * 如果源目录或目标目录无效。 * @throws IOException * 如果拷贝中出现IO错误。 */ public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (srcDir.exists() && srcDir.isDirectory() == false) { throw new IllegalArgumentException("Source '" + destDir + "' is not a directory"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (destDir.exists() && destDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); } copyDirectory(srcDir, new File(destDir, srcDir.getName()), true); } /** * <p> * 将目录及其以下子目录拷贝到一个新的位置,并且保留文件日期。 * <p> * 如果目标目录不存在,则被创建。 如果目标目录已经存在,则将会合并两个文件夹的内容,若有冲突则替换掉目标目录中的文件。 * <p> * * @param srcDir * 一个存在的源目录,不能为null。 * @param destDir * 新的目录,不能为null。 * * @throws NullPointerException * 如果源目录或目标目录为null。 * @throws IOException * 如果源目录或目标目录无效。 * @throws IOException * 如果拷贝中出现IO错误。 */ public static void copyDirectory(File srcDir, File destDir) throws IOException { copyDirectory(srcDir, destDir, true); } /** * 拷贝目录到一个新的位置。 * <p> * 该方法将拷贝指定的源目录的所有内容到一个新的目录中。 * </p> * <p> * 如果目标目录不存在,则被创建。 如果目标目录已经存在,则将会合并两个文件夹的内容,若有冲突则替换掉目标目录中的文件。 * </p> * * @param srcDir * 一个存在的源目录,不能为null。 * @param destDir * 新的目录,不能为null。 * * @throws NullPointerException * 如果源目录或目标目录为null。 * @throws IOException * 如果源目录或目标目录无效。 * @throws IOException * 如果拷贝中出现IO错误。 */ public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException { if (srcDir == null) { throw new NullPointerException("Source must not be null"); } if (srcDir.exists() && srcDir.isDirectory() == false) { throw new IllegalArgumentException("Source '" + destDir + "' is not a directory"); } if (destDir == null) { throw new NullPointerException("Destination must not be null"); } if (destDir.exists() && destDir.isDirectory() == false) { throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); } if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); } // 为满足当目标目录在源目录里面的情况。 List<String> exclusionList = null; if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { File[] srcFiles = srcDir.listFiles(); if (srcFiles != null && srcFiles.length > 0) { exclusionList = new ArrayList<String>(srcFiles.length); for (File srcFile : srcFiles) { File copiedFile = new File(destDir, srcFile.getName()); exclusionList.add(copiedFile.getCanonicalPath()); } } } doCopyDirectory(srcDir, destDir, preserveFileDate, exclusionList); } /** * Internal copy directory method. * * @param srcDir * the validated source directory, must not be <code>null</code> * @param destDir * the validated destination directory, must not be * <code>null</code> * @param filter * the filter to apply, null means copy all directories and files * @param preserveFileDate * whether to preserve the file date * @param exclusionList * List of files and directories to exclude from the copy, may be * null * @throws IOException * if an error occurs * @since Commons IO 1.1 */ private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, List<String> exclusionList) throws IOException { // recurse File[] srcFiles = srcDir.listFiles(); if (srcFiles == null) { // null if abstract pathname does not denote a // directory, or if an I/O error occurs throw new IOException("Failed to list contents of " + srcDir); } if (destDir.exists()) { if (destDir.isDirectory() == false) { throw new IOException("Destination '" + destDir + "' exists but is not a directory"); } } else { if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException("Destination '" + destDir + "' directory cannot be created"); } } if (destDir.canWrite() == false) { throw new IOException("Destination '" + destDir + "' cannot be written to"); } for (File srcFile : srcFiles) { File dstFile = new File(destDir, srcFile.getName()); if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { if (srcFile.isDirectory()) { doCopyDirectory(srcFile, dstFile, preserveFileDate, exclusionList); } else { doCopyFile(srcFile, dstFile, preserveFileDate); } } } // Do this last, as the above has probably affected directory metadata if (preserveFileDate) { destDir.setLastModified(srcDir.lastModified()); } } /** * Internal copy file method. * * @param srcFile * the validated source file, must not be <code>null</code> * @param destFile * the validated destination file, must not be <code>null</code> * @param preserveFileDate * whether to preserve the file date * @throws IOException * if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { IOKit.closeQuietly(output); IOKit.closeQuietly(fos); IOKit.closeQuietly(input); IOKit.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling <code>new FileInputStream(file)</code> * . * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * <p> * An exception is thrown if the file does not exist. An exception is thrown * if the file object exists but is a directory. An exception is thrown if * the file exists but cannot be read. * * @param file * the file to open for input, must not be <code>null</code> * @return a new {@link FileInputStream} for the specified file * @throws FileNotFoundException * if the file does not exist * @throws IOException * if the file object is a directory * @throws IOException * if the file cannot be read * @since Commons IO 1.3 */ public static FileInputStream openInputStream(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canRead() == false) { throw new IOException("File '" + file + "' cannot be read"); } } else { throw new FileNotFoundException("File '" + file + "' does not exist"); } return new FileInputStream(file); } /** * Reads the contents of a file line by line to a List of Strings. The file * is always closed. * * @param file * the file to read, must not be <code>null</code> * @param encoding * the encoding to use, <code>null</code> means platform default * @return the list of Strings representing each line in the file, never * <code>null</code> * @throws IOException * in case of an I/O error * @throws java.io.UnsupportedEncodingException * if the encoding is not supported by the VM * @since Commons IO 1.1 */ public static List<String> readLines(File file, String encoding) throws IOException { InputStream in = null; try { in = openInputStream(file); return readLines(in, encoding); } finally { IOKit.closeQuietly(in); } } /** * Reads the contents of a file line by line to a List of Strings using the * default encoding for the VM. The file is always closed. * * @param file * the file to read, must not be <code>null</code> * @return the list of Strings representing each line in the file, never * <code>null</code> * @throws IOException * in case of an I/O error * @since Commons IO 1.3 */ public static List<String> readLines(File file) throws IOException { return readLines(file, null); } /** * Get the contents of an <code>InputStream</code> as a list of Strings, one * entry per line, using the default character encoding of the platform. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * * @param input * the <code>InputStream</code> to read from, not null * @return the list of Strings, never null * @throws NullPointerException * if the input is null * @throws IOException * if an I/O error occurs * @since Commons IO 1.1 */ public static List<String> readLines(InputStream input) throws IOException { InputStreamReader reader = new InputStreamReader(input); return readLines(reader); } /** * Get the contents of an <code>InputStream</code> as a list of Strings, one * entry per line, using the specified character encoding. * <p> * Character encoding names can be found at <a * href="http://www.iana.org/assignments/character-sets">IANA</a>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * * @param input * the <code>InputStream</code> to read from, not null * @param encoding * the encoding to use, null means platform default * @return the list of Strings, never null * @throws NullPointerException * if the input is null * @throws IOException * if an I/O error occurs * @since Commons IO 1.1 */ public static List<String> readLines(InputStream input, String encoding) throws IOException { if (encoding == null) { return readLines(input); } else { InputStreamReader reader = new InputStreamReader(input, encoding); return readLines(reader); } } /** * Get the contents of a <code>Reader</code> as a list of Strings, one entry * per line. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedReader</code>. * * @param input * the <code>Reader</code> to read from, not null * @return the list of Strings, never null * @throws NullPointerException * if the input is null * @throws IOException * if an I/O error occurs * @since Commons IO 1.1 */ public static List<String> readLines(Reader input) throws IOException { BufferedReader reader = new BufferedReader(input); List<String> list = new ArrayList<String>(); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } return list; } public static String[] getAllAssertFileName(Context context) { String[] files = null; try { files = context.getAssets().list(""); } catch (IOException e) { e.printStackTrace(); } return files; } /** * 返回 后缀名 为 。rule 的文件 名 * * @param files * 要匹配的文件 * @param rule * 匹配规则 * @return 返回 后缀名 为 。rule 的文件 名 */ public static List<String> getFiles(String[] files, String rule) { List<String> ruleFiles = new ArrayList<String>(); for (String file : files) { if (file.endsWith(rule)) { ruleFiles.add(file); } } return ruleFiles; } /** * * 输入 要检查 的文件名列表 检查 zip 文件 是否解压到 目标目录 * * @param files * 检查的zip 文件 * @param toPath * 解压的目录路径 * @return 是否解压到 目标文件 * @throws FileNotFoundException */ public static boolean isFileDecompression(String[] files, String toPath) throws FileNotFoundException { return isFileDecompression(files, toPath, ".zip"); } /** * * 输入 要检查 的文件名列表 检查 zip 文件 是否解压到 目标目录 * * @param files * 检查的zip 文件 * @param toPath * 解压的目录路径 * @param rule * 要检测文件的后缀名 可以自定义 不一定是 。zip * @return 是否解压到 目标文件 * @throws FileNotFoundException */ public static boolean isFileDecompression(String[] files, String toPath, String rule) throws FileNotFoundException { boolean result = true; if (files.length == 0) throw new FileNotFoundException(); List<String> zipFiles = getFiles(files, rule); for (String zipFile : zipFiles) { String dbFile = zipFile.replace(rule, ".db"); File file = new File(toPath + File.separator + dbFile); if (!file.exists()) { Log.i(TAG.UTIL,dbFile+" 没有找到"); result = false; } } return result; } /** * 拷贝 指定 的 单个asset 文件到指定目录 * @param context * @param assetsFileNmae * @param outDirName * @throws IOException */ public static void copyAssetsFile(Context context, String assetsFileNmae, String outDirName) throws IOException { // 判断目录是否存在。如不存在则创建一个目录 File outDir = new File(outDirName); if (!outDir.exists() || !outDir.isDirectory()) { outDir.mkdir(); } // 建立输出 文件 File outFile = new File(outDirName + File.separator + assetsFileNmae); if (!outFile.exists()) { outFile.createNewFile(); } InputStream is = context.getAssets().open(assetsFileNmae); OutputStream os = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } os.flush(); os.close(); is.close(); } /** * 查到 文件夹 下面 所以 文件 非递归方式 * */ public static LinkedList<File> listLinkedFiles(String strPath) { LinkedList<File> list = new LinkedList<File>(); File dir = new File(strPath); File file[] = dir.listFiles(); for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) list.add(file[i]); else System.out.println(file[i].getAbsolutePath()); } File tmp; while (!list.isEmpty()) { tmp = (File) list.removeFirst(); if (tmp.isDirectory()) { file = tmp.listFiles(); if (file == null) continue; for (int i = 0; i < file.length; i++) { if (file[i].isDirectory()) list.add(file[i]); else System.out.println(file[i].getAbsolutePath()); } } else { System.out.println(tmp.getAbsolutePath()); } } return list; } /** * 查到 文件夹 下面 所以 文件 递归方式 * */ public static ArrayList<File> listFiles(String strPath) { return refreshFileList(strPath); } private static ArrayList<File> refreshFileList(String strPath) { ArrayList<File> filelist = new ArrayList<File>(); File dir = new File(strPath); File[] files = dir.listFiles(); if (files == null) return null; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { refreshFileList(files[i].getAbsolutePath()); } else { if (files[i].getName().toLowerCase().endsWith("zip")) filelist.add(files[i]); } } return filelist; } public static boolean deleteFile(String fileName) { File file = new File(fileName); if (file.exists()) return file.delete(); else return false; } /** * 删除目录(文件夹)以及目录下的文件 * @param dir 被删除目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String dir){ //如果dir不以文件分隔符结尾,自动添加文件分隔符 if(!dir.endsWith(File.separator)){ dir = dir+File.separator; } File dirFile = new File(dir); //如果dir对应的文件不存在,或者不是一个目录,则退出 if(!dirFile.exists() || !dirFile.isDirectory()){ return false; } boolean flag = true; //删除文件夹下的所有文件(包括子目录) File[] files = dirFile.listFiles(); for(int i=0;i<files.length;i++){ //删除子文件 if(files[i].isFile()){ flag = deleteFile(files[i].getAbsolutePath()); if(!flag){ break; } } //删除子目录 else{ flag = deleteDirectory(files[i].getAbsolutePath()); if(!flag){ break; } } } if(!flag){ return false; } //删除当前目录 if(dirFile.delete()){ return true; }else{ return false; } } }
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2014-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file MainMenu.java /// @author Maximiliano Bottazzi /// @date 2014 /// // /****************************************************************************/ package de.dlr.ts.commons.javafx.mainwindow.top; import java.util.ArrayList; import java.util.List; import javafx.scene.Node; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.input.KeyCombination; /** * * @author @author <a href="mailto:maximiliano.bottazzi@dlr.de">Maximiliano Bottazzi</a> */ public class MainMenu { private List<Menu> menus = new ArrayList<>(); private MenuBar menuBar = new MenuBar(); //default height 25 private FileMenu fileMenu = new FileMenu(); private EditMenu editMenu = new EditMenu(); private Menu windowMenu = new Menu("_Window"); private Menu helpMenu = new Menu("_Help"); /** * */ public MainMenu() { menus.add(fileMenu); menus.add(editMenu); menus.add(windowMenu); menus.add(helpMenu); windowMenu.setAccelerator(KeyCombination.keyCombination("SHORTCUT+W")); helpMenu.setAccelerator(KeyCombination.keyCombination("SHORTCUT+H")); loadMenus(); } /** * * @return */ public FileMenu getFileMenu() { return fileMenu; } /** * * @return */ public EditMenu getEditMenu() { return editMenu; } /** * * @return */ public Menu getWindowMenu() { return windowMenu; } /** * * @return */ public Menu getHelpMenu() { return helpMenu; } /** * * @param name * @return */ public Menu getMenu(String name) { for (Menu menu : menus) if (menu.getText().equalsIgnoreCase(name)) { return menu; } return null; } /** * * @return */ public Node getNode() { return menuBar; } /** * */ private void loadMenus() { menuBar.getMenus().clear(); for (Menu menu : menus) { menuBar.getMenus().add(menu); } } /** * * @param index * @param menuName */ public Menu addMenu(int index, String menuName) { Menu menu = new Menu(menuName); menus.add(index, menu); loadMenus(); return menu; } /** * * @param menuName */ public void removeMenu(String menuName) { for (int i = 0; i < menus.size(); i++) { if (menus.get(i).getText().equalsIgnoreCase(menuName)) { menus.remove(i); break; } } } }
package com.neophoenix.proxy; public class TargetClass { public int someMethod(){ System.out.println("am awesome!!!"); return 2; } }
package com.rotanava.framework.module.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.rotanava.framework.model.SysBehaviorLog; import org.apache.ibatis.annotations.Mapper; @Mapper public interface BaseLogMapper extends BaseMapper<SysBehaviorLog> { }
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.ccda_r1_1.reactionobservation; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.annotation.Hl7XmlMapping; import ca.infoway.messagebuilder.datatype.BL; import ca.infoway.messagebuilder.datatype.II; import ca.infoway.messagebuilder.datatype.INT; import ca.infoway.messagebuilder.datatype.LIST; import ca.infoway.messagebuilder.datatype.impl.BLImpl; import ca.infoway.messagebuilder.datatype.impl.IIImpl; import ca.infoway.messagebuilder.datatype.impl.INTImpl; import ca.infoway.messagebuilder.datatype.impl.LISTImpl; import ca.infoway.messagebuilder.datatype.lang.Identifier; import ca.infoway.messagebuilder.model.MessagePartBean; import ca.infoway.messagebuilder.model.ccda_r1_1.procedureactivityprocedure.ProcedureBean; import java.util.List; @Hl7PartTypeMapping({"ReactionObservation.ProcedureActivityProcedureEntryRelationship"}) public class ProcedureActivityProcedureEntryRelationshipBean extends MessagePartBean implements EntryRelationshipChoice { private static final long serialVersionUID = 20190617L; private BL contextConductionInd = new BLImpl(); private BL negationInd = new BLImpl(); private II typeId = new IIImpl(); private LIST<II, Identifier> templateId = new LISTImpl<II, Identifier>(IIImpl.class); private INT sequenceNumber = new INTImpl(); private BL seperatableInd = new BLImpl(); private ProcedureBean procedure; /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.contextConductionInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ @Hl7XmlMapping({"contextConductionInd"}) public Boolean getContextConductionInd() { return this.contextConductionInd.getValue(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.contextConductionInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ public void setContextConductionInd(Boolean contextConductionInd) { this.contextConductionInd.setValue(contextConductionInd); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.negationInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ @Hl7XmlMapping({"negationInd"}) public Boolean getNegationInd() { return this.negationInd.getValue(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.negationInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ public void setNegationInd(Boolean negationInd) { this.negationInd.setValue(negationInd); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.typeId</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ @Hl7XmlMapping({"typeId"}) public Identifier getTypeId() { return this.typeId.getValue(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.typeId</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ public void setTypeId(Identifier typeId) { this.typeId.setValue(typeId); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.templateId</p> * * <p>Conformance/Cardinality: OPTIONAL (0-*)</p> */ @Hl7XmlMapping({"templateId"}) public List<Identifier> getTemplateId() { return this.templateId.rawList(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.sequenceNumber</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ @Hl7XmlMapping({"sequenceNumber"}) public Integer getSequenceNumber() { return this.sequenceNumber.getValue(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.sequenceNumber</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber.setValue(sequenceNumber); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.seperatableInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ @Hl7XmlMapping({"seperatableInd"}) public Boolean getSeperatableInd() { return this.seperatableInd.getValue(); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.seperatableInd</p> * * <p>Conformance/Cardinality: OPTIONAL (0-1)</p> */ public void setSeperatableInd(Boolean seperatableInd) { this.seperatableInd.setValue(seperatableInd); } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.procedure</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"procedure"}) public ProcedureBean getProcedure() { return this.procedure; } /** * <p>Relationship: * ReactionObservation.ProcedureActivityProcedureEntryRelationship.procedure</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setProcedure(ProcedureBean procedure) { this.procedure = procedure; } }
/** * Copyright (c) 2016-2019 SWAN开源 All rights reserved. * * https://www.swan.io * * 版权所有,侵权必究! */ package io.swan.modules.sys.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import javax.validation.constraints.NotBlank; import java.io.Serializable; /** * 数据字典 * * @author Mark sunlightcs@gmail.com */ @Data @TableName("sys_dict") public class SysDictEntity implements Serializable { private static final long serialVersionUID = 1L; @TableId private Long id; /** * 字典名称 */ @NotBlank(message="字典名称不能为空") private String name; /** * 字典类型 */ @NotBlank(message="字典类型不能为空") private String type; /** * 字典码 */ @NotBlank(message="字典码不能为空") private String code; /** * 字典值 */ @NotBlank(message="字典值不能为空") private String value; /** * 排序 */ private Integer orderNum; /** * 备注 */ private String remark; /** * 删除标记 -1:已删除 0:正常 */ @TableLogic private Integer delFlag; }
package com.lewin.qrcode; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.RGBLuminanceSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeReader; import java.util.Hashtable; /** * Created by lewin on 2018/3/14. */ public class QRScanReader extends ReactContextBaseJavaModule { public QRScanReader(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "QRScanReader"; } @ReactMethod public void readerQR(String fileUrl, Promise promise) { Result result = scanningImage(fileUrl); if (result == null) { promise.reject("404", "No related QR code"); result = decodeBarcodeRGB(fileUrl); if (result == null) { result = decodeBarcodeYUV(fileUrl); if (result == null) { promise.reject("404", "No related QR code"); } else { promise.resolve(result.getText()); } } else { promise.resolve(result.getText()); } } else { promise.resolve(result.getText()); } } /** * Method for scanning QR code pictures * * @param path * @return */ public Result scanningImage(String path) { if (path == null || path.length() == 0) { return null; } Hashtable<DecodeHintType, String> hints = new Hashtable<>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // Set the encoding of QR code content BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // Get the original size first Bitmap scanBitmap = BitmapFactory.decodeFile(path, options); options.inJustDecodeBounds = false; // Get new size int sampleSize = (int) (options.outHeight / (float) 200); if (sampleSize <= 0) sampleSize = 1; options.inSampleSize = sampleSize; scanBitmap = BitmapFactory.decodeFile(path, options); int width = scanBitmap.getWidth(); int height = scanBitmap.getHeight(); int[] pixels = new int[width * height]; scanBitmap.getPixels(pixels, 0, width, 0, 0, width, height);// Get picture pixels RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap.getWidth(), scanBitmap.getHeight(), pixels); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); try { return reader.decode(bitmap1, hints); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } return null; } /** * Parse QR code (using the method of parsing RGB coded data) * * @param path * @return */ public static Result decodeBarcodeRGB(String path) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 1; Bitmap barcode = BitmapFactory.decodeFile(path, opts); Result result = decodeBarcodeRGB(barcode); barcode.recycle(); barcode = null; return result; } /** * Parse QR code (using the method of parsing RGB coded data) * * @param barcode * @return */ public static Result decodeBarcodeRGB(Bitmap barcode) { int width = barcode.getWidth(); int height = barcode.getHeight(); int[] data = new int[width * height]; barcode.getPixels(data, 0, width, 0, 0, width, height); RGBLuminanceSource source = new RGBLuminanceSource(width, height, data); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result result = null; try { result = reader.decode(bitmap1); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } barcode.recycle(); barcode = null; return result; } /** * Parse QR code (using the method of parsing YUV coded data) * * @param path * @return */ public static Result decodeBarcodeYUV(String path) { if (path == null || path.length() == 0) { return null; } BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 1; Bitmap barcode = BitmapFactory.decodeFile(path, opts); Result result = decodeBarcodeYUV(barcode); barcode.recycle(); barcode = null; return result; } /** * Parse QR code (using the method of parsing YUV coded data) * * @param barcode * @return */ public static Result decodeBarcodeYUV(Bitmap barcode) { if (null == barcode) { return null; } int width = barcode.getWidth(); int height = barcode.getHeight(); // Store the pixels of the picture in argb mode int[] argb = new int[width * height]; barcode.getPixels(argb, 0, width, 0, 0, width, height); // Convert argb to yuv byte[] yuv = new byte[width * height * 3 / 2]; encodeYUV420SP(yuv, argb, width, height); // Analyze the QR code of the YUV encoding method Result result = decodeBarcodeYUV(yuv, width, height); barcode.recycle(); barcode = null; return result; } /** * Parse QR code (using the method of parsing YUV coded data) * * @param yuv * @param width * @param height * @return */ private static Result decodeBarcodeYUV(byte[] yuv, int width, int height) { long start = System.currentTimeMillis(); MultiFormatReader multiFormatReader = new MultiFormatReader(); multiFormatReader.setHints(null); Result rawResult = null; PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(yuv, width, height, 0, 0, width, height, false); if (source != null) { BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { rawResult = multiFormatReader.decodeWithState(bitmap); } catch (ReaderException re) { re.printStackTrace(); } finally { multiFormatReader.reset(); multiFormatReader = null; } } long end = System.currentTimeMillis(); return rawResult; } /** * The formula for RGB to YUV is: Y=0.299R+0.587G+0.114B; * U=-0.147R-0.289G+0.436B; V=0.615R-0.515G-0.1B; * * @param yuv * @param argb * @param width * @param height */ private static void encodeYUV420SP(byte[] yuv, int[] argb, int width, int height) { // Pixel size of frame picture final int frameSize = width * height; // ---YUV data--- int Y, U, V; // Y index starts at 0 int yIndex = 0; // UV的index从frameSize开始 int uvIndex = frameSize; // ---Color data--- int R, G, B; int rgbIndex = 0; // ---Cycle all pixels, RGB to YUV--- for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { R = (argb[rgbIndex] & 0xff0000) >> 16; G = (argb[rgbIndex] & 0xff00) >> 8; B = (argb[rgbIndex] & 0xff); // rgbIndex++; // well known RGB to YUV algorithm Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16; U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128; V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128; Y = Math.max(0, Math.min(Y, 255)); U = Math.max(0, Math.min(U, 255)); V = Math.max(0, Math.min(V, 255)); // NV21 has a plane of Y and interleaved planes of VU each sampled by a factor // of 2 // meaning for every 4 Y pixels there are 1 V and 1 U. Note the sampling is // every other // pixel AND every other scan line. // ---Y--- yuv[yIndex++] = (byte) Y; // ---UV--- if ((j % 2 == 0) && (i % 2 == 0)) { // yuv[uvIndex++] = (byte) V; // yuv[uvIndex++] = (byte) U; } } } } }
/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.runtime.io.text.value; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.FieldPosition; import java.text.MessageFormat; import java.text.ParsePosition; import java.util.Optional; import com.asakusafw.runtime.io.text.TextUtil; import com.asakusafw.runtime.io.text.driver.FieldAdapter; import com.asakusafw.runtime.value.ValueOption; /** * An abstract implementation of {@link ValueOptionFieldAdapter} for numeric types. * @param <T> the property type * @since 0.9.1 */ public abstract class NumericOptionFieldAdapter<T extends ValueOption<T>> extends ValueOptionFieldAdapter<T> { private final DecimalFormat numberFormat; private final StringBuffer emitBuffer = new StringBuffer(); private final ParsePosition parsePosition = new ParsePosition(0); private final FieldPosition fieldPosition = new FieldPosition(0); NumericOptionFieldAdapter(String nullFormat, DecimalFormat numberFormat) { super(nullFormat); this.numberFormat = numberFormat; } @Override protected final void doParse(CharSequence contents, T property) { if (numberFormat == null) { doParseDefault(contents, property); } else { ParsePosition position = parsePosition; position.setIndex(0); position.setErrorIndex(-1); Number number = numberFormat.parse(contents.toString(), position); if (position.getIndex() == 0 || position.getIndex() != contents.length()) { throw new NumberFormatException(MessageFormat.format( "invalid number {0}", TextUtil.quote(contents))); } else if (number instanceof BigDecimal) { set((BigDecimal) number, property); } else { setSpecial(contents, number, property); } } } @Override protected final void doEmit(T property, StringBuilder output) { if (numberFormat == null) { doEmitDefault(property, output); } else { fieldPosition.setBeginIndex(0); fieldPosition.setEndIndex(0); emitBuffer.setLength(0); Number value = get(property); numberFormat.format(value, emitBuffer, fieldPosition); output.append(emitBuffer); } } /** * Parses the given non-null character sequence and set the parsed value into property. * @param contents the contents, never {@code null} * @param property the destination property * @throws IllegalArgumentException if the character sequence is malformed for this field */ protected abstract void doParseDefault(CharSequence contents, T property); /** * Emits the given non-null property value into the string builder. * @param property the property value, never {@code null} nor represents {@code null} * @param output the destination buffer */ protected abstract void doEmitDefault(T property, StringBuilder output); /** * Returns the property value. * @param property the property * @return the property value */ protected abstract Number get(T property); /** * Sets the given number into the property. * @param value the value * @param property the property */ protected abstract void set(BigDecimal value, T property); /** * Sets the given special number into the property. * @param contents the original contents * @param value the value * @param property the property */ protected void setSpecial(CharSequence contents, Number value, T property) { throw new NumberFormatException(MessageFormat.format( "invalid number {0}", TextUtil.quote(contents))); } /** * A basic implementation of builder for {@link NumericOptionFieldAdapter}. * @param <S> this builder type * @param <T> the build target type * @since 0.9.1 */ protected abstract static class NumericBuilderBase<S extends NumericBuilderBase<S, T>, T extends FieldAdapter<?>> extends BuilderBase<S, T> { private String numberFormat; private DecimalFormatSymbols decimalFormatSymbols; /** * Sets the decimal format. * @param newValue the format string * @return this */ public S withNumberFormat(String newValue) { this.numberFormat = newValue; return self(); } /** * Sets a decimal format symbols. * @param newValue the format symbols * @return this */ public S withDecimalFormatSymbols(DecimalFormatSymbols newValue) { this.decimalFormatSymbols = Optional.ofNullable(newValue) .map(v -> (DecimalFormatSymbols) v.clone()) .orElse(null); return self(); } /** * Returns the number format. * @return the number format */ protected DecimalFormat getDecimalFormat() { return Optional.ofNullable(numberFormat) .map(s -> { DecimalFormat f = new DecimalFormat(s, Optional.ofNullable(decimalFormatSymbols) .orElseGet(DecimalFormatSymbols::getInstance)); f.setParseBigDecimal(true); return f; }) .orElse(null); } } }
package dsk.anotex.importer; import dsk.anotex.core.AnnotatedDocument; /** * Interface for importing annotations for different documents. */ public interface AnnotationImporter { /** * Read annotations from given document file. * @param fileName Document file name. * @return Document annotations. */ public AnnotatedDocument readAnnotations(String fileName); }
/* * Copyright 2016 Jose Luis Cardenas - jluis.pcardenas@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 jcardenas.com.chess; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.squareup.picasso.Picasso; import jcardenas.com.chess.activities.BaseActivity; import jcardenas.com.chess.activities.ChannelsActivity; import jcardenas.com.chess.activities.GameActivity; import jcardenas.com.chess.activities.SignedInActivity; import jcardenas.com.chess.utils.Constants; import jcardenas.com.chess.utils.RoundedTransformation; import jcardenas.com.chess.utils.Score; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!checkAuth()) return; setContentView(R.layout.activity_main); FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseUser current = auth.getCurrentUser(); TextView txt = (TextView)findViewById(R.id.welcome); txt.setText(current.getDisplayName()); ImageView picture = (ImageView)findViewById(R.id.picture); if (current.getPhotoUrl() != null) Picasso.with(this).load(current.getPhotoUrl()).transform(new RoundedTransformation(30, 0)).into(picture); // firts time?, update score from db int score = Score.getScore(this); if (score == 0) { Score.retrieveDB(this, new Handler() { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); int score = bundle.getInt("score"); TextView level = (TextView)findViewById(R.id.level); level.setText(Score.getLevel(score)); } }); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void newGame(View v) { if (v.getId() == R.id.btn_online) { startActivity(createIntent(this, ChannelsActivity.class)); } else if (v.getId() == R.id.btn_phone) { Intent intent = new Intent(this, GameActivity.class); intent.putExtra(Constants.MODE, "phone"); startActivity(intent); } } @Override public void onStart() { super.onStart(); int score = Score.getScore(this); TextView level = (TextView)findViewById(R.id.level); level.setText(Score.getLevel(score)); } }
package ink.tomo.gulimall.product.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import ink.tomo.gulimall.product.entity.SpuImagesEntity; import ink.tomo.gulimall.product.service.SpuImagesService; import ink.tomo.common.utils.PageUtils; import ink.tomo.common.utils.R; /** * spu图片 * * @author tomo * @email tomotsune@foxmail.com * @date 2021-06-20 20:17:11 */ @RestController @RequestMapping("product/spuimages") public class SpuImagesController { @Autowired private SpuImagesService spuImagesService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("product:spuimages:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = spuImagesService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("product:spuimages:info") public R info(@PathVariable("id") Long id){ SpuImagesEntity spuImages = spuImagesService.getById(id); return R.ok().put("spuImages", spuImages); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("product:spuimages:save") public R save(@RequestBody SpuImagesEntity spuImages){ spuImagesService.save(spuImages); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("product:spuimages:update") public R update(@RequestBody SpuImagesEntity spuImages){ spuImagesService.updateById(spuImages); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("product:spuimages:delete") public R delete(@RequestBody Long[] ids){ spuImagesService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package org.prevayler.socketserver.server; /* * prevayler.socketServer, a socket-based server (and client library) * to help create client-server Prevayler applications * * Copyright (C) 2003 Advanced Systems Concepts, Inc. * * Written by David Orme <daveo@swtworkbench.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import org.prevayler.Prevayler; import org.prevayler.TransactionWithQuery; import org.prevayler.socketserver.transactions.*; import org.prevayler.socketserver.transactions.IRemoteTransaction; import org.prevayler.socketserver.transactions.ThrownException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.Socket; /** * Forwards commands to Prevayler from a single client for its entire session. * * @author DaveO */ public class CommandThread extends Thread { private Prevayler prevayler; private Socket socket; private long myId; /** * Server socket thread constructor */ public CommandThread(Prevayler p, Socket s) { prevayler = p; socket = s; myId = Reaper.registerCommandThread(); } /* * Request handling loop */ private void handleRequests() throws Exception { boolean done = false; ObjectOutputStream o = null; ObjectInputStream i = null; // First send the connection ID back to the client o = new ObjectOutputStream(socket.getOutputStream()); o.writeObject(new Long(myId)); // Now read commands in a loop until the client is done. while (!done) { i = new ObjectInputStream(socket.getInputStream()); Object t = i.readObject(); if (t instanceof Disconnect) { socket.close(); done = true; Reaper.reap(new Long(myId)); } else if (t instanceof RegisterCallback) { Notification.registerCallback(myId, ((RegisterCallback) t).message); } else if (t instanceof UnregisterCallback) { Notification.unregisterCallback(myId, ((UnregisterCallback) t).message); } else { ((IRemoteTransaction) t).setSenderID(new Long(myId)); Serializable result; TransactionWithQuery transaction = (TransactionWithQuery) t; try { result = (Serializable) prevayler.execute(transaction); } catch (Exception e) { result = new ThrownException(e); } o = new ObjectOutputStream(socket.getOutputStream()); o.writeObject(result); } } } /* * Start a request handling loop and log exceptions */ public void run() { try { handleRequests(); } catch (Exception e) { Reaper.reap(new Long(myId)); try { socket.close(); } catch (Exception e2) { } e.printStackTrace(); } } }
package neqsim.util.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * <p> * NeqSimExperimentDatabase class. * </p> * * @author Even Solbraa * @version Dec 2018 */ public class NeqSimExperimentDatabase implements neqsim.util.util.FileSystemSettings, java.io.Serializable { /** * <p> * createTemporaryTables. * </p> * * @return the createTemporaryTables */ public boolean createTemporaryTables() { return createTemporaryTables; } /** * <p> * Setter for the field <code>createTemporaryTables</code>. * </p> * * @param createTemporaryTables the createTemporaryTables to set */ public void setCreateTemporaryTables(boolean createTemporaryTables) { NeqSimExperimentDatabase.createTemporaryTables = createTemporaryTables; } private static final long serialVersionUID = 1000; /** Constant <code>dataBasePath=""</code> */ public static String dataBasePath = ""; /** Constant <code>username=""</code> */ /** Constant <code>password=""</code> */ /** Constant <code>password=""</code> */ /** Constant <code>password=""</code> */ /** Constant <code>password=""</code> */ /** Constant <code>password=""</code> */ /** Constant <code>password=""</code> */ public static String username = "", password = ""; static Logger logger = LogManager.getLogger(NeqSimExperimentDatabase.class); private static boolean createTemporaryTables = false; private static String dataBaseType = "MSAccessUCanAccess"; /** Constant <code>connectionString="jdbc:ucanaccess://C:/Users/esol/OneDriv"{trunked}</code> */ public static String connectionString = "jdbc:ucanaccess://C:/Users/esol/OneDrive - Equinor/programming/neqsimdatabase/MSAccess/NeqSimExperimentalData.mdb;memory=true"; private Statement statement = null; protected Connection databaseConnection = null; /** * <p> * Constructor for NeqSimExperimentDatabase. * </p> */ public NeqSimExperimentDatabase() { setDataBaseType(dataBaseType); try { databaseConnection = this.openConnection(); statement = databaseConnection.createStatement(); } catch (Exception ex) { logger.error("SQLException " + ex.getMessage()); throw new RuntimeException(ex); } } /** * <p> * openConnection. * </p> * * @return a Connection object * @throws java.sql.SQLException if any. * @throws java.lang.ClassNotFoundException if any. */ public Connection openConnection() throws SQLException, ClassNotFoundException { javax.naming.InitialContext ctx = null; javax.sql.DataSource ds = null; try { if (dataBaseType.equals("MSAccessUCanAccess")) { return DriverManager.getConnection(getConnectionString()); } else if (dataBaseType.equals("mySQL") || dataBaseType.equals("mySQLNTNU") || dataBaseType.equals("Derby")) { return DriverManager.getConnection(getConnectionString(), username, password); } else if (dataBaseType.equals("mySQLNeqSimWeb")) { ctx = new javax.naming.InitialContext(); ds = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/NeqsimDataSource"); if (ctx != null) { ctx.close(); } return ds.getConnection(); } else { return DriverManager.getConnection(getConnectionString(), username, password); } } catch (Exception ex) { logger.error("error loading NeqSimDataBase... " + ex.toString()); throw new RuntimeException(ex); } finally { try { if (ctx != null) { ctx.close(); } } catch (Exception e) { logger.error("error", e); } } } /** * <p> * getConnection. * </p> * * @return a Connection object */ public Connection getConnection() { return databaseConnection; } /** * <p> * getResultSet. * </p> * * @param sqlString a {@link java.lang.String} object * @return a ResultSet object */ public ResultSet getResultSet(String sqlString) { try { ResultSet result = getStatement().executeQuery(sqlString); return result; } catch (Exception e) { logger.error("error loading NeqSimbataBase " + e.toString()); throw new RuntimeException(e); } } /** * <p> * execute. * </p> * * @param sqlString a {@link java.lang.String} object */ public void execute(String sqlString) { try { if (databaseConnection == null) { databaseConnection = this.openConnection(); setStatement(databaseConnection.createStatement()); } getStatement().execute(sqlString); } catch (Exception e) { logger.error("error in NeqSimDataBase " + e.toString(), e); logger.error("The database must be rgistered on the local DBMS to work."); throw new RuntimeException(e); } } /** * <p> * Getter for the field <code>dataBaseType</code>. * </p> * * @return a {@link java.lang.String} object */ public static String getDataBaseType() { return dataBaseType; } /** * <p> * Setter for the field <code>dataBaseType</code>. * </p> * * @param aDataBaseType a {@link java.lang.String} object */ public static void setDataBaseType(String aDataBaseType) { setDataBaseType(aDataBaseType, null); } /** * <p> * Setter for the field <code>dataBaseType</code>. * </p> * * @param aDataBaseType a {@link java.lang.String} object * @param connectionString a {@link java.lang.String} object */ public static void setDataBaseType(String aDataBaseType, String connectionString) { dataBaseType = aDataBaseType; if (connectionString != null) { NeqSimExperimentDatabase.connectionString = connectionString; } try { if (dataBaseType.equals("MSAccess")) { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").getDeclaredConstructor() .newInstance(); } else if (dataBaseType.equals("H2")) { Class.forName("org.h2.Driver"); } else if (dataBaseType.equals("H2RT")) { Class.forName("org.h2.Driver"); } else if (dataBaseType.equals("MSAccessUCanAccess")) { Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); } else if (dataBaseType.equals("mySQL")) { Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); } else if (dataBaseType.equals("mySQLNTNU")) { Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); } else if (dataBaseType.equals("Derby")) { Class.forName("org.apache.derby.jdbc.EmbeddedDriver").getDeclaredConstructor() .newInstance(); } else if (dataBaseType.equals("oracle")) { Class.forName("oracle.jdbc.driver.OracleDriver").getDeclaredConstructor() .newInstance(); } else if (dataBaseType.equals("oracleST")) { Class.forName("oracle.jdbc.driver.OracleDriver").getDeclaredConstructor() .newInstance(); } else { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } } catch (Exception ex) { logger.error("error loading database driver.. " + ex.toString()); throw new RuntimeException(ex); } } /** * <p> * Getter for the field <code>statement</code>. * </p> * * @return a Statement object */ public Statement getStatement() { return statement; } /** * <p> * Setter for the field <code>statement</code>. * </p> * * @param statement a Statement object */ public void setStatement(Statement statement) { this.statement = statement; } /** * <p> * Setter for the field <code>username</code>. * </p> * * @param aUsername the username to set */ public static void setUsername(String aUsername) { username = aUsername; } /** * <p> * Setter for the field <code>password</code>. * </p> * * @param aPassword the password to set */ public static void setPassword(String aPassword) { password = aPassword; } /** * <p> * Getter for the field <code>connectionString</code>. * </p> * * @return the connectionString */ public static String getConnectionString() { return connectionString; } /** * <p> * Setter for the field <code>connectionString</code>. * </p> * * @param aConnectionString the connectionString to set */ public static void setConnectionString(String aConnectionString) { connectionString = aConnectionString; } }