code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
package org.gradle.test.performance.mediummonolithicjavaproject.p428; import org.junit.Test; import static org.junit.Assert.*; public class Test8570 { Production8570 objectUnderTest = new Production8570(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p428/Test8570.java
Java
apache-2.0
2,111
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.distributed.DistributedSystemDisconnectedException; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.InternalCacheForClientAccess; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.management.ManagementService; /** * Super class to all Management Service * * @since GemFire 7.0 */ public abstract class BaseManagementService extends ManagementService { private static final Logger logger = LogService.getLogger(); /** * The main mapping between different resources and Service instance Object can be Cache */ @MakeNotStatic protected static final Map<Object, BaseManagementService> instances = new HashMap<Object, BaseManagementService>(); /** List of connected <code>DistributedSystem</code>s */ @MakeNotStatic private static final List<InternalDistributedSystem> systems = new ArrayList<InternalDistributedSystem>(1); /** Protected constructor. */ protected BaseManagementService() {} // Static block to initialize the ConnectListener on the System static { initInternalDistributedSystem(); } /** * This method will close the service. Any operation on the service instance will throw exception */ protected abstract void close(); /** * This method will close the service. Any operation on the service instance will throw exception */ protected abstract boolean isClosed(); /** * Returns a ManagementService to use for the specified Cache. * * @param cache defines the scope of resources to be managed */ public static ManagementService getManagementService(InternalCacheForClientAccess cache) { synchronized (instances) { BaseManagementService service = instances.get(cache); if (service == null) { service = SystemManagementService.newSystemManagementService(cache); instances.put(cache, service); } return service; } } public static ManagementService getExistingManagementService(InternalCache cache) { synchronized (instances) { BaseManagementService service = instances.get(cache.getCacheForProcessingClientRequests()); return service; } } /** * Initialises the distributed system listener */ private static void initInternalDistributedSystem() { synchronized (instances) { // Initialize our own list of distributed systems via a connect listener @SuppressWarnings("unchecked") List<InternalDistributedSystem> existingSystems = InternalDistributedSystem .addConnectListener(new InternalDistributedSystem.ConnectListener() { @Override public void onConnect(InternalDistributedSystem sys) { addInternalDistributedSystem(sys); } }); // While still holding the lock on systems, add all currently known // systems to our own list for (InternalDistributedSystem sys : existingSystems) { try { if (sys.isConnected()) { addInternalDistributedSystem(sys); } } catch (DistributedSystemDisconnectedException e) { if (logger.isDebugEnabled()) { logger.debug("DistributedSystemDisconnectedException {}", e.getMessage(), e); } } } } } /** * Add an Distributed System and adds a Discon Listener */ private static void addInternalDistributedSystem(InternalDistributedSystem sys) { synchronized (instances) { sys.addDisconnectListener(new InternalDistributedSystem.DisconnectListener() { @Override public String toString() { return "Disconnect listener for BaseManagementService"; } @Override public void onDisconnect(InternalDistributedSystem ss) { removeInternalDistributedSystem(ss); } }); systems.add(sys); } } /** * Remove a Distributed System from the system lists. If list is empty it closes down all the * services if not closed */ private static void removeInternalDistributedSystem(InternalDistributedSystem sys) { synchronized (instances) { systems.remove(sys); if (systems.isEmpty()) { for (Object key : instances.keySet()) { BaseManagementService service = (BaseManagementService) instances.get(key); try { if (!service.isClosed()) { // Service close method should take care of the cleaning up // activities service.close(); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("ManagementException while removing InternalDistributedSystem {}", e.getMessage(), e); } } } instances.clear(); } } } }
davebarnes97/geode
geode-core/src/main/java/org/apache/geode/management/internal/BaseManagementService.java
Java
apache-2.0
5,962
/* * Copyright 1999-2020 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.adapter.okhttp.extractor; import okhttp3.Connection; import okhttp3.Request; /** * @author zhaoyuguang */ public class DefaultOkHttpResourceExtractor implements OkHttpResourceExtractor { @Override public String extract(Request request, Connection connection) { return request.method() + ":" + request.url().toString(); } }
alibaba/Sentinel
sentinel-adapter/sentinel-okhttp-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/okhttp/extractor/DefaultOkHttpResourceExtractor.java
Java
apache-2.0
997
package com.melvin.share.ui.activity; import android.content.Context; import android.databinding.DataBindingUtil; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.jcodecraeer.xrecyclerview.ProgressStyle; import com.melvin.share.R; import com.melvin.share.Utils.ShapreUtils; import com.melvin.share.Utils.Utils; import com.melvin.share.databinding.ActivityOrderEvaluateBinding; import com.melvin.share.model.Evaluation; import com.melvin.share.model.WaitPayOrderInfo; import com.melvin.share.model.list.CommonList; import com.melvin.share.model.serverReturn.CommonReturnModel; import com.melvin.share.modelview.acti.OrderEvaluateViewModel; import com.melvin.share.network.GlobalUrl; import com.melvin.share.rx.RxActivityHelper; import com.melvin.share.rx.RxFragmentHelper; import com.melvin.share.rx.RxModelSubscribe; import com.melvin.share.rx.RxSubscribe; import com.melvin.share.ui.activity.common.BaseActivity; import com.melvin.share.ui.activity.shopcar.ShoppingCarActivity; import com.melvin.share.ui.fragment.productinfo.ProductEvaluateFragment; import com.melvin.share.view.MyRecyclerView; import com.melvin.share.view.RatingBar; import java.util.HashMap; import java.util.Map; import static com.melvin.share.R.id.map; import static com.melvin.share.R.id.ratingbar; /** * Author: Melvin * <p/> * Data: 2017/4/8 * <p/> * 描述: 订单评价页面 */ public class OderEvaluateActivity extends BaseActivity { private ActivityOrderEvaluateBinding binding; private Context mContext = null; private int starCount; private WaitPayOrderInfo.OrderBean.OrderItemResponsesBean orderItemResponsesBean; @Override protected void initView() { binding = DataBindingUtil.setContentView(this, R.layout.activity_order_evaluate); mContext = this; initWindow(); initToolbar(binding.toolbar); ininData(); } private void ininData() { binding.ratingbar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() { @Override public void onRatingChange(int var1) { starCount = var1; } }); orderItemResponsesBean = getIntent().getParcelableExtra("orderItemResponsesBean"); if (orderItemResponsesBean != null) { String[] split = orderItemResponsesBean.mainPicture.split("\\|"); if (split != null && split.length >= 1) { String url = GlobalUrl.SERVICE_URL + split[0]; Glide.with(mContext) .load(url) .placeholder(R.mipmap.logo) .centerCrop() .into(binding.image); } binding.name.setText(orderItemResponsesBean.productName); } } public void submit(View view) { String contents = binding.content.getText().toString(); if (TextUtils.isEmpty(contents)) { Utils.showToast(mContext, "请评价"); } if (starCount == 0) { Utils.showToast(mContext, "请评分"); } Map map = new HashMap(); map.put("orderItemId", orderItemResponsesBean.id); map.put("startlevel", starCount); map.put("picture", orderItemResponsesBean.mainPicture); map.put("content", contents); ShapreUtils.putParamCustomerId(map); JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = (JsonObject) jsonParser.parse((new Gson().toJson(map))); fromNetwork.insertOderItemEvaluation(jsonObject) .compose(new RxActivityHelper<CommonReturnModel>().ioMain(OderEvaluateActivity.this, true)) .subscribe(new RxSubscribe<CommonReturnModel>(mContext, true) { @Override protected void myNext(CommonReturnModel commonReturnModel) { Utils.showToast(mContext, commonReturnModel.message); finish(); } @Override protected void myError(String message) { Utils.showToast(mContext, message); } }); } }
MelvinWang/NewShare
NewShare/app/src/main/java/com/melvin/share/ui/activity/OderEvaluateActivity.java
Java
apache-2.0
4,380
package clockworktest.water; import com.clockwork.app.SimpleApplication; import com.clockwork.audio.AudioNode; import com.clockwork.audio.LowPassFilter; import com.clockwork.effect.ParticleEmitter; import com.clockwork.effect.ParticleMesh; import com.clockwork.input.KeyInput; import com.clockwork.input.controls.ActionListener; import com.clockwork.input.controls.KeyTrigger; import com.clockwork.light.DirectionalLight; import com.clockwork.material.Material; import com.clockwork.material.RenderState.BlendMode; import com.clockwork.math.ColorRGBA; import com.clockwork.math.FastMath; import com.clockwork.math.Quaternion; import com.clockwork.math.Vector3f; import com.clockwork.post.FilterPostProcessor; import com.clockwork.post.filters.BloomFilter; import com.clockwork.post.filters.DepthOfFieldFilter; import com.clockwork.post.filters.LightScatteringFilter; import com.clockwork.renderer.Camera; import com.clockwork.renderer.queue.RenderQueue.Bucket; import com.clockwork.renderer.queue.RenderQueue.ShadowMode; import com.clockwork.scene.Geometry; import com.clockwork.scene.Node; import com.clockwork.scene.Spatial; import com.clockwork.scene.shape.Box; import com.clockwork.terrain.geomipmap.TerrainQuad; import com.clockwork.terrain.heightmap.AbstractHeightMap; import com.clockwork.terrain.heightmap.ImageBasedHeightMap; import com.clockwork.texture.Texture; import com.clockwork.texture.Texture.WrapMode; import com.clockwork.texture.Texture2D; import com.clockwork.util.SkyFactory; import com.clockwork.water.WaterFilter; import java.util.ArrayList; import java.util.List; /** * test * */ public class TestPostWater extends SimpleApplication { private Vector3f lightDir = new Vector3f(-4.9236743f, -1.27054665f, 5.896916f); private WaterFilter water; TerrainQuad terrain; Material matRock; AudioNode waves; LowPassFilter underWaterAudioFilter = new LowPassFilter(0.5f, 0.1f); LowPassFilter underWaterReverbFilter = new LowPassFilter(0.5f, 0.1f); LowPassFilter aboveWaterAudioFilter = new LowPassFilter(1, 1); public static void main(String[] args) { TestPostWater app = new TestPostWater(); app.start(); } @Override public void simpleInitApp() { setDisplayFps(false); setDisplayStatView(false); Node mainScene = new Node("Main Scene"); rootNode.attachChild(mainScene); createTerrain(mainScene); DirectionalLight sun = new DirectionalLight(); sun.setDirection(lightDir); sun.setColor(ColorRGBA.White.clone().multLocal(1.7f)); mainScene.addLight(sun); DirectionalLight l = new DirectionalLight(); l.setDirection(Vector3f.UNIT_Y.mult(-1)); l.setColor(ColorRGBA.White.clone().multLocal(0.3f)); // mainScene.addLight(l); flyCam.setMoveSpeed(50); //cam.setLocation(new Vector3f(-700, 100, 300)); //cam.setRotation(new Quaternion().fromAngleAxis(0.5f, Vector3f.UNIT_Z)); cam.setLocation(new Vector3f(-327.21957f, 61.6459f, 126.884346f)); cam.setRotation(new Quaternion(0.052168474f, 0.9443102f, -0.18395276f, 0.2678024f)); cam.setRotation(new Quaternion().fromAngles(new float[]{FastMath.PI * 0.06f, FastMath.PI * 0.65f, 0})); Spatial sky = SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false); sky.setLocalScale(350); mainScene.attachChild(sky); cam.setFrustumFar(4000); //cam.setFrustumNear(100); //private FilterPostProcessor fpp; water = new WaterFilter(rootNode, lightDir); FilterPostProcessor fpp = new FilterPostProcessor(assetManager); fpp.addFilter(water); BloomFilter bloom = new BloomFilter(); //bloom.getE bloom.setExposurePower(55); bloom.setBloomIntensity(1.0f); fpp.addFilter(bloom); LightScatteringFilter lsf = new LightScatteringFilter(lightDir.mult(-300)); lsf.setLightDensity(1.0f); fpp.addFilter(lsf); DepthOfFieldFilter dof = new DepthOfFieldFilter(); dof.setFocusDistance(0); dof.setFocusRange(100); fpp.addFilter(dof); // // fpp.addFilter(new TranslucentBucketFilter()); // // fpp.setNumSamples(4); water.setWaveScale(0.003f); water.setMaxAmplitude(2f); water.setFoamExistence(new Vector3f(1f, 4, 0.5f)); water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg")); //water.setNormalScale(0.5f); //water.setRefractionConstant(0.25f); water.setRefractionStrength(0.2f); //water.setFoamHardness(0.6f); water.setWaterHeight(initialWaterHeight); uw = cam.getLocation().y < waterHeight; waves = new AudioNode(assetManager, "Sound/Environment/Ocean Waves.ogg", false); waves.setLooping(true); waves.setReverbEnabled(true); if (uw) { waves.setDryFilter(new LowPassFilter(0.5f, 0.1f)); } else { waves.setDryFilter(aboveWaterAudioFilter); } audioRenderer.playSource(waves); // viewPort.addProcessor(fpp); inputManager.addListener(new ActionListener() { public void onAction(String name, boolean isPressed, float tpf) { if (isPressed) { if (name.equals("foam1")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg")); } if (name.equals("foam2")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam2.jpg")); } if (name.equals("foam3")) { water.setFoamTexture((Texture2D) assetManager.loadTexture("Common/MatDefs/Water/Textures/foam3.jpg")); } if (name.equals("upRM")) { water.setReflectionMapSize(Math.min(water.getReflectionMapSize() * 2, 4096)); System.out.println("Reflection map size : " + water.getReflectionMapSize()); } if (name.equals("downRM")) { water.setReflectionMapSize(Math.max(water.getReflectionMapSize() / 2, 32)); System.out.println("Reflection map size : " + water.getReflectionMapSize()); } } } }, "foam1", "foam2", "foam3", "upRM", "downRM"); inputManager.addMapping("foam1", new KeyTrigger(KeyInput.KEY_1)); inputManager.addMapping("foam2", new KeyTrigger(KeyInput.KEY_2)); inputManager.addMapping("foam3", new KeyTrigger(KeyInput.KEY_3)); inputManager.addMapping("upRM", new KeyTrigger(KeyInput.KEY_PGUP)); inputManager.addMapping("downRM", new KeyTrigger(KeyInput.KEY_PGDN)); // createBox(); // createFire(); } Geometry box; private void createBox() { //creating a transluscent box box = new Geometry("box", new Box(new Vector3f(0, 0, 0), 50, 50, 50)); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(1.0f, 0, 0, 0.3f)); mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); //mat.getAdditionalRenderState().setDepthWrite(false); //mat.getAdditionalRenderState().setDepthTest(false); box.setMaterial(mat); box.setQueueBucket(Bucket.Translucent); //creating a post view port // ViewPort post=renderManager.createPostView("transpPost", cam); // post.setClearFlags(false, true, true); box.setLocalTranslation(-600, 0, 300); //attaching the box to the post viewport //Don't forget to updateGeometricState() the box in the simpleUpdate // post.attachScene(box); rootNode.attachChild(box); } private void createFire() { /** * Uses Texture from CW-test-data library! */ ParticleEmitter fire = new ParticleEmitter("Emitter", ParticleMesh.Type.Triangle, 30); Material mat_red = new Material(assetManager, "Common/MatDefs/Misc/Particle.j3md"); mat_red.setTexture("Texture", assetManager.loadTexture("Effects/Explosion/flame.png")); fire.setMaterial(mat_red); fire.setImagesX(2); fire.setImagesY(2); // 2x2 texture animation fire.setEndColor(new ColorRGBA(1f, 0f, 0f, 1f)); // red fire.setStartColor(new ColorRGBA(1f, 1f, 0f, 0.5f)); // yellow fire.getParticleInfluencer().setInitialVelocity(new Vector3f(0, 2, 0)); fire.setStartSize(10f); fire.setEndSize(1f); fire.setGravity(0, 0, 0); fire.setLowLife(0.5f); fire.setHighLife(1.5f); fire.getParticleInfluencer().setVelocityVariation(0.3f); fire.setLocalTranslation(-350, 40, 430); fire.setQueueBucket(Bucket.Transparent); rootNode.attachChild(fire); } private void createTerrain(Node rootNode) { matRock = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matRock.setBoolean("useTriPlanarMapping", false); matRock.setBoolean("WardIso", true); matRock.setTexture("AlphaMap", assetManager.loadTexture("Textures/Terrain/splat/alphamap.png")); Texture heightMapImage = assetManager.loadTexture("Textures/Terrain/splat/mountains512.png"); Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap", grass); matRock.setFloat("DiffuseMap_0_scale", 64); Texture dirt = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg"); dirt.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_1", dirt); matRock.setFloat("DiffuseMap_1_scale", 16); Texture rock = assetManager.loadTexture("Textures/Terrain/splat/road.jpg"); rock.setWrap(WrapMode.Repeat); matRock.setTexture("DiffuseMap_2", rock); matRock.setFloat("DiffuseMap_2_scale", 128); Texture normalMap0 = assetManager.loadTexture("Textures/Terrain/splat/grass_normal.jpg"); normalMap0.setWrap(WrapMode.Repeat); Texture normalMap1 = assetManager.loadTexture("Textures/Terrain/splat/dirt_normal.png"); normalMap1.setWrap(WrapMode.Repeat); Texture normalMap2 = assetManager.loadTexture("Textures/Terrain/splat/road_normal.png"); normalMap2.setWrap(WrapMode.Repeat); matRock.setTexture("NormalMap", normalMap0); matRock.setTexture("NormalMap_1", normalMap2); matRock.setTexture("NormalMap_2", normalMap2); AbstractHeightMap heightmap = null; try { heightmap = new ImageBasedHeightMap(heightMapImage.getImage(), 0.25f); heightmap.load(); } catch (Exception e) { e.printStackTrace(); } terrain = new TerrainQuad("terrain", 65, 513, heightmap.getHeightMap()); List<Camera> cameras = new ArrayList<Camera>(); cameras.add(getCamera()); terrain.setMaterial(matRock); terrain.setLocalScale(new Vector3f(5, 5, 5)); terrain.setLocalTranslation(new Vector3f(0, -30, 0)); terrain.setLocked(false); // unlock it so we can edit the height terrain.setShadowMode(ShadowMode.Receive); rootNode.attachChild(terrain); } //This part is to emulate tides, slightly varrying the height of the water plane private float time = 0.0f; private float waterHeight = 0.0f; private float initialWaterHeight = 90f;//0.8f; private boolean uw = false; @Override public void simpleUpdate(float tpf) { super.simpleUpdate(tpf); // box.updateGeometricState(); time += tpf; waterHeight = (float) Math.cos(((time * 0.6f) % FastMath.TWO_PI)) * 1.5f; water.setWaterHeight(initialWaterHeight + waterHeight); if (water.isUnderWater() && !uw) { waves.setDryFilter(new LowPassFilter(0.5f, 0.1f)); uw = true; } if (!water.isUnderWater() && uw) { uw = false; //waves.setReverbEnabled(false); waves.setDryFilter(new LowPassFilter(1, 1f)); //waves.setDryFilter(new LowPassFilter(1,1f)); } } }
PlanetWaves/clockworkengine
branches/3.0/engine/src/test/clockworktest/water/TestPostWater.java
Java
apache-2.0
12,539
/******************************************************************************* * Copyright 2002-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 com.github.lothar.security.acl.elasticsearch.repository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject; @Repository public interface UnknownStrategyRepository extends ElasticsearchRepository<UnknownStrategyObject, Long> { }
lordlothar99/strategy-spring-security-acl
elasticsearch/src/test/java/com/github/lothar/security/acl/elasticsearch/repository/UnknownStrategyRepository.java
Java
apache-2.0
1,173
package javassist.build; /** * A generic build exception when applying a transformer. * Wraps the real cause of the (probably javassist) root exception. * @author SNI */ @SuppressWarnings("serial") public class JavassistBuildException extends Exception { public JavassistBuildException() { super(); } public JavassistBuildException(String message, Throwable throwable) { super(message, throwable); } public JavassistBuildException(String message) { super(message); } public JavassistBuildException(Throwable throwable) { super(throwable); } }
stephanenicolas/javassist-build-plugin-api
src/main/java/javassist/build/JavassistBuildException.java
Java
apache-2.0
569
package com.hcentive.webservice.soap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import com.hcentive.service.FormResponse; import com.hcentive.webservice.exception.HcentiveSOAPException; import org.apache.log4j.Logger; /** * @author Mebin.Jacob *Endpoint class. */ @Endpoint public final class FormEndpoint { private static final String NAMESPACE_URI = "http://hcentive.com/service"; Logger logger = Logger.getLogger(FormEndpoint.class); @Autowired FormRepository formRepo; @PayloadRoot(namespace = NAMESPACE_URI, localPart = "FormResponse") @ResponsePayload public FormResponse submitForm(@RequestPayload FormResponse request) throws HcentiveSOAPException { // GetCountryResponse response = new GetCountryResponse(); // response.setCountry(countryRepository.findCountry(request.getName())); FormResponse response = null; logger.debug("AAGAYA"); try{ response = new FormResponse(); response.setForm1(formRepo.findForm("1")); //make API call }catch(Exception exception){ throw new HcentiveSOAPException("Something went wrong!!! The exception is --- " + exception); } return response; // return null; } }
mebinjacob/spring-boot-soap
src/main/java/com/hcentive/webservice/soap/FormEndpoint.java
Java
apache-2.0
1,458
/* * Copyright 2015 Luca Capra <luca.capra@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.createnet.compose.data; /** * * @author Luca Capra <luca.capra@gmail.com> */ public class GeoPointRecord extends Record<String> { public Point point; protected String value; public GeoPointRecord() {} public GeoPointRecord(String point) { this.point = new Point(point); } public GeoPointRecord(double latitude, double longitude) { this.point = new Point(latitude, longitude); } @Override public String getValue() { return point.toString(); } @Override public void setValue(Object value) { this.value = parseValue(value); this.point = new Point(this.value); } @Override public String parseValue(Object raw) { return (String)raw; } @Override public String getType() { return "geo_point"; } public class Point { public double latitude; public double longitude; public Point(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } public Point(String val) { String[] coords = val.split(","); longitude = Double.parseDouble(coords[0].trim()); latitude = Double.parseDouble(coords[1].trim()); } @Override public String toString() { return this.longitude + "," + this.latitude; } } }
muka/compose-java-client
src/main/java/org/createnet/compose/data/GeoPointRecord.java
Java
apache-2.0
2,062
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.ide.intellij; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.xml.XmlDomParser; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.w3c.dom.Node; public class ProjectIntegrationTest { @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths(); @Before public void setUp() throws Exception { // These tests consistently fail on Windows due to path separator issues. Assume.assumeFalse(Platform.detect() == Platform.WINDOWS); } @Test public void testAndroidLibraryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_library"); } @Test public void testAndroidBinaryProject() throws InterruptedException, IOException { runBuckProjectAndVerify("android_binary"); } @Test public void testVersion2BuckProject() throws InterruptedException, IOException { runBuckProjectAndVerify("project1"); } @Test public void testVersion2BuckProjectWithoutAutogeneratingSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_autogeneration"); } @Test public void testVersion2BuckProjectSlice() throws InterruptedException, IOException { runBuckProjectAndVerify("project_slice", "--without-tests", "modules/dep1:dep1"); } @Test public void testVersion2BuckProjectSourceMerging() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation"); } @Test public void testBuckProjectWithCustomAndroidSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_android_sdks"); } @Test public void testBuckProjectWithCustomJavaSdks() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_custom_java_sdks"); } @Test public void testBuckProjectWithIntellijSdk() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_intellij_sdk"); } @Test public void testVersion2BuckProjectWithProjectSettings() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_project_settings"); } @Test public void testVersion2BuckProjectWithScripts() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_scripts", "//modules/dep1:dep1"); } @Test public void testVersion2BuckProjectWithUnusedLibraries() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "project_with_unused_libraries", temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand("project"); result.assertSuccess("buck project should exit cleanly"); assertFalse(workspace.resolve(".idea/libraries/library_libs_jsr305.xml").toFile().exists()); } @Test public void testVersion2BuckProjectWithExcludedResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_excluded_resources"); } @Test public void testVersion2BuckProjectWithAssets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_assets"); } @Test public void testVersion2BuckProjectWithLanguageLevel() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_language_level"); } @Test public void testVersion2BuckProjectWithOutputUrl() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_output_url"); } @Test public void testVersion2BuckProjectWithJavaResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_java_resources"); } public void testVersion2BuckProjectWithExtraOutputModules() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_extra_output_modules"); } @Test public void testVersion2BuckProjectWithGeneratedSources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_generated_sources"); } @Test public void testBuckProjectWithSubdirGlobResources() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_subdir_glob_resources"); } @Test public void testRobolectricTestRule() throws InterruptedException, IOException { runBuckProjectAndVerify("robolectric_test"); } @Test public void testAndroidResourcesInDependencies() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_android_resources"); } @Test public void testPrebuiltJarWithJavadoc() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_prebuilt_jar"); } @Test public void testZipFile() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_zipfile"); } @Test public void testAndroidResourcesAndLibraryInTheSameFolder() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resources_in_the_same_folder"); } @Test public void testAndroidResourcesWithPackagesAtTheSameLocation() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_resources_with_package_names"); } @Test public void testCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_cxx_library"); } @Test public void testAggregatingCxxLibrary() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_cxx_library"); } @Test public void testSavingGeneratedFilesList() throws InterruptedException, IOException { runBuckProjectAndVerify( "save_generated_files_list", "--file-with-list-of-generated-files", ".idea/generated-files.txt"); } @Test public void testMultipleLibraries() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_multiple_libraries"); } @Test public void testProjectWithIgnoredTargets() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_ignored_targets"); } @Test public void testProjectWithCustomPackages() throws InterruptedException, IOException { runBuckProjectAndVerify("aggregation_with_custom_packages"); } @Test public void testAndroidResourceAggregation() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation"); } @Test public void testAndroidResourceAggregationWithLimit() throws InterruptedException, IOException { runBuckProjectAndVerify("android_resource_aggregation_with_limit"); } @Test public void testProjectIncludesTestsByDefault() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_tests_by_default", "//modules/lib:lib"); } @Test public void testProjectExcludesTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify("project_without_tests", "--without-tests", "//modules/lib:lib"); } @Test public void testProjectExcludesDepTestsWhenRequested() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_without_dep_tests", "--without-dependencies-tests", "//modules/lib:lib"); } @Test public void testUpdatingExistingWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_existing_workspace"); } @Test public void testCreateNewWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("create_new_workspace"); } @Test public void testUpdateMalformedWorkspace() throws InterruptedException, IOException { runBuckProjectAndVerify("update_malformed_workspace"); } @Test public void testUpdateWorkspaceWithoutIgnoredNodes() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_ignored_nodes"); } @Test public void testUpdateWorkspaceWithoutManagerNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_manager_node"); } @Test public void testUpdateWorkspaceWithoutProjectNode() throws InterruptedException, IOException { runBuckProjectAndVerify("update_workspace_without_project_node"); } @Test public void testProjectWthPackageBoundaryException() throws InterruptedException, IOException { runBuckProjectAndVerify("project_with_package_boundary_exception", "//project2:lib"); } @Test public void testProjectWithProjectRoot() throws InterruptedException, IOException { runBuckProjectAndVerify( "project_with_project_root", "--intellij-project-root", "project1", "--intellij-include-transitive-dependencies", "--intellij-module-group-name", "", "//project1/lib:lib"); } @Test public void testGeneratingAndroidManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("generate_android_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkWithDifferentVersionsFromManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_different_from_manifests"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBinaryManifest() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_binary_manifest"); } @Test public void testGeneratingAndroidManifestWithMinSdkFromBuckConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_from_buck_config"); } @Test public void testGeneratingAndroidManifestWithNoMinSdkConfig() throws InterruptedException, IOException { runBuckProjectAndVerify("min_sdk_version_with_no_config"); } @Test public void testPreprocessScript() throws InterruptedException, IOException { ProcessResult result = runBuckProjectAndVerify("preprocess_script_test"); assertEquals("intellij", result.getStdout().trim()); } @Test public void testScalaProject() throws InterruptedException, IOException { runBuckProjectAndVerify("scala_project"); } @Test public void testIgnoredPathAddedToExcludedFolders() throws InterruptedException, IOException { runBuckProjectAndVerify("ignored_excluded"); } @Test public void testBuckModuleRegenerateSubproject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); final String extraModuleFilePath = "modules/extra/modules_extra.iml"; final File extraModuleFile = workspace.getPath(extraModuleFilePath).toFile(); workspace .runBuckCommand("project", "--intellij-aggregation-mode=none", "//modules/tip:tip") .assertSuccess(); assertFalse(extraModuleFile.exists()); final String modulesBefore = workspace.getFileContents(".idea/modules.xml"); final String fileXPath = String.format( "/project/component/modules/module[contains(@filepath,'%s')]", extraModuleFilePath); assertThat(XmlDomParser.parse(modulesBefore), Matchers.not(Matchers.hasXPath(fileXPath))); // Run regenerate on the new modules workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); assertTrue(extraModuleFile.exists()); final String modulesAfter = workspace.getFileContents(".idea/modules.xml"); assertThat(XmlDomParser.parse(modulesAfter), Matchers.hasXPath(fileXPath)); workspace.verify(); } @Test public void testBuckModuleRegenerateSubprojectNoOp() throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "incrementalProject", temporaryFolder.newFolder()) .setUp(); workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "//modules/tip:tip", "//modules/extra:extra") .assertSuccess(); workspace.verify(); // Run regenerate, should be a no-op relative to previous workspace .runBuckCommand( "project", "--intellij-aggregation-mode=none", "--update", "//modules/extra:extra") .assertSuccess(); workspace.verify(); } @Test public void testCrossCellIntelliJProject() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace primary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/primary", temporaryFolder.newFolder()); primary.setUp(); ProjectWorkspace secondary = TestDataHelper.createProjectWorkspaceForScenario( this, "inter-cell/secondary", temporaryFolder.newFolder()); secondary.setUp(); TestDataHelper.overrideBuckconfig( primary, ImmutableMap.of( "repositories", ImmutableMap.of("secondary", secondary.getPath(".").normalize().toString()))); // First try with cross-cell enabled String target = "//apps/sample:app_with_cross_cell_android_lib"; ProcessResult result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=true", "--ide", "intellij", target); result.assertSuccess(); String libImlPath = ".idea/libraries/secondary__java_com_crosscell_crosscell.xml"; Node doc = XmlDomParser.parse(primary.getFileContents(libImlPath)); String urlXpath = "/component/library/CLASSES/root/@url"; // Assert that the library URL is inside the project root assertThat( doc, Matchers.hasXPath( urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/buck-out/cells/secondary/gen/"))); result = primary.runBuckCommand( "project", "--config", "project.embedded_cell_buck_out_enabled=false", "--ide", "intellij", target); result.assertSuccess(); Node doc2 = XmlDomParser.parse(primary.getFileContents(libImlPath)); // Assert that the library URL is outside the project root assertThat(doc2, Matchers.hasXPath(urlXpath, Matchers.startsWith("jar://$PROJECT_DIR$/.."))); } private ProcessResult runBuckProjectAndVerify(String folderWithTestData, String... commandArgs) throws InterruptedException, IOException { AssumeAndroidPlatform.assumeSdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, folderWithTestData, temporaryFolder); workspace.setUp(); ProcessResult result = workspace.runBuckCommand(Lists.asList("project", commandArgs).toArray(new String[0])); result.assertSuccess("buck project should exit cleanly"); workspace.verify(); return result; } }
clonetwin26/buck
test/com/facebook/buck/ide/intellij/ProjectIntegrationTest.java
Java
apache-2.0
16,432
/* * Copyright 2016 John Grosh <john.a.grosh@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 com.jagrosh.jmusicbot.commands; import java.util.List; import java.util.concurrent.TimeUnit; import com.jagrosh.jdautilities.commandclient.CommandEvent; import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.audio.AudioHandler; import com.jagrosh.jmusicbot.audio.QueuedTrack; import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.exceptions.PermissionException; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class QueueCmd extends MusicCommand { private final PaginatorBuilder builder; public QueueCmd(Bot bot) { super(bot); this.name = "queue"; this.help = "shows the current queue"; this.arguments = "[pagenum]"; this.aliases = new String[]{"list"}; this.bePlaying = true; this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS}; builder = new PaginatorBuilder() .setColumns(1) .setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}}) .setItemsPerPage(10) .waitOnSinglePage(false) .useNumberedItems(true) .showPageNumbers(true) .setEventWaiter(bot.getWaiter()) .setTimeout(1, TimeUnit.MINUTES) ; } @Override public void doCommand(CommandEvent event) { int pagenum = 1; try{ pagenum = Integer.parseInt(event.getArgs()); }catch(NumberFormatException e){} AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); List<QueuedTrack> list = ah.getQueue().getList(); if(list.isEmpty()) { event.replyWarning("There is no music in the queue!" +(!ah.isMusicPlaying() ? "" : " Now playing:\n\n**"+ah.getPlayer().getPlayingTrack().getInfo().title+"**\n"+FormatUtil.embedformattedAudio(ah))); return; } String[] songs = new String[list.size()]; long total = 0; for(int i=0; i<list.size(); i++) { total += list.get(i).getTrack().getDuration(); songs[i] = list.get(i).toString(); } long fintotal = total; builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal)) .setItems(songs) .setUsers(event.getAuthor()) .setColor(event.getSelfMember().getColor()) ; builder.build().paginate(event.getChannel(), pagenum); } private String getQueueTitle(AudioHandler ah, String success, int songslength, long total) { StringBuilder sb = new StringBuilder(); if(ah.getPlayer().getPlayingTrack()!=null) sb.append("**").append(ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n").append(FormatUtil.embedformattedAudio(ah)).append("\n\n"); return sb.append(success).append(" Current Queue | ").append(songslength).append(" entries | `").append(FormatUtil.formatTime(total)).append("` ").toString(); } }
Blankscar/NothingToSeeHere
src/main/java/com/jagrosh/jmusicbot/commands/QueueCmd.java
Java
apache-2.0
3,885
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.opsworks.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeregisterEcsClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeregisterEcsClusterResult == false) return false; DeregisterEcsClusterResult other = (DeregisterEcsClusterResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeregisterEcsClusterResult clone() { try { return (DeregisterEcsClusterResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DeregisterEcsClusterResult.java
Java
apache-2.0
2,373
package com.google.api.ads.adwords.jaxws.v201509.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Represents a criterion belonging to a shared set. * * * <p>Java class for SharedCriterion complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SharedCriterion"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="sharedSetId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="criterion" type="{https://adwords.google.com/api/adwords/cm/v201509}Criterion" minOccurs="0"/> * &lt;element name="negative" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SharedCriterion", propOrder = { "sharedSetId", "criterion", "negative" }) public class SharedCriterion { protected Long sharedSetId; protected Criterion criterion; protected Boolean negative; /** * Gets the value of the sharedSetId property. * * @return * possible object is * {@link Long } * */ public Long getSharedSetId() { return sharedSetId; } /** * Sets the value of the sharedSetId property. * * @param value * allowed object is * {@link Long } * */ public void setSharedSetId(Long value) { this.sharedSetId = value; } /** * Gets the value of the criterion property. * * @return * possible object is * {@link Criterion } * */ public Criterion getCriterion() { return criterion; } /** * Sets the value of the criterion property. * * @param value * allowed object is * {@link Criterion } * */ public void setCriterion(Criterion value) { this.criterion = value; } /** * Gets the value of the negative property. * * @return * possible object is * {@link Boolean } * */ public Boolean isNegative() { return negative; } /** * Sets the value of the negative property. * * @param value * allowed object is * {@link Boolean } * */ public void setNegative(Boolean value) { this.negative = value; } }
gawkermedia/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201509/cm/SharedCriterion.java
Java
apache-2.0
2,764
package de.choesel.blechwiki.model; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.UUID; /** * Created by christian on 05.05.16. */ @DatabaseTable(tableName = "komponist") public class Komponist { @DatabaseField(generatedId = true) private UUID id; @DatabaseField(canBeNull = true, uniqueCombo = true) private String name; @DatabaseField(canBeNull = true) private String kurzname; @DatabaseField(canBeNull = true, uniqueCombo = true) private Integer geboren; @DatabaseField(canBeNull = true) private Integer gestorben; public UUID getId() { return id; } public String getName() { return name; } public String getKurzname() { return kurzname; } public Integer getGeboren() { return geboren; } public Integer getGestorben() { return gestorben; } public void setId(UUID id) { this.id = id; } public void setName(String name) { this.name = name; } public void setKurzname(String kurzname) { this.kurzname = kurzname; } public void setGeboren(Integer geboren) { this.geboren = geboren; } public void setGestorben(Integer gestorben) { this.gestorben = gestorben; } }
ChristianHoesel/android-blechwiki
app/src/main/java/de/choesel/blechwiki/model/Komponist.java
Java
apache-2.0
1,341
package org.judal.examples.java.model.array; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import javax.jdo.JDOException; import org.judal.storage.DataSource; import org.judal.storage.EngineFactory; import org.judal.storage.java.ArrayRecord; import org.judal.storage.relational.RelationalDataSource; /** * Extend ArrayRecord in order to create model classes manageable by JUDAL. * Add your getters and setters for database fields. */ public class Student extends ArrayRecord { private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "student"; public Student() throws JDOException { this(EngineFactory.getDefaultRelationalDataSource()); } public Student(RelationalDataSource dataSource) throws JDOException { super(dataSource, TABLE_NAME); } @Override public void store(DataSource dts) throws JDOException { // Generate the student Id. from a sequence if it is not provided if (isNull("id_student")) setId ((int) dts.getSequence("seq_student").nextValue()); super.store(dts); } public int getId() { return getInt("id_student"); } public void setId(final int id) { put("id_student", id); } public String getFirstName() { return getString("first_name"); } public void setFirstName(final String firstName) { put("first_name", firstName); } public String getLastName() { return getString("last_name"); } public void setLastName(final String lastName) { put("last_name", lastName); } public Calendar getDateOfBirth() { return getCalendar("date_of_birth"); } public void setDateOfBirth(final Calendar dob) { put("date_of_birth", dob); } public void setDateOfBirth(final String yyyyMMdd) throws ParseException { SimpleDateFormat dobFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = new GregorianCalendar(); cal.setTime(dobFormat.parse(yyyyMMdd)); setDateOfBirth(cal); } public byte[] getPhoto() { return getBytes("photo"); } public void setPhoto(final byte[] photoData) { put("photo", photoData); } }
sergiomt/judal
aexample/src/main/java/org/judal/examples/java/model/array/Student.java
Java
apache-2.0
2,209
/* * Copyright 2011-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.http.apache.client.impl; import com.amazonaws.ClientConfiguration; import com.amazonaws.http.settings.HttpClientSettings; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ApacheConnectionManagerFactoryTest { private final ApacheConnectionManagerFactory factory = new ApacheConnectionManagerFactory(); @Test public void validateAfterInactivityMillis_RespectedInConnectionManager() { final int validateAfterInactivity = 1234; final HttpClientSettings httpClientSettings = HttpClientSettings.adapt(new ClientConfiguration() .withValidateAfterInactivityMillis(validateAfterInactivity)); final PoolingHttpClientConnectionManager connectionManager = (PoolingHttpClientConnectionManager) factory.create(httpClientSettings); assertEquals(validateAfterInactivity, connectionManager.getValidateAfterInactivity()); } }
dagnir/aws-sdk-java
aws-java-sdk-core/src/test/java/com/amazonaws/http/apache/client/impl/ApacheConnectionManagerFactoryTest.java
Java
apache-2.0
1,653
package org.spincast.core.routing; import java.util.List; import org.spincast.core.exchange.RequestContext; /** * The result of the router, when asked to find matches for * a request. */ public interface RoutingResult<R extends RequestContext<?>> { /** * The handlers matching the route (a main handler + filters, if any), * in order they have to be called. */ public List<RouteHandlerMatch<R>> getRouteHandlerMatches(); /** * The main route handler and its information, from the routing result. */ public RouteHandlerMatch<R> getMainRouteHandlerMatch(); }
spincast/spincast-framework
spincast-core-parent/spincast-core/src/main/java/org/spincast/core/routing/RoutingResult.java
Java
apache-2.0
609
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package king.flow.common; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.File; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import king.flow.action.business.ShowClockAction; import king.flow.data.TLSResult; import king.flow.view.Action; import king.flow.view.Action.CleanAction; import king.flow.view.Action.EjectCardAction; import king.flow.view.Action.WithdrawCardAction; import king.flow.view.Action.EncryptKeyboardAction; import king.flow.view.Action.HideAction; import king.flow.view.Action.InsertICardAction; import king.flow.view.Action.LimitInputAction; import king.flow.view.Action.MoveCursorAction; import king.flow.view.Action.NumericPadAction; import king.flow.view.Action.OpenBrowserAction; import king.flow.view.Action.PlayMediaAction; import king.flow.view.Action.PlayVideoAction; import king.flow.view.Action.PrintPassbookAction; import king.flow.view.Action.RunCommandAction; import king.flow.view.Action.RwFingerPrintAction; import king.flow.view.Action.SetFontAction; import king.flow.view.Action.SetPrinterAction; import king.flow.view.Action.ShowComboBoxAction; import king.flow.view.Action.ShowGridAction; import king.flow.view.Action.ShowTableAction; import king.flow.view.Action.Swipe2In1CardAction; import king.flow.view.Action.SwipeCardAction; import king.flow.view.Action.UploadFileAction; import king.flow.view.Action.UseTipAction; import king.flow.view.Action.VirtualKeyboardAction; import king.flow.view.Action.WriteICardAction; import king.flow.view.ComponentEnum; import king.flow.view.DefinedAction; import king.flow.view.DeviceEnum; import king.flow.view.JumpAction; import king.flow.view.MsgSendAction; /** * * @author LiuJin */ public class CommonConstants { public static final String APP_STARTUP_ENTRY = "bank.exe"; public static final Charset UTF8 = Charset.forName("UTF-8"); static final File[] SYS_ROOTS = File.listRoots(); public static final int DRIVER_COUNT = SYS_ROOTS.length; public static final String XML_NODE_PREFIX = "N_"; public static final String REVERT = "re_"; public static final String BID = "bid"; public static final String UID_PREFIX = "<" + TLSResult.UID + ">"; public static final String UID_AFFIX = "</" + TLSResult.UID + ">"; public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd"; public static final String VALID_BANK_CARD = "validBankCard"; public static final String BALANCED_PAY_MAC = "balancedPayMAC"; public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]"; public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]"; public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt"; public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt"; public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt"; public static final int CONTAINER_KEY = Integer.MAX_VALUE; public static final int NORMAL = 0; public static final int ABNORMAL = 1; public static final int BALANCE = 12345; public static final int RESTART_SIGNAL = 1; public static final int DOWNLOAD_KEY_SIGNAL = 1; public static final int UPDATE_SIGNAL = 1; public static final int WATCHDOG_CHECK_INTERVAL = 5; public static final String VERSION; public static final long DEBUG_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(3); public static final long RUN_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(1); // public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString(); static { String workingPath = System.getProperty("user.dir"); final int lastIndexOf = workingPath.lastIndexOf('_'); if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) { VERSION = workingPath.substring(lastIndexOf + 1); } else { VERSION = "Unknown"; } } /* JMX configuration */ private static String getJmxRmiUrl(int port) { return "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi"; } public static final int APP_JMX_RMI_PORT = 9998; public static final String APP_JMX_RMI_URL = getJmxRmiUrl(APP_JMX_RMI_PORT); public static final int WATCHDOG_JMX_RMI_PORT = 9999; public static final String WATCHDOG_JMX_RMI_URL = getJmxRmiUrl(WATCHDOG_JMX_RMI_PORT); /* system variable pattern */ public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}"; public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*"; public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID"; /* swing default config */ public static final int DEFAULT_TABLE_ROW_COUNT = 15; public static final int TABLE_ROW_HEIGHT = 25; public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20; /* packet header ID */ public static final int GENERAL_MSG_CODE = 0; //common message public static final int REGISTRY_MSG_CODE = 1; //terminal registration message public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message public static final int MANAGER_MSG_CODE = 100; //management message /*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */ public static final int MAX_MESSAGES_PER_READ = 64; //how many read actions in one message conversation public static final int MIN_RECEIVED_BUFFER_SIZE = 1024; //1024 bytes public static final int RECEIVED_BUFFER_SIZE = 32 * 1024; //32k bytes public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes /* keyboard cipher key */ public static final String WORK_SECRET_KEY = "workSecretKey"; public static final String MA_KEY = "maKey"; public static final String MASTER_KEY = "masterKey"; /* packet result flag */ public static final int SUCCESSFUL_MSG_CODE = 0; /* xml jaxb context */ public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net"; public static final String TLS_PACKAGE_CONTEXT = "king.flow.data"; public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view"; public static final String KING_FLOW_BACKGROUND = "king.flow.background"; public static final String KING_FLOW_PROGRESS = "king.flow.progress"; public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config"; public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+"; public static final String ADVANCED_TABLE_TOTAL_PAGES = "total"; public static final String ADVANCED_TABLE_VALUE = "value"; public static final String ADVANCED_TABLE_CURRENT_PAGE = "current"; /* card-reading state */ public static final int INVALID_CARD_STATE = -1; public static final int MAGNET_CARD_STATE = 2; public static final int IC_CARD_STATE = 3; /* union-pay transaction type */ public static final String UNION_PAY_REGISTRATION = "1"; public static final String UNION_PAY_TRANSACTION = "3"; public static final String UNION_PAY_TRANSACTION_BALANCE = "4"; /* card affiliation type */ public static final String CARD_AFFILIATION_INTERNAL = "1"; public static final String CARD_AFFILIATION_EXTERNAL = "2"; /* supported driver types */ static final ImmutableSet<DeviceEnum> SUPPORTED_DEVICES = new ImmutableSet.Builder<DeviceEnum>() .add(DeviceEnum.IC_CARD) .add(DeviceEnum.CASH_SAVER) .add(DeviceEnum.GZ_CARD) .add(DeviceEnum.HIS_CARD) .add(DeviceEnum.KEYBOARD) .add(DeviceEnum.MAGNET_CARD) .add(DeviceEnum.MEDICARE_CARD) .add(DeviceEnum.PATIENT_CARD) .add(DeviceEnum.PID_CARD) .add(DeviceEnum.PKG_8583) .add(DeviceEnum.PRINTER) .add(DeviceEnum.SENSOR_CARD) .add(DeviceEnum.TWO_IN_ONE_CARD) .build(); /* action-component relationship map */ public static final String JUMP_ACTION = JumpAction.class.getSimpleName(); public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName(); public static final String CLEAN_ACTION = CleanAction.class.getSimpleName(); public static final String HIDE_ACTION = HideAction.class.getSimpleName(); public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName(); public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName(); public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName(); public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName(); public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName(); public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName(); public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName(); public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName(); public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName(); public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName(); public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName(); public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName(); public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName(); public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName(); public static final String BALANCE_TRANS_ACTION = "BalanceTransAction"; public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName(); public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName(); public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName(); public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName(); public static final String EJECT_CARD_ACTION = EjectCardAction.class.getSimpleName(); public static final String WITHDRAW_CARD_ACTION = WithdrawCardAction.class.getSimpleName(); public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName(); public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName(); public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName(); public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName(); public static final String SHOW_GRID_ACTION = ShowGridAction.class.getSimpleName(); public static final String TYPE_NUMERIC_PAD_ACTION = NumericPadAction.class.getSimpleName(); public static final String WEB_LOAD_ACTION = Action.WebLoadAction.class.getSimpleName(); static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>() .put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(JUMP_ACTION) .add(SET_FONT_ACTION) .add(CLEAN_ACTION) .add(HIDE_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(OPEN_BROWSER_ACTION) .add(RUN_COMMAND_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(PRINT_RECEIPT_ACTION) .add(SEND_MSG_ACTION) .add(INSERT_IC_ACTION) .add(WRITE_IC_ACTION) .add(MOVE_CURSOR_ACTION) .add(PRINT_PASSBOOK_ACTION) .add(UPLOAD_FILE_ACTION) .add(BALANCE_TRANS_ACTION) .add(EJECT_CARD_ACTION) .add(WITHDRAW_CARD_ACTION) .add(WEB_LOAD_ACTION) .build()) .put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_COMBOBOX_ACTION) .add(SWIPE_CARD_ACTION) .add(SWIPE_TWO_IN_ONE_CARD_ACTION) .add(PLAY_MEDIA_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.LABEL, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_CLOCK_ACTION) .build()) .put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(MOVE_CURSOR_ACTION) .add(ENCRYPT_KEYBORAD_ACTION) .build()) .put(ComponentEnum.TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_TABLE_ACTION) .build()) .put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(SHOW_TABLE_ACTION) .add(SEND_MSG_ACTION) .build()) .put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(PLAY_VIDEO_ACTION) .build()) .put(ComponentEnum.GRID, new ImmutableList.Builder<String>() .add(SHOW_GRID_ACTION) .build()) .put(ComponentEnum.NUMERIC_PAD, new ImmutableList.Builder<String>() .add(TYPE_NUMERIC_PAD_ACTION) .build()) .build(); }
toyboxman/yummy-xml-UI
xml-UI/src/main/java/king/flow/common/CommonConstants.java
Java
apache-2.0
15,275
package ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import ca.qc.bergeron.marcantoine.crammeur.librairy.annotations.Entity; import ca.qc.bergeron.marcantoine.crammeur.librairy.exceptions.KeyException; import ca.qc.bergeron.marcantoine.crammeur.android.models.Client; import ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.SQLiteTemplate; import ca.qc.bergeron.marcantoine.crammeur.librairy.repository.i.Repository; /** * Created by Marc-Antoine on 2017-01-11. */ public final class SQLiteClient extends SQLiteTemplate<Client,Integer> implements ca.qc.bergeron.marcantoine.crammeur.android.repository.crud.sqlite.i.SQLiteClient { public SQLiteClient(Repository pRepository, Context context) { super(Client.class,Integer.class,pRepository, context); } @Override protected Client convertCursorToEntity(@NonNull Cursor pCursor) { Client o = new Client(); o.Id = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name())); o.Name = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_NAME)); o.EMail = pCursor.getString(pCursor.getColumnIndex(F_CLIENT_EMAIL)); return o; } @Override protected Integer convertCursorToId(@NonNull Cursor pCursor) { Integer result; result = pCursor.getInt(pCursor.getColumnIndex(mId.getAnnotation(Entity.Id.class).name())); return result; } @Override public void create() { mDB.execSQL(CREATE_TABLE_CLIENTS); } @NonNull @Override public Integer save(@NonNull Client pData) throws KeyException { ContentValues values = new ContentValues(); try { if (pData.Id == null) { pData.Id = this.getKey(pData); } values.put(mId.getAnnotation(Entity.Id.class).name(), mKey.cast(mId.get(pData))); values.put(F_CLIENT_NAME, pData.Name); values.put(F_CLIENT_EMAIL, pData.EMail); if (mId.get(pData) == null || !this.contains(mKey.cast(mId.get(pData)))) { mId.set(pData, (int) mDB.insert(T_CLIENTS, null, values)); } else { mDB.update(T_CLIENTS, values, mId.getAnnotation(Entity.Id.class).name() + "=?", new String[]{String.valueOf(pData.Id)}); } return pData.Id; } catch (IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Nullable @Override public Integer getKey(@NonNull Client pEntity) { Integer result = null; try { if (mId.get(pEntity) != null) return (Integer) mId.get(pEntity); String[] columns = new String[] {F_ID}; String where = "LOWER(" + F_CLIENT_NAME + ")=LOWER(?) AND LOWER(" + F_CLIENT_EMAIL + ")=LOWER(?)"; String[] whereArgs = new String[] {pEntity.Name,pEntity.EMail}; // limit 1 row = "1"; Cursor cursor = mDB.query(T_CLIENTS, columns, where, whereArgs, null, null, null, "1"); if (cursor.moveToFirst()) { result = cursor.getInt(cursor.getColumnIndex(F_ID)); } } catch (IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } return result; } }
crammeur/MyInvoices
crammeurAndroid/src/main/java/ca/qc/bergeron/marcantoine/crammeur/android/repository/crud/sqlite/SQLiteClient.java
Java
apache-2.0
3,537
/* * Copyright 2015 - 2021 TU Dortmund * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.learnlib.alex.learning.services; import de.learnlib.alex.data.entities.ProjectEnvironment; import de.learnlib.alex.data.entities.ProjectUrl; import de.learnlib.alex.data.entities.actions.Credentials; import java.util.HashMap; import java.util.Map; /** * Class to mange a URL and get URL based on this. */ public class BaseUrlManager { private final Map<String, ProjectUrl> urlMap; /** Advanced constructor which sets the base url field. */ public BaseUrlManager(ProjectEnvironment environment) { this.urlMap = new HashMap<>(); environment.getUrls().forEach(u -> this.urlMap.put(u.getName(), u)); } /** * Get the absolute URL of a path, i.e. based on the base url (base url + '/' + path'), as String * and insert the credentials if possible. * * @param path * The path to append on the base url. * @param credentials * The credentials to insert into the URL. * @return An absolute URL as String */ public String getAbsoluteUrl(String urlName, String path, Credentials credentials) { final String url = combineUrls(urlMap.get(urlName).getUrl(), path); return BaseUrlManager.getUrlWithCredentials(url, credentials); } public String getAbsoluteUrl(String urlName, String path) { final String url = combineUrls(urlMap.get(urlName).getUrl(), path); return BaseUrlManager.getUrlWithCredentials(url, null); } /** * Append apiPath to basePath and make sure that only one '/' is between them. * * @param basePath * The prefix of the new URL. * @param apiPath * The suffix of the new URL. * @return The combined URL. */ private String combineUrls(String basePath, String apiPath) { if (basePath.endsWith("/") && apiPath.startsWith("/")) { // both have a '/' -> remove one return basePath + apiPath.substring(1); } else if (!basePath.endsWith("/") && !apiPath.startsWith("/")) { // no one has a '/' -> add one return basePath + "/" + apiPath; } else { // exact 1. '/' in between -> good to go return basePath + apiPath; } } private static String getUrlWithCredentials(String url, Credentials credentials) { if (credentials != null && credentials.areValid()) { return url.replaceFirst("^(http[s]?://)", "$1" + credentials.getName() + ":" + credentials.getPassword() + "@"); } else { return url; } } }
LearnLib/alex
backend/src/main/java/de/learnlib/alex/learning/services/BaseUrlManager.java
Java
apache-2.0
3,225
/* * Copyright 2015 Cognitive Medical Systems, Inc (http://www.cognitivemedciine.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.socraticgrid.hl7.services.orders.model.types.orderitems; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.socraticgrid.hl7.services.orders.model.OrderItem; import org.socraticgrid.hl7.services.orders.model.primatives.Code; import org.socraticgrid.hl7.services.orders.model.primatives.Identifier; import org.socraticgrid.hl7.services.orders.model.primatives.Period; import org.socraticgrid.hl7.services.orders.model.primatives.Quantity; import org.socraticgrid.hl7.services.orders.model.primatives.Ratio; public class MedicationOrderItem extends OrderItem { /** * */ private static final long serialVersionUID = 1L; private String additionalDosageIntructions; private String comment; private Quantity dispenseQuantity= new Quantity(); private String dosageInstructions; private Code dosageMethod; private Quantity dosageQuantity = new Quantity(); private Ratio dosageRate = new Ratio(); private Code dosageSite = new Code(); private Date dosageTiming; private Period dosageTimingPeriod = new Period(); private List<Identifier> drug = new ArrayList<Identifier>(0); private Date endDate; private Quantity expectedSupplyDuration = new Quantity(); private Ratio maxDosePerPeriod = new Ratio(); private List<Identifier> medication = new ArrayList<Identifier>(0); private int numberOfRepeatsAllowed=0; private Code prescriber; private Code route = new Code(); private String schedule; private Date startDate; /** * @return the additionalDosageIntructions */ public String getAdditionalDosageIntructions() { return additionalDosageIntructions; } /** * @return the comment */ public String getComment() { return comment; } /** * @return the dispenseQuantity */ public Quantity getDispenseQuantity() { return dispenseQuantity; } /** * @return the dosageInstructions */ public String getDosageInstructions() { return dosageInstructions; } /** * @return the dosageMethod */ public Code getDosageMethod() { return dosageMethod; } /** * @return the dosageQuantity */ public Quantity getDosageQuantity() { return dosageQuantity; } /** * @return the dosageRate */ public Ratio getDosageRate() { return dosageRate; } /** * @return the dosageSite */ public Code getDosageSite() { return dosageSite; } /** * @return the dosageTiming */ public Date getDosageTiming() { return dosageTiming; } /** * @return the dosageTimingPeriod */ public Period getDosageTimingPeriod() { return dosageTimingPeriod; } /** * @return the drug */ public List<Identifier> getDrug() { return drug; } /** * @return the endDate */ public Date getEndDate() { return endDate; } /** * @return the expectedSupplyDuration */ public Quantity getExpectedSupplyDuration() { return expectedSupplyDuration; } /** * @return the maxDosePerPeriod */ public Ratio getMaxDosePerPeriod() { return maxDosePerPeriod; } /** * @return the medication */ public List<Identifier> getMedication() { return medication; } /** * @return the numberOfRepeatsAllowed */ public int getNumberOfRepeatsAllowed() { return numberOfRepeatsAllowed; } /** * @return the prescriber */ public Code getPrescriber() { return prescriber; } /** * @return the route */ public Code getRoute() { return route; } /** * @return the schedule */ public String getSchedule() { return schedule; } /** * @return the startDate */ public Date getStartDate() { return startDate; } /** * @param additionalDosageIntructions the additionalDosageIntructions to set */ public void setAdditionalDosageIntructions(String additionalDosageIntructions) { this.additionalDosageIntructions = additionalDosageIntructions; } /** * @param comment the comment to set */ public void setComment(String comment) { this.comment = comment; } /** * @param dispenseQuantity the dispenseQuantity to set */ public void setDispenseQuantity(Quantity dispenseQuantity) { this.dispenseQuantity = dispenseQuantity; } /** * @param dosageInstructions the dosageInstructions to set */ public void setDosageInstructions(String dosageInstructions) { this.dosageInstructions = dosageInstructions; } /** * @param dosageMethod the dosageMethod to set */ public void setDosageMethod(Code dosageMethod) { this.dosageMethod = dosageMethod; } /** * @param dosageQuantity the dosageQuantity to set */ public void setDosageQuantity(Quantity dosageQuantity) { this.dosageQuantity = dosageQuantity; } /** * @param dosageRate the dosageRate to set */ public void setDosageRate(Ratio dosageRate) { this.dosageRate = dosageRate; } /** * @param dosageSite the dosageSite to set */ public void setDosageSite(Code dosageSite) { this.dosageSite = dosageSite; } /** * @param dosageTiming the dosageTiming to set */ public void setDosageTiming(Date dosageTiming) { this.dosageTiming = dosageTiming; } /** * @param dosageTimingPeriod the dosageTimingPeriod to set */ public void setDosageTimingPeriod(Period dosageTimingPeriod) { this.dosageTimingPeriod = dosageTimingPeriod; } /** * @param drug the drug to set */ public void setDrug(List<Identifier> drug) { this.drug = drug; } /** * @param endDate the endDate to set */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * @param expectedSupplyDuration the expectedSupplyDuration to set */ public void setExpectedSupplyDuration(Quantity expectedSupplyDuration) { this.expectedSupplyDuration = expectedSupplyDuration; } /** * @param maxDosePerPeriod the maxDosePerPeriod to set */ public void setMaxDosePerPeriod(Ratio maxDosePerPeriod) { this.maxDosePerPeriod = maxDosePerPeriod; } /** * @param medication the medication to set */ public void setMedication(List<Identifier> medication) { this.medication = medication; } /** * @param numberOfRepeatsAllowed the numberOfRepeatsAllowed to set */ public void setNumberOfRepeatsAllowed(int numberOfRepeatsAllowed) { this.numberOfRepeatsAllowed = numberOfRepeatsAllowed; } /** * @param prescriber the prescriber to set */ public void setPrescriber(Code prescriber) { this.prescriber = prescriber; } /** * @param route the route to set */ public void setRoute(Code route) { this.route = route; } /** * @param schedule the schedule to set */ public void setSchedule(String schedule) { this.schedule = schedule; } /** * @param startDate the startDate to set */ public void setStartDate(Date startDate) { this.startDate = startDate; } }
SocraticGrid/OMS-API
src/main/java/org/socraticgrid/hl7/services/orders/model/types/orderitems/MedicationOrderItem.java
Java
apache-2.0
7,408
package gui; //: gui/SubmitLabelManipulationTask.java import javax.swing.*; import java.util.concurrent.*; public class SubmitLabelManipulationTask { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Hello Swing"); final JLabel label = new JLabel("A Label"); frame.add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); frame.setVisible(true); TimeUnit.SECONDS.sleep(1); SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Hey! This is Different!"); } }); } } ///:~
vowovrz/thinkinj
thinkinj/src/main/java/gui/SubmitLabelManipulationTask.java
Java
apache-2.0
646
/** * Copyright 2006-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.mybatis.generator.codegen.ibatis2.dao.elements; import java.util.Set; import java.util.TreeSet; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; import org.mybatis.generator.api.dom.java.TopLevelClass; /** * * @author Jeff Butler * */ public class UpdateByExampleWithoutBLOBsMethodGenerator extends AbstractDAOElementGenerator { public UpdateByExampleWithoutBLOBsMethodGenerator() { super(); } @Override public void addImplementationElements(TopLevelClass topLevelClass) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); Method method = getMethodShell(importedTypes); method .addBodyLine("UpdateByExampleParms parms = new UpdateByExampleParms(record, example);"); //$NON-NLS-1$ StringBuilder sb = new StringBuilder(); sb.append("int rows = "); //$NON-NLS-1$ sb.append(daoTemplate.getUpdateMethod(introspectedTable .getIbatis2SqlMapNamespace(), introspectedTable .getUpdateByExampleStatementId(), "parms")); //$NON-NLS-1$ method.addBodyLine(sb.toString()); method.addBodyLine("return rows;"); //$NON-NLS-1$ if (context.getPlugins() .clientUpdateByExampleWithoutBLOBsMethodGenerated(method, topLevelClass, introspectedTable)) { topLevelClass.addImportedTypes(importedTypes); topLevelClass.addMethod(method); } } @Override public void addInterfaceElements(Interface interfaze) { if (getExampleMethodVisibility() == JavaVisibility.PUBLIC) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); Method method = getMethodShell(importedTypes); if (context.getPlugins() .clientUpdateByExampleWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable)) { interfaze.addImportedTypes(importedTypes); interfaze.addMethod(method); } } } private Method getMethodShell(Set<FullyQualifiedJavaType> importedTypes) { FullyQualifiedJavaType parameterType; if (introspectedTable.getRules().generateBaseRecordClass()) { parameterType = new FullyQualifiedJavaType(introspectedTable .getBaseRecordType()); } else { parameterType = new FullyQualifiedJavaType(introspectedTable .getPrimaryKeyType()); } importedTypes.add(parameterType); Method method = new Method(); method.setVisibility(getExampleMethodVisibility()); method.setReturnType(FullyQualifiedJavaType.getIntInstance()); method.setName(getDAOMethodNameCalculator() .getUpdateByExampleWithoutBLOBsMethodName(introspectedTable)); method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$ method.addParameter(new Parameter(new FullyQualifiedJavaType( introspectedTable.getExampleType()), "example")); //$NON-NLS-1$ for (FullyQualifiedJavaType fqjt : daoTemplate.getCheckedExceptions()) { method.addException(fqjt); importedTypes.add(fqjt); } context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable); return method; } }
li24361/mybatis-generator-core
src/main/java/org/mybatis/generator/codegen/ibatis2/dao/elements/UpdateByExampleWithoutBLOBsMethodGenerator.java
Java
apache-2.0
4,329
package jp.teraparser.transition; import java.util.Arrays; /** * Resizable-array implementation of Deque which works like java.util.ArrayDeque * * jp.teraparser.util * * @author Hiroki Teranishi */ public class Stack implements Cloneable { private static final int MIN_INITIAL_CAPACITY = 8; private int[] elements; private int head; private int tail; /** * Allocates empty array to hold the given number of elements. */ private void allocateElements(int numElements) { int initialCapacity = MIN_INITIAL_CAPACITY; // Find the best power of two to hold elements. // Tests "<=" because arrays aren't kept full. if (numElements >= initialCapacity) { initialCapacity = numElements; initialCapacity |= (initialCapacity >>> 1); initialCapacity |= (initialCapacity >>> 2); initialCapacity |= (initialCapacity >>> 4); initialCapacity |= (initialCapacity >>> 8); initialCapacity |= (initialCapacity >>> 16); initialCapacity++; if (initialCapacity < 0) { // Too many elements, must back off initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements } } elements = new int[initialCapacity]; } /** * Doubles the capacity of this deque. Call only when full, i.e., * when head and tail have wrapped around to become equal. */ private void doubleCapacity() { assert head == tail; int p = head; int n = elements.length; int r = n - p; // number of elements to the right of p int newCapacity = n << 1; if (newCapacity < 0) { throw new IllegalStateException("Sorry, deque too big"); } int[] a = new int[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = a; head = 0; tail = n; } public Stack() { elements = new int[16]; } public Stack(int numElements) { allocateElements(numElements); } public void push(int e) { elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) { doubleCapacity(); } } public int pop() { int h = head; int result = elements[h]; elements[h] = 0; head = (h + 1) & (elements.length - 1); return result; } public int top() { return elements[head]; } public int getFirst() { return top(); } public int get(int position, int defaultValue) { if (position < 0 || position >= size()) { return defaultValue; } int mask = elements.length - 1; int h = head; for (int i = 0; i < position; i++) { h = (h + 1) & mask; } return elements[h]; } public int size() { return (tail - head) & (elements.length - 1); } public boolean isEmpty() { return head == tail; } public Stack clone() { try { Stack result = (Stack) super.clone(); result.elements = Arrays.copyOf(elements, elements.length); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(); } } }
chantera/teraparser
src/jp/teraparser/transition/Stack.java
Java
apache-2.0
3,381
package ppp.menu; import java.awt.image.BufferedImage; public abstract interface Menu { public abstract void up(); public abstract void down(); public abstract void enter(); public abstract void escape(); public abstract BufferedImage getImage(); }
mzijlstra/java-games
ppp/menu/Menu.java
Java
apache-2.0
256
/* * */ package org.utilities; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; // TODO: Auto-generated Javadoc /** * The Class CUtils. */ public class CUtils { /** * Work. * * @param task * the task * @return the object */ public static Object work(Callable<?> task) { Future<?> futureTask = es.submit(task); return futureTask; } /** * Gets the random string. * * @param rndSeed the rnd seed * @return the random string */ public static String getRandomString(double rndSeed) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); byte[] data = ("" + rndSeed).getBytes(); m.update(data, 0, data.length); BigInteger i = new BigInteger(1, m.digest()); return String.format("%1$032X", i); } catch (NoSuchAlgorithmException e) { } return "" + rndSeed; } /** * Gets the random number. * * @param s the s * @return the random number * @throws Exception the exception */ public static int getRandomNumber(String s) throws Exception { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); byte[] data = s.getBytes(); m.update(data, 0, data.length); BigInteger i = new BigInteger(1, m.digest()); return i.intValue(); } catch (NoSuchAlgorithmException e) { } throw new Exception("Cannot generate random number"); } /** The Constant es. */ private final static ExecutorService es = Executors.newCachedThreadPool(); /** * Instantiates a new c utils. */ private CUtils() { } }
sarathrami/Chain-Replication
src/org/utilities/CUtils.java
Java
apache-2.0
1,735
/* Copyright 2020 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.floodlight.switchmanager; import static java.util.Collections.singletonList; import static org.projectfloodlight.openflow.protocol.OFVersion.OF_12; import static org.projectfloodlight.openflow.protocol.OFVersion.OF_13; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.util.FlowModUtils; import org.projectfloodlight.openflow.protocol.OFFactory; import org.projectfloodlight.openflow.protocol.OFFlowMod; import org.projectfloodlight.openflow.protocol.OFMeterFlags; import org.projectfloodlight.openflow.protocol.OFMeterMod; import org.projectfloodlight.openflow.protocol.OFMeterModCommand; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.action.OFActions; import org.projectfloodlight.openflow.protocol.instruction.OFInstruction; import org.projectfloodlight.openflow.protocol.instruction.OFInstructionApplyActions; import org.projectfloodlight.openflow.protocol.meterband.OFMeterBandDrop; import org.projectfloodlight.openflow.protocol.oxm.OFOxms; import org.projectfloodlight.openflow.types.DatapathId; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.MacAddress; import org.projectfloodlight.openflow.types.OFBufferId; import org.projectfloodlight.openflow.types.OFPort; import org.projectfloodlight.openflow.types.OFVlanVidMatch; import org.projectfloodlight.openflow.types.TableId; import org.projectfloodlight.openflow.types.TransportPort; import org.projectfloodlight.openflow.types.U64; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Utils for switch flow generation. */ public final class SwitchFlowUtils { /** * OVS software switch manufacturer constant value. */ public static final String OVS_MANUFACTURER = "Nicira, Inc."; /** * Indicates the maximum size in bytes for a packet which will be send from switch to the controller. */ private static final int MAX_PACKET_LEN = 0xFFFFFFFF; private SwitchFlowUtils() { } /** * Create a MAC address based on the DPID. * * @param dpId switch object * @return {@link MacAddress} */ public static MacAddress convertDpIdToMac(DatapathId dpId) { return MacAddress.of(Arrays.copyOfRange(dpId.getBytes(), 2, 8)); } /** * Create sent to controller OpenFlow action. * * @param ofFactory OpenFlow factory * @return OpenFlow Action */ public static OFAction actionSendToController(OFFactory ofFactory) { OFActions actions = ofFactory.actions(); return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(OFPort.CONTROLLER) .build(); } /** * Create an OFAction which sets the output port. * * @param ofFactory OF factory for the switch * @param outputPort port to set in the action * @return {@link OFAction} */ public static OFAction actionSetOutputPort(final OFFactory ofFactory, final OFPort outputPort) { OFActions actions = ofFactory.actions(); return actions.buildOutput().setMaxLen(MAX_PACKET_LEN).setPort(outputPort).build(); } /** * Create go to table OFInstruction. * * @param ofFactory OF factory for the switch * @param tableId tableId to go * @return {@link OFAction} */ public static OFInstruction instructionGoToTable(final OFFactory ofFactory, final TableId tableId) { return ofFactory.instructions().gotoTable(tableId); } /** * Create an OFInstructionApplyActions which applies actions. * * @param ofFactory OF factory for the switch * @param actionList OFAction list to apply * @return {@link OFInstructionApplyActions} */ public static OFInstructionApplyActions buildInstructionApplyActions(OFFactory ofFactory, List<OFAction> actionList) { return ofFactory.instructions().applyActions(actionList).createBuilder().build(); } /** * Create set destination MAC address OpenFlow action. * * @param ofFactory OpenFlow factory * @param macAddress MAC address to set * @return OpenFlow Action */ public static OFAction actionSetDstMac(OFFactory ofFactory, final MacAddress macAddress) { OFOxms oxms = ofFactory.oxms(); OFActions actions = ofFactory.actions(); return actions.buildSetField() .setField(oxms.buildEthDst().setValue(macAddress).build()).build(); } /** * Create set source MAC address OpenFlow action. * * @param ofFactory OpenFlow factory * @param macAddress MAC address to set * @return OpenFlow Action */ public static OFAction actionSetSrcMac(OFFactory ofFactory, final MacAddress macAddress) { return ofFactory.actions().buildSetField() .setField(ofFactory.oxms().ethSrc(macAddress)).build(); } /** * Create set UDP source port OpenFlow action. * * @param ofFactory OpenFlow factory * @param srcPort UDP src port to set * @return OpenFlow Action */ public static OFAction actionSetUdpSrcAction(OFFactory ofFactory, TransportPort srcPort) { OFOxms oxms = ofFactory.oxms(); return ofFactory.actions().setField(oxms.udpSrc(srcPort)); } /** * Create set UDP destination port OpenFlow action. * * @param ofFactory OpenFlow factory * @param dstPort UDP dst port to set * @return OpenFlow Action */ public static OFAction actionSetUdpDstAction(OFFactory ofFactory, TransportPort dstPort) { OFOxms oxms = ofFactory.oxms(); return ofFactory.actions().setField(oxms.udpDst(dstPort)); } /** * Create OpenFlow flow modification command builder. * * @param ofFactory OpenFlow factory * @param cookie cookie * @param priority priority * @param tableId table id * @return OpenFlow command builder */ public static OFFlowMod.Builder prepareFlowModBuilder(OFFactory ofFactory, long cookie, int priority, int tableId) { OFFlowMod.Builder fmb = ofFactory.buildFlowAdd(); fmb.setIdleTimeout(FlowModUtils.INFINITE_TIMEOUT); fmb.setHardTimeout(FlowModUtils.INFINITE_TIMEOUT); fmb.setBufferId(OFBufferId.NO_BUFFER); fmb.setCookie(U64.of(cookie)); fmb.setPriority(priority); fmb.setTableId(TableId.of(tableId)); return fmb; } /** * Create OpenFlow meter modification command. * * @param ofFactory OpenFlow factory * @param bandwidth bandwidth * @param burstSize burst size * @param meterId meter id * @param flags flags * @param commandType ADD, MODIFY or DELETE * @return OpenFlow command */ public static OFMeterMod buildMeterMod(OFFactory ofFactory, long bandwidth, long burstSize, long meterId, Set<OFMeterFlags> flags, OFMeterModCommand commandType) { OFMeterBandDrop.Builder bandBuilder = ofFactory.meterBands() .buildDrop() .setRate(bandwidth) .setBurstSize(burstSize); OFMeterMod.Builder meterModBuilder = ofFactory.buildMeterMod() .setMeterId(meterId) .setCommand(commandType) .setFlags(flags); if (ofFactory.getVersion().compareTo(OF_13) > 0) { meterModBuilder.setBands(singletonList(bandBuilder.build())); } else { meterModBuilder.setMeters(singletonList(bandBuilder.build())); } return meterModBuilder.build(); } /** * Create an OFAction to add a VLAN header. * * @param ofFactory OF factory for the switch * @param etherType ethernet type of the new VLAN header * @return {@link OFAction} */ public static OFAction actionPushVlan(final OFFactory ofFactory, final int etherType) { OFActions actions = ofFactory.actions(); return actions.buildPushVlan().setEthertype(EthType.of(etherType)).build(); } /** * Create an OFAction to change the outer most vlan. * * @param factory OF factory for the switch * @param newVlan final VLAN to be set on the packet * @return {@link OFAction} */ public static OFAction actionReplaceVlan(final OFFactory factory, final int newVlan) { OFOxms oxms = factory.oxms(); OFActions actions = factory.actions(); if (OF_12.compareTo(factory.getVersion()) == 0) { return actions.buildSetField().setField(oxms.buildVlanVid() .setValue(OFVlanVidMatch.ofRawVid((short) newVlan)) .build()).build(); } else { return actions.buildSetField().setField(oxms.buildVlanVid() .setValue(OFVlanVidMatch.ofVlan(newVlan)) .build()).build(); } } /** * Check switch is OVS. * * @param sw switch * @return true if switch is OVS */ public static boolean isOvs(IOFSwitch sw) { return OVS_MANUFACTURER.equals(sw.getSwitchDescription().getManufacturerDescription()); } }
telstra/open-kilda
src-java/floodlight-service/floodlight-modules/src/main/java/org/openkilda/floodlight/switchmanager/SwitchFlowUtils.java
Java
apache-2.0
9,966
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.nats; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class NatsComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("servers", java.lang.String.class); map.put("verbose", boolean.class); map.put("bridgeErrorHandler", boolean.class); map.put("lazyStartProducer", boolean.class); map.put("basicPropertyBinding", boolean.class); map.put("useGlobalSslContextParameters", boolean.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { NatsComponent target = (NatsComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "servers": target.setServers(property(camelContext, java.lang.String.class, value)); return true; case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": target.setUseGlobalSslContextParameters(property(camelContext, boolean.class, value)); return true; case "verbose": target.setVerbose(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { NatsComponent target = (NatsComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "servers": return target.getServers(); case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": return target.isUseGlobalSslContextParameters(); case "verbose": return target.isVerbose(); default: return null; } } }
alvinkwekel/camel
components/camel-nats/src/generated/java/org/apache/camel/component/nats/NatsComponentConfigurer.java
Java
apache-2.0
3,229
package ruboweb.pushetta.back.model; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity @Table(name = "user") public class User extends AbstractPersistable<Long> { private static final Logger logger = LoggerFactory.getLogger(User.class); private static final long serialVersionUID = 6088280461151862299L; @Column(nullable = false) private String name; @Column(nullable = false) private String token; public User() { } public User(String name) { this.name = name; this.token = this.generateToken(); } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the token */ public String getToken() { return token; } /** * @param token * the token to set */ public void setToken(String token) { this.token = token; } private String generateToken() { try { SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); String randomNum = new Integer(prng.nextInt()).toString(); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] bytes = sha.digest(randomNum.getBytes()); StringBuilder result = new StringBuilder(); char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; byte b; for (int idx = 0; idx < bytes.length; ++idx) { b = bytes[idx]; result.append(digits[(b & 240) >> 4]); result.append(digits[b & 15]); } return result.toString(); } catch (NoSuchAlgorithmException ex) { logger.error("generateToken() -- " + ex.getMessage()); } return null; } }
ruboweb/pushetta
src/main/java/ruboweb/pushetta/back/model/User.java
Java
apache-2.0
2,054
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.10.09 at 10:10:23 AM CST // package com.elong.nb.model.elong; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import java.util.List; import com.alibaba.fastjson.annotation.JSONField; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CommentResult complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CommentResult"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Count" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="Comments" type="{}ArrayOfCommentInfo" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CommentResult", propOrder = { "count", "comments" }) public class CommentResult { @JSONField(name = "Count") protected int count; @JSONField(name = "Comments") protected List<CommentInfo> comments; /** * Gets the value of the count property. * */ public int getCount() { return count; } /** * Sets the value of the count property. * */ public void setCount(int value) { this.count = value; } /** * Gets the value of the comments property. * * @return * possible object is * {@link List<CommentInfo> } * */ public List<CommentInfo> getComments() { return comments; } /** * Sets the value of the comments property. * * @param value * allowed object is * {@link List<CommentInfo> } * */ public void setComments(List<CommentInfo> value) { this.comments = value; } }
Gaonaifeng/eLong-OpenAPI-H5-demo
nb_demo_h5/src/main/java/com/elong/nb/model/elong/CommentResult.java
Java
apache-2.0
2,314
// Copyright 2014 The Serviced 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.zenoss.app.annotations; import org.springframework.stereotype.Component; /** * Mark an object as an API implementation. */ @Component public @interface API { }
zenoss/zenoss-zapp
java/zenoss-app/src/main/java/org/zenoss/app/annotations/API.java
Java
apache-2.0
773
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v9.services; import com.google.ads.googleads.v9.resources.OperatingSystemVersionConstant; import com.google.ads.googleads.v9.services.stub.OperatingSystemVersionConstantServiceStubSettings; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link OperatingSystemVersionConstantServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li> The default service address (googleads.googleapis.com) and default port (443) are used. * <li> Credentials are acquired automatically through Application Default Credentials. * <li> Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of getOperatingSystemVersionConstant to 30 seconds: * * <pre>{@code * OperatingSystemVersionConstantServiceSettings.Builder * operatingSystemVersionConstantServiceSettingsBuilder = * OperatingSystemVersionConstantServiceSettings.newBuilder(); * operatingSystemVersionConstantServiceSettingsBuilder * .getOperatingSystemVersionConstantSettings() * .setRetrySettings( * operatingSystemVersionConstantServiceSettingsBuilder * .getOperatingSystemVersionConstantSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * OperatingSystemVersionConstantServiceSettings operatingSystemVersionConstantServiceSettings = * operatingSystemVersionConstantServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class OperatingSystemVersionConstantServiceSettings extends ClientSettings<OperatingSystemVersionConstantServiceSettings> { /** Returns the object with the settings used for calls to getOperatingSystemVersionConstant. */ public UnaryCallSettings<GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant> getOperatingSystemVersionConstantSettings() { return ((OperatingSystemVersionConstantServiceStubSettings) getStubSettings()) .getOperatingSystemVersionConstantSettings(); } public static final OperatingSystemVersionConstantServiceSettings create( OperatingSystemVersionConstantServiceStubSettings stub) throws IOException { return new OperatingSystemVersionConstantServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return OperatingSystemVersionConstantServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return OperatingSystemVersionConstantServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return OperatingSystemVersionConstantServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return OperatingSystemVersionConstantServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return OperatingSystemVersionConstantServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return OperatingSystemVersionConstantServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return OperatingSystemVersionConstantServiceStubSettings .defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected OperatingSystemVersionConstantServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for OperatingSystemVersionConstantServiceSettings. */ public static class Builder extends ClientSettings.Builder<OperatingSystemVersionConstantServiceSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(OperatingSystemVersionConstantServiceStubSettings.newBuilder(clientContext)); } protected Builder(OperatingSystemVersionConstantServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(OperatingSystemVersionConstantServiceStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(OperatingSystemVersionConstantServiceStubSettings.newBuilder()); } public OperatingSystemVersionConstantServiceStubSettings.Builder getStubSettingsBuilder() { return ((OperatingSystemVersionConstantServiceStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to getOperatingSystemVersionConstant. */ public UnaryCallSettings.Builder< GetOperatingSystemVersionConstantRequest, OperatingSystemVersionConstant> getOperatingSystemVersionConstantSettings() { return getStubSettingsBuilder().getOperatingSystemVersionConstantSettings(); } @Override public OperatingSystemVersionConstantServiceSettings build() throws IOException { return new OperatingSystemVersionConstantServiceSettings(this); } } }
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/OperatingSystemVersionConstantServiceSettings.java
Java
apache-2.0
8,198
/* * Copyright 2016 Atanas Stoychev Kanchev * 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.atanas.kanchev.testframework.appium.tests.android.browser_tests; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileBrowserType; import io.appium.java_client.remote.MobileCapabilityType; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Platform; import org.openqa.selenium.ScreenOrientation; import static com.atanas.kanchev.testframework.appium.accessors.AppiumAccessors.$appium; import static com.atanas.kanchev.testframework.selenium.accessors.SeleniumAccessors.$selenium; public class ChromeTest { @Test public void androidChromeTest() throws Exception { $appium().init().buildDefaultService(); $appium().init().startServer(); $appium().init() .setCap(MobileCapabilityType.BROWSER_NAME, MobileBrowserType.CHROME) .setCap(MobileCapabilityType.PLATFORM, Platform.ANDROID) .setCap(MobileCapabilityType.DEVICE_NAME, "ZY22398GL7") .setCap(MobileCapabilityType.PLATFORM_VERSION, "6.0.1") .setCap(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60) .setCap(MobileCapabilityType.FULL_RESET, false) .setCap(AndroidMobileCapabilityType.ANDROID_DEVICE_READY_TIMEOUT, 60) .setCap(AndroidMobileCapabilityType.ENABLE_PERFORMANCE_LOGGING, true); $appium().init().getAndroidDriver(); $selenium().goTo("https://bbc.co.uk"); $selenium().find().elementBy(By.id("idcta-link")); $appium().android().orientation().rotate(ScreenOrientation.LANDSCAPE); } }
atanaskanchev/hybrid-test-framework
test-framework-appium/src/test/java/com/atanas/kanchev/testframework/appium/tests/android/browser_tests/ChromeTest.java
Java
apache-2.0
2,204
/* * Copyright 2006-2016 Edward Smith * * 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 root.json; import root.lang.StringExtractor; /** * * @author Edward Smith * @version 0.5 * @since 0.5 */ final class JSONBoolean extends JSONValue { // <><><><><><><><><><><><><>< Class Attributes ><><><><><><><><><><><><><> private final boolean value; // <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><> JSONBoolean(final boolean value) { this.value = value; } // <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><> @Override public final void extract(final StringExtractor chars) { chars.append(this.value); } } // End JSONBoolean
macvelli/RootFramework
src/root/json/JSONBoolean.java
Java
apache-2.0
1,215
package uk.co.listpoint.context; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Context6Type. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="Context6Type"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Data Standard"/> * &lt;enumeration value="Application"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "Context6Type", namespace = "http://www.listpoint.co.uk/schemas/v6") @XmlEnum public enum Context6Type { @XmlEnumValue("Data Standard") DATA_STANDARD("Data Standard"), @XmlEnumValue("Application") APPLICATION("Application"); private final String value; Context6Type(String v) { value = v; } public String value() { return value; } public static Context6Type fromValue(String v) { for (Context6Type c: Context6Type.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
davidcarboni/listpoint-ws
src/main/java/uk/co/listpoint/context/Context6Type.java
Java
apache-2.0
1,238
package com.example.customviewdemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DragViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drag_view); } }
jianghang/CustomViewDemo
src/com/example/customviewdemo/DragViewActivity.java
Java
apache-2.0
354
package com.gentics.mesh.core.schema.field; import static com.gentics.mesh.assertj.MeshAssertions.assertThat; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBINARY; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBOOLEAN; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEBOOLEANLIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEDATE; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEDATELIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEHTML; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEHTMLLIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEMICRONODE; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATEMICRONODELIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENODE; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENODELIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENUMBER; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATENUMBERLIST; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATESTRING; import static com.gentics.mesh.core.field.FieldSchemaCreator.CREATESTRINGLIST; import static com.gentics.mesh.core.field.FieldTestHelper.NOOP; import static com.gentics.mesh.test.ElasticsearchTestMode.TRACKING; import static com.gentics.mesh.test.TestSize.FULL; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.junit.Test; import com.gentics.mesh.FieldUtil; import com.gentics.mesh.core.data.node.field.HibHtmlField; import com.gentics.mesh.core.field.html.HtmlFieldTestHelper; import com.gentics.mesh.test.MeshTestSetting; import com.gentics.mesh.util.IndexOptionHelper; @MeshTestSetting(elasticsearch = TRACKING, testSize = FULL, startServer = false) public class HtmlFieldMigrationTest extends AbstractFieldMigrationTest implements HtmlFieldTestHelper { @Test @Override public void testRemove() throws Exception { removeField(CREATEHTML, FILLTEXT, FETCH); } @Test @Override public void testChangeToBinary() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBINARY, (container, name) -> { assertThat(container.getBinary(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToBinary() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEBINARY, (container, name) -> { assertThat(container.getBinary(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToBoolean() throws Exception { changeType(CREATEHTML, FILLTRUE, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(true); }); changeType(CREATEHTML, FILLFALSE, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(false); }); changeType(CREATEHTML, FILL1, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(true); }); changeType(CREATEHTML, FILL0, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBoolean(name).getBoolean()).as(NEWFIELDVALUE).isEqualTo(false); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToBoolean() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEBOOLEAN, (container, name) -> { assertThat(container.getBoolean(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToBooleanList() throws Exception { changeType(CREATEHTML, FILLTRUE, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(true); }); changeType(CREATEHTML, FILLFALSE, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(false); }); changeType(CREATEHTML, FILL1, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(true); }); changeType(CREATEHTML, FILL0, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getBooleanList(name).getValues()).as(NEWFIELDVALUE).containsExactly(false); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToBooleanList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEBOOLEANLIST, (container, name) -> { assertThat(container.getBooleanList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToDate() throws Exception { changeType(CREATEHTML, FILL0, FETCH, CREATEDATE, (container, name) -> { assertThat(container.getDate(name)).as(NEWFIELD).isNotNull(); assertThat(container.getDate(name).getDate()).as(NEWFIELDVALUE).isEqualTo(0L); }); changeType(CREATEHTML, FILL1, FETCH, CREATEDATE, (container, name) -> { assertThat(container.getDate(name)).as(NEWFIELD).isNotNull(); // Internally timestamps are stored in miliseconds assertThat(container.getDate(name).getDate()).as(NEWFIELDVALUE).isEqualTo(1000L); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATEDATE, (container, name) -> { assertThat(container.getDate(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToDate() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEDATE, (container, name) -> { assertThat(container.getDate(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToDateList() throws Exception { changeType(CREATEHTML, FILL0, FETCH, CREATEDATELIST, (container, name) -> { assertThat(container.getDateList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getDateList(name).getValues()).as(NEWFIELDVALUE).containsExactly(0L); }); changeType(CREATEHTML, FILL1, FETCH, CREATEDATELIST, (container, name) -> { assertThat(container.getDateList(name)).as(NEWFIELD).isNotNull(); // Internally timestamps are stored in miliseconds assertThat(container.getDateList(name).getValues()).as(NEWFIELDVALUE).containsExactly(1000L); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATEDATELIST, (container, name) -> { assertThat(container.getDateList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToDateList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEDATELIST, (container, name) -> { assertThat(container.getDateList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToHtml() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATEHTML, (container, name) -> { assertThat(container.getHtml(name)).as(NEWFIELD).isNotNull(); assertThat(container.getHtml(name).getHTML()).as(NEWFIELDVALUE).isEqualTo("<b>HTML</b> content"); }); } @Test @Override public void testEmptyChangeToHtml() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEHTML, (container, name) -> { assertThat(container.getHtml(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToHtmlList() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATEHTMLLIST, (container, name) -> { assertThat(container.getHTMLList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getHTMLList(name).getValues()).as(NEWFIELDVALUE).containsExactly("<b>HTML</b> content"); }); } @Test @Override public void testEmptyChangeToHtmlList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEHTMLLIST, (container, name) -> { assertThat(container.getHTMLList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToMicronode() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATEMICRONODE, (container, name) -> { assertThat(container.getMicronode(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToMicronode() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEMICRONODE, (container, name) -> { assertThat(container.getMicronode(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToMicronodeList() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATEMICRONODELIST, (container, name) -> { assertThat(container.getMicronodeList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToMicronodeList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATEMICRONODELIST, (container, name) -> { assertThat(container.getMicronodeList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToNode() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATENODE, (container, name) -> { assertThat(container.getNode(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToNode() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATENODE, (container, name) -> { assertThat(container.getNode(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToNodeList() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATENODELIST, (container, name) -> { assertThat(container.getNodeList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToNodeList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATENODELIST, (container, name) -> { assertThat(container.getNodeList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToNumber() throws Exception { changeType(CREATEHTML, FILL0, FETCH, CREATENUMBER, (container, name) -> { assertThat(container.getNumber(name)).as(NEWFIELD).isNotNull(); assertThat(container.getNumber(name).getNumber().longValue()).as(NEWFIELDVALUE).isEqualTo(0L); }); changeType(CREATEHTML, FILL1, FETCH, CREATENUMBER, (container, name) -> { assertThat(container.getNumber(name)).as(NEWFIELD).isNotNull(); assertThat(container.getNumber(name).getNumber().longValue()).as(NEWFIELDVALUE).isEqualTo(1L); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATENUMBER, (container, name) -> { assertThat(container.getNumber(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToNumber() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATENUMBER, (container, name) -> { assertThat(container.getNumber(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToNumberList() throws Exception { changeType(CREATEHTML, FILL0, FETCH, CREATENUMBERLIST, (container, name) -> { assertThat(container.getNumberList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getNumberList(name).getValues()).as(NEWFIELDVALUE).containsExactly(0L); }); changeType(CREATEHTML, FILL1, FETCH, CREATENUMBERLIST, (container, name) -> { assertThat(container.getNumberList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getNumberList(name).getValues()).as(NEWFIELDVALUE).containsExactly(1L); }); changeType(CREATEHTML, FILLTEXT, FETCH, CREATENUMBERLIST, (container, name) -> { assertThat(container.getNumberList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testEmptyChangeToNumberList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATENUMBERLIST, (container, name) -> { assertThat(container.getNumberList(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToString() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATESTRING, (container, name) -> { assertThat(container.getString(name)).as(NEWFIELD).isNotNull(); assertThat(container.getString(name).getString()).as(NEWFIELDVALUE).isEqualTo("<b>HTML</b> content"); }); } @Test @Override public void testEmptyChangeToString() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATESTRING, (container, name) -> { assertThat(container.getString(name)).as(NEWFIELD).isNull(); }); } @Test @Override public void testChangeToStringList() throws Exception { changeType(CREATEHTML, FILLTEXT, FETCH, CREATESTRINGLIST, (container, name) -> { assertThat(container.getStringList(name)).as(NEWFIELD).isNotNull(); assertThat(container.getStringList(name).getValues()).as(NEWFIELDVALUE).containsExactly("<b>HTML</b> content"); }); } @Test @Override public void testEmptyChangeToStringList() throws Exception { changeType(CREATEHTML, NOOP, FETCH, CREATESTRINGLIST, (container, name) -> { assertThat(container.getStringList(name)).as(NEWFIELD).isNull(); }); } @Test public void testIndexOptionAddRaw() throws InterruptedException, ExecutionException, TimeoutException { changeType(CREATEHTML, FILLLONGTEXT, FETCH, name -> FieldUtil.createHtmlFieldSchema(name).setElasticsearch(IndexOptionHelper.getRawFieldOption()), (container, name) -> { HibHtmlField htmlField = container.getHtml(name); assertEquals("The html field should not be truncated.", 40_000, htmlField.getHTML().length()); waitForSearchIdleEvent(); assertThat(trackingSearchProvider()).recordedStoreEvents(1); }); } }
gentics/mesh
tests/tests-core/src/main/java/com/gentics/mesh/core/schema/field/HtmlFieldMigrationTest.java
Java
apache-2.0
14,181
/* * 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 redis.common.container; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.common.config.FlinkJedisClusterConfig; import redis.common.config.FlinkJedisConfigBase; import redis.common.config.FlinkJedisPoolConfig; import redis.common.config.FlinkJedisSentinelConfig; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisSentinelPool; import redis.common.container.*; import redis.common.container.RedisCommandsContainer; import redis.common.container.RedisContainer; import java.util.Objects; /** * The builder for {@link redis.common.container.RedisCommandsContainer}. */ public class RedisCommandsContainerBuilder { /** * Initialize the {@link redis.common.container.RedisCommandsContainer} based on the instance type. * @param flinkJedisConfigBase configuration base * @return @throws IllegalArgumentException if jedisPoolConfig, jedisClusterConfig and jedisSentinelConfig are all null */ public static redis.common.container.RedisCommandsContainer build(FlinkJedisConfigBase flinkJedisConfigBase){ if(flinkJedisConfigBase instanceof FlinkJedisPoolConfig){ FlinkJedisPoolConfig flinkJedisPoolConfig = (FlinkJedisPoolConfig) flinkJedisConfigBase; return RedisCommandsContainerBuilder.build(flinkJedisPoolConfig); } else if (flinkJedisConfigBase instanceof FlinkJedisClusterConfig) { FlinkJedisClusterConfig flinkJedisClusterConfig = (FlinkJedisClusterConfig) flinkJedisConfigBase; return RedisCommandsContainerBuilder.build(flinkJedisClusterConfig); } else if (flinkJedisConfigBase instanceof FlinkJedisSentinelConfig) { FlinkJedisSentinelConfig flinkJedisSentinelConfig = (FlinkJedisSentinelConfig) flinkJedisConfigBase; return RedisCommandsContainerBuilder.build(flinkJedisSentinelConfig); } else { throw new IllegalArgumentException("Jedis configuration not found"); } } /** * Builds container for single Redis environment. * * @param jedisPoolConfig configuration for JedisPool * @return container for single Redis environment * @throws NullPointerException if jedisPoolConfig is null */ public static redis.common.container.RedisCommandsContainer build(FlinkJedisPoolConfig jedisPoolConfig) { Objects.requireNonNull(jedisPoolConfig, "Redis pool config should not be Null"); GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxIdle(jedisPoolConfig.getMaxIdle()); genericObjectPoolConfig.setMaxTotal(jedisPoolConfig.getMaxTotal()); genericObjectPoolConfig.setMinIdle(jedisPoolConfig.getMinIdle()); JedisPool jedisPool = new JedisPool(genericObjectPoolConfig, jedisPoolConfig.getHost(), jedisPoolConfig.getPort(), jedisPoolConfig.getConnectionTimeout(), jedisPoolConfig.getPassword(), jedisPoolConfig.getDatabase()); return new redis.common.container.RedisContainer(jedisPool); } /** * Builds container for Redis Cluster environment. * * @param jedisClusterConfig configuration for JedisCluster * @return container for Redis Cluster environment * @throws NullPointerException if jedisClusterConfig is null */ public static redis.common.container.RedisCommandsContainer build(FlinkJedisClusterConfig jedisClusterConfig) { Objects.requireNonNull(jedisClusterConfig, "Redis cluster config should not be Null"); GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxIdle(jedisClusterConfig.getMaxIdle()); genericObjectPoolConfig.setMaxTotal(jedisClusterConfig.getMaxTotal()); genericObjectPoolConfig.setMinIdle(jedisClusterConfig.getMinIdle()); JedisCluster jedisCluster = new JedisCluster(jedisClusterConfig.getNodes(), jedisClusterConfig.getConnectionTimeout(), jedisClusterConfig.getMaxRedirections(), genericObjectPoolConfig); return new redis.common.container.RedisClusterContainer(jedisCluster); } /** * Builds container for Redis Sentinel environment. * * @param jedisSentinelConfig configuration for JedisSentinel * @return container for Redis sentinel environment * @throws NullPointerException if jedisSentinelConfig is null */ public static RedisCommandsContainer build(FlinkJedisSentinelConfig jedisSentinelConfig) { Objects.requireNonNull(jedisSentinelConfig, "Redis sentinel config should not be Null"); GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxIdle(jedisSentinelConfig.getMaxIdle()); genericObjectPoolConfig.setMaxTotal(jedisSentinelConfig.getMaxTotal()); genericObjectPoolConfig.setMinIdle(jedisSentinelConfig.getMinIdle()); JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(jedisSentinelConfig.getMasterName(), jedisSentinelConfig.getSentinels(), genericObjectPoolConfig, jedisSentinelConfig.getConnectionTimeout(), jedisSentinelConfig.getSoTimeout(), jedisSentinelConfig.getPassword(), jedisSentinelConfig.getDatabase()); return new RedisContainer(jedisSentinelPool); } }
eltitopera/TFM
manager/src/src/main/java/redis/common/container/RedisCommandsContainerBuilder.java
Java
apache-2.0
6,212
package fundamental.games.metropolis.connection.bluetooth; import android.bluetooth.BluetoothSocket; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.UUID; import fundamental.games.metropolis.connection.global.MessagesQueue; import fundamental.games.metropolis.connection.serializable.PlayerInitData; import fundamental.games.metropolis.global.WidgetsData; /** * Created by regair on 27.05.15. */ public class BluetoothServerConnection extends BluetoothConnection { private ObjectOutputStream writer; private ObjectInputStream reader; //******************************** public BluetoothServerConnection(BluetoothSocket socket, MessagesQueue<Serializable> queue, UUID uuid) { super(socket, queue, uuid); this.queue = new MessagesQueue<>(); deviceName = "SERVER"; } //******************************** @Override public void run() { working = true; } //******************************** @Override public void stopConnection() { super.stopConnection(); BluetoothServer.getInstance().removeConnection(this); } public MessagesQueue<Serializable> getQueue() { return queue; } //********************************** public void sendMessage(Serializable message) { if(message instanceof PlayerInitData) { setID(((PlayerInitData)message).ID); //ID = ((PlayerInitData)message).ID; BluetoothServer.getInstance().getIncomingQueue().addMessage(new PlayerInitData(WidgetsData.playerName, ID)); return; } queue.addMessage(message); } @Override public void setID(int id) { super.setID(id); BluetoothConnection.humanID = id; } }
Ragnarokma/metropolis
src/main/java/fundamental/games/metropolis/connection/bluetooth/BluetoothServerConnection.java
Java
apache-2.0
1,850
package bookshop2.client.paymentService; import java.util.List; import org.aries.message.Message; import org.aries.message.MessageInterceptor; import org.aries.util.ExceptionUtil; import bookshop2.Payment; @SuppressWarnings("serial") public class PaymentServiceInterceptor extends MessageInterceptor<PaymentService> implements PaymentService { @Override public List<Payment> getAllPaymentRecords() { try { log.info("#### [admin]: getAllPaymentRecords() sending..."); Message request = createMessage("getAllPaymentRecords"); Message response = getProxy().invoke(request); List<Payment> result = response.getPart("result"); return result; } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public Payment getPaymentRecordById(Long id) { try { log.info("#### [admin]: getPaymentRecordById() sending..."); Message request = createMessage("getPaymentRecordById"); request.addPart("id", id); Message response = getProxy().invoke(request); Payment result = response.getPart("result"); return result; } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public List<Payment> getPaymentRecordsByPage(int pageIndex, int pageSize) { try { log.info("#### [admin]: getPaymentRecordsByPage() sending..."); Message request = createMessage("getPaymentRecordsByPage"); request.addPart("pageIndex", pageIndex); request.addPart("pageSize", pageSize); Message response = getProxy().invoke(request); List<Payment> result = response.getPart("result"); return result; } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public Long addPaymentRecord(Payment payment) { try { log.info("#### [admin]: addPaymentRecord() sending..."); Message request = createMessage("addPaymentRecord"); request.addPart("payment", payment); Message response = getProxy().invoke(request); Long result = response.getPart("result"); return result; } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public void savePaymentRecord(Payment payment) { try { log.info("#### [admin]: savePaymentRecord() sending..."); Message request = createMessage("savePaymentRecord"); request.addPart("payment", payment); getProxy().invoke(request); } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public void removeAllPaymentRecords() { try { log.info("#### [admin]: removeAllPaymentRecords() sending..."); Message request = createMessage("removeAllPaymentRecords"); getProxy().invoke(request); } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public void removePaymentRecord(Payment payment) { try { log.info("#### [admin]: removePaymentRecord() sending..."); Message request = createMessage("removePaymentRecord"); request.addPart("payment", payment); getProxy().invoke(request); } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } @Override public void importPaymentRecords() { try { log.info("#### [admin]: importPaymentRecords() sending..."); Message request = createMessage("importPaymentRecords"); getProxy().invoke(request); } catch (Exception e) { throw ExceptionUtil.rewrap(e); } } }
tfisher1226/ARIES
bookshop2/bookshop2-client/src/main/java/bookshop2/client/paymentService/PaymentServiceInterceptor.java
Java
apache-2.0
3,276
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.redshift.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/DeleteAuthenticationProfile" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteAuthenticationProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the authentication profile to delete. * </p> */ private String authenticationProfileName; /** * <p> * The name of the authentication profile to delete. * </p> * * @param authenticationProfileName * The name of the authentication profile to delete. */ public void setAuthenticationProfileName(String authenticationProfileName) { this.authenticationProfileName = authenticationProfileName; } /** * <p> * The name of the authentication profile to delete. * </p> * * @return The name of the authentication profile to delete. */ public String getAuthenticationProfileName() { return this.authenticationProfileName; } /** * <p> * The name of the authentication profile to delete. * </p> * * @param authenticationProfileName * The name of the authentication profile to delete. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteAuthenticationProfileRequest withAuthenticationProfileName(String authenticationProfileName) { setAuthenticationProfileName(authenticationProfileName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAuthenticationProfileName() != null) sb.append("AuthenticationProfileName: ").append(getAuthenticationProfileName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteAuthenticationProfileRequest == false) return false; DeleteAuthenticationProfileRequest other = (DeleteAuthenticationProfileRequest) obj; if (other.getAuthenticationProfileName() == null ^ this.getAuthenticationProfileName() == null) return false; if (other.getAuthenticationProfileName() != null && other.getAuthenticationProfileName().equals(this.getAuthenticationProfileName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAuthenticationProfileName() == null) ? 0 : getAuthenticationProfileName().hashCode()); return hashCode; } @Override public DeleteAuthenticationProfileRequest clone() { return (DeleteAuthenticationProfileRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/DeleteAuthenticationProfileRequest.java
Java
apache-2.0
4,104
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeu.chat.client.core; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import codeu.chat.common.BasicView; import codeu.chat.common.User; import codeu.chat.util.Uuid; import codeu.chat.util.connections.ConnectionSource; public final class Context { private final BasicView view; private final Controller controller; public Context(ConnectionSource source) { this.view = new View(source); this.controller = new Controller(source); } public UserContext create(String name) { final User user = controller.newUser(name); return user == null ? null : new UserContext(user, view, controller); } public Iterable<UserContext> allUsers() { final Collection<UserContext> users = new ArrayList<>(); for (final User user : view.getUsers()) { users.add(new UserContext(user, view, controller)); } return users; } }
crepric/codeu_mirrored_test_1
src/codeu/chat/client/core/Context.java
Java
apache-2.0
1,510
/* * Copyright 2015-2017 EMBL - European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ebi.eva.runner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobOperator; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import uk.ac.ebi.eva.pipeline.runner.ManageJobsUtils; import uk.ac.ebi.eva.test.configuration.AsynchronousBatchTestConfiguration; import uk.ac.ebi.eva.test.utils.AbstractJobRestartUtils; /** * Test to check if the ManageJobUtils.markLastJobAsFailed let us restart a job redoing all the steps. */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = {AsynchronousBatchTestConfiguration.class}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class JobRestartForceTest extends AbstractJobRestartUtils { // Wait until the job has been launched properly. The launch operation is not transactional, and other // instances of the same job with the same parameter can throw exceptions in this interval. public static final int INITIALIZE_JOB_SLEEP = 100; public static final int STEP_TIME_DURATION = 1000; public static final int WAIT_FOR_JOB_TO_END = 2000; @Autowired private JobOperator jobOperator; @Test public void forceJobFailureEnsuresCleanRunEvenIfStepsNotRestartables() throws Exception { Job job = getTestJob(getQuickStep(false), getWaitingStep(false, STEP_TIME_DURATION)); JobLauncherTestUtils jobLauncherTestUtils = getJobLauncherTestUtils(job); JobExecution jobExecution = launchJob(jobLauncherTestUtils); Thread.sleep(INITIALIZE_JOB_SLEEP); jobOperator.stop(jobExecution.getJobId()); Thread.sleep(WAIT_FOR_JOB_TO_END); ManageJobsUtils.markLastJobAsFailed(getJobRepository(), job.getName(), new JobParameters()); jobExecution = launchJob(jobLauncherTestUtils); Thread.sleep(WAIT_FOR_JOB_TO_END); Assert.assertFalse(jobExecution.getStepExecutions().isEmpty()); } }
cyenyxe/eva-pipeline
src/test/java/uk/ac/ebi/eva/runner/JobRestartForceTest.java
Java
apache-2.0
2,993
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert // Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2020.03.13 um 12:48:52 PM CET // package net.opengis.ows._1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * Complete reference to a remote or local resource, allowing including metadata about that resource. * * <p>Java-Klasse für ReferenceType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="ReferenceType"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://www.opengis.net/ows/1.1}AbstractReferenceBaseType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://www.opengis.net/ows/1.1}Identifier" minOccurs="0"/&gt; * &lt;element ref="{http://www.opengis.net/ows/1.1}Abstract" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="Format" type="{http://www.opengis.net/ows/1.1}MimeType" minOccurs="0"/&gt; * &lt;element ref="{http://www.opengis.net/ows/1.1}Metadata" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ReferenceType", propOrder = { "identifier", "_abstract", "format", "metadata" }) @XmlSeeAlso({ ServiceReferenceType.class }) public class ReferenceType extends AbstractReferenceBaseType { @XmlElement(name = "Identifier") protected CodeType identifier; @XmlElement(name = "Abstract") protected List<LanguageStringType> _abstract; @XmlElement(name = "Format") protected String format; @XmlElement(name = "Metadata") protected List<MetadataType> metadata; /** * Optional unique identifier of the referenced resource. * * @return * possible object is * {@link CodeType } * */ public CodeType getIdentifier() { return identifier; } /** * Legt den Wert der identifier-Eigenschaft fest. * * @param value * allowed object is * {@link CodeType } * */ public void setIdentifier(CodeType value) { this.identifier = value; } public boolean isSetIdentifier() { return (this.identifier!= null); } /** * Gets the value of the abstract property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the abstract property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAbstract().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LanguageStringType } * * */ public List<LanguageStringType> getAbstract() { if (_abstract == null) { _abstract = new ArrayList<LanguageStringType>(); } return this._abstract; } public boolean isSetAbstract() { return ((this._abstract!= null)&&(!this._abstract.isEmpty())); } public void unsetAbstract() { this._abstract = null; } /** * Ruft den Wert der format-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getFormat() { return format; } /** * Legt den Wert der format-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setFormat(String value) { this.format = value; } public boolean isSetFormat() { return (this.format!= null); } /** * Optional unordered list of additional metadata about this resource. A list of optional metadata elements for this ReferenceType could be specified in the Implementation Specification for each use of this type in a specific OWS. Gets the value of the metadata property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the metadata property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMetadata().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MetadataType } * * */ public List<MetadataType> getMetadata() { if (metadata == null) { metadata = new ArrayList<MetadataType>(); } return this.metadata; } public boolean isSetMetadata() { return ((this.metadata!= null)&&(!this.metadata.isEmpty())); } public void unsetMetadata() { this.metadata = null; } public void setAbstract(List<LanguageStringType> value) { this._abstract = value; } public void setMetadata(List<MetadataType> value) { this.metadata = value; } }
3dcitydb/web-feature-service
src-gen/main/java/net/opengis/ows/_1/ReferenceType.java
Java
apache-2.0
5,813
package io.github.varvelworld.var.ioc.core.annotation.meta.factory; import io.github.varvelworld.var.ioc.core.annotation.Resource; import io.github.varvelworld.var.ioc.core.meta.ParamResourceMeta; import io.github.varvelworld.var.ioc.core.meta.factory.ParamResourceMetaFactory; import java.lang.reflect.Parameter; /** * Created by luzhonghao on 2016/12/4. */ public class AnnotationParamResourceMetaFactoryImpl implements ParamResourceMetaFactory { private final ParamResourceMeta paramResourceMeta; public AnnotationParamResourceMetaFactoryImpl(Parameter parameter) { this(parameter, parameter.getAnnotation(Resource.class)); } public AnnotationParamResourceMetaFactoryImpl(Parameter parameter, Resource annotation) { String id = annotation.value(); if(id.isEmpty()) { if(parameter.isNamePresent()){ id = parameter.getName(); } else { throw new RuntimeException("id is empty"); } } this.paramResourceMeta = new ParamResourceMeta(id); } @Override public ParamResourceMeta paramResourceMeta() { return paramResourceMeta; } }
varvelworld/var-ioc
src/main/java/io/github/varvelworld/var/ioc/core/annotation/meta/factory/AnnotationParamResourceMetaFactoryImpl.java
Java
apache-2.0
1,193
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor.juel; import javax.naming.Context; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.jndi.JndiContext; import static org.apache.camel.language.juel.JuelExpression.el; /** * @version */ public class SimulatorTest extends ContextTestSupport { protected Context createJndiContext() throws Exception { JndiContext answer = new JndiContext(); answer.bind("foo", new MyBean("foo")); answer.bind("bar", new MyBean("bar")); return answer; } public void testReceivesFooResponse() throws Exception { assertRespondsWith("foo", "Bye said foo"); } public void testReceivesBarResponse() throws Exception { assertRespondsWith("bar", "Bye said bar"); } protected void assertRespondsWith(final String value, String containedText) throws InvalidPayloadException { Exchange response = template.request("direct:a", new Processor() { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setBody("answer"); in.setHeader("cheese", value); } }); assertNotNull("Should receive a response!", response); String text = ExchangeHelper.getMandatoryOutBody(response, String.class); assertStringContains(text, containedText); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example from("direct:a"). recipientList(el("bean:${in.headers.cheese}")); // END SNIPPET: example } }; } public static class MyBean { private String value; public MyBean(String value) { this.value = value; } public String doSomething(String in) { return "Bye said " + value; } } }
everttigchelaar/camel-svn
components/camel-juel/src/test/java/org/apache/camel/processor/juel/SimulatorTest.java
Java
apache-2.0
3,124
package com.stf.bj.app.game.players; import java.util.Random; import com.stf.bj.app.game.bj.Spot; import com.stf.bj.app.game.server.Event; import com.stf.bj.app.game.server.EventType; import com.stf.bj.app.settings.AppSettings; import com.stf.bj.app.strategy.FullStrategy; public class RealisticBot extends BasicBot { private enum InsuranceStrategy { NEVER, EVEN_MONEY_ONLY, GOOD_HANDS_ONLY, RARELY, OFTEN; } private enum PlayAbility { PERFECT, NOOB, RANDOM; } private enum BetChanging { NEVER, RANDOM; } private final InsuranceStrategy insuranceStrategy; private final PlayAbility playAbility; private final Random r; private double wager = -1.0; private final BetChanging betChanging; private boolean insurancePlay = false; private boolean calculatedInsurancePlay = false; private boolean messUpNextPlay = false; public RealisticBot(AppSettings settings, FullStrategy strategy, Random r, Spot s) { super(settings, strategy, r, s); if (r == null) { r = new Random(System.currentTimeMillis()); } this.r = r; insuranceStrategy = InsuranceStrategy.values()[r.nextInt(InsuranceStrategy.values().length)]; playAbility = PlayAbility.values()[r.nextInt(PlayAbility.values().length)]; setBaseBet(); betChanging = BetChanging.RANDOM; } @Override public void sendEvent(Event e) { super.sendEvent(e); if (e.getType() == EventType.DECK_SHUFFLED) { if (betChanging == BetChanging.RANDOM && r.nextInt(2) == 0) { wager = 5; } } } @Override public double getWager() { if (delay > 0) { delay--; return -1; } return wager; } private void setBaseBet() { int rInt = r.nextInt(12); if (rInt < 6) { wager = 5.0 * (1 + rInt); } else if (rInt < 9) { wager = 10.0; } else { wager = 5.0; } } @Override public boolean getInsurancePlay() { if (insuranceStrategy == InsuranceStrategy.NEVER) { return false; } if (!calculatedInsurancePlay) { insurancePlay = calculateInsurancePlay(); calculatedInsurancePlay = true; } return insurancePlay; } private boolean calculateInsurancePlay() { switch (insuranceStrategy) { case EVEN_MONEY_ONLY: return getHandSoftTotal(0) == 21; case GOOD_HANDS_ONLY: return getHandSoftTotal(0) > 16 + r.nextInt(3); case OFTEN: return r.nextInt(2) == 0; case RARELY: return r.nextInt(5) == 0; default: throw new IllegalStateException(); } } @Override public Play getMove(int handIndex, boolean canDouble, boolean canSplit, boolean canSurrender) { if (delay > 0) { delay--; return null; } Play play = super.getMove(handIndex, canDouble, canSplit, canSurrender); if (messUpNextPlay) { if (play != Play.SPLIT && canSplit) { play = Play.SPLIT; } else if (play != Play.DOUBLEDOWN && canSplit) { play = Play.DOUBLEDOWN; } else if (play == Play.STAND) { play = Play.HIT; } else { play = Play.STAND; } } return play; } @Override protected void reset() { super.reset(); calculatedInsurancePlay = false; int random = r.nextInt(10); if (playAbility == PlayAbility.RANDOM) { messUpNextPlay = (random < 2); } if ((random == 2 || random == 3) && betChanging == BetChanging.RANDOM) { wager += 5; } else if (random == 4 && betChanging == BetChanging.RANDOM) { if (wager > 6) { wager -= 5; } } } }
Boxxy/Blackjack
core/src/com/stf/bj/app/game/players/RealisticBot.java
Java
apache-2.0
3,337
package me.marcosassuncao.servsim.job; import me.marcosassuncao.servsim.profile.RangeList; import com.google.common.base.MoreObjects; /** * {@link Reservation} represents a resource reservation request * made by a customer to reserve a given number of resources * from a provider. * * @see WorkUnit * @see DefaultWorkUnit * * @author Marcos Dias de Assuncao */ public class Reservation extends DefaultWorkUnit { private long reqStartTime = WorkUnit.TIME_NOT_SET; private RangeList rangeList; /** * Creates a reservation request to start at * <code>startTime</code> and with the given duration. * @param startTime the requested start time for the reservation * @param duration the duration of the reservation * @param numResources number of required resources */ public Reservation(long startTime, long duration, int numResources) { super(duration); super.setNumReqResources(numResources); this.reqStartTime = startTime; } /** * Creates a reservation request to start at * <code>startTime</code> and with the given duration and priority * @param startTime the requested start time for the reservation * @param duration the duration of the reservation * @param numResources the number of resources to be reserved * @param priority the reservation priority */ public Reservation(long startTime, long duration, int numResources, int priority) { super(duration, priority); super.setNumReqResources(numResources); this.reqStartTime = startTime; } /** * Returns the start time requested by this reservation * @return the requested start time */ public long getRequestedStartTime() { return reqStartTime; } /** * Sets the ranges of reserved resources * @param ranges the ranges of resources allocated for the reservation * @return <code>true</code> if the ranges have been set correctly, * <code>false</code> otherwise. */ public boolean setResourceRanges(RangeList ranges) { if (this.rangeList != null) { return false; } this.rangeList = ranges; return true; } /** * Gets the ranges of reserved resources * @return the ranges of reserved resources */ public RangeList getResourceRanges() { return rangeList; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", getId()) .add("submission time", getSubmitTime()) .add("start time", getStartTime()) .add("finish time", getFinishTime()) .add("duration", getDuration()) .add("priority", getPriority()) .add("status", getStatus()) .add("resources", rangeList) .toString(); } }
assuncaomarcos/servsim
src/main/java/me/marcosassuncao/servsim/job/Reservation.java
Java
apache-2.0
2,646
/* * Copyright (c) 2016, baihw (javakf@163.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * */ package com.yoya.rdf.router; /** * Created by baihw on 16-6-13. * * 统一的服务请求处理器规范接口,此接口用于标识类文件为请求处理器实现类,无必须实现的方法。 * * 实现类中所有符合public void xxx( IRequest request, IResponse response )签名规则的方法都将被自动注册到对应的请求处理器中。 * * 如下所示: * * public void login( IRequest request, IResponse response ){}; * * public void logout( IRequest request, IResponse response ){} ; * * 上边的login, logout将被自动注册到请求处理器路径中。 * * 假如类名为LoginHnadler, 则注册的处理路径为:/Loginhandler/login, /Loginhandler/logout. * * 注意:大小写敏感。 * */ public interface IRequestHandler{ /** * 当请求中没有明确指定处理方法时,默认执行的请求处理方法。 * * @param request 请求对象 * @param response 响应对象 */ void handle( IRequest request, IResponse response ); } // end class
javakf/rdf
src/main/java/com/yoya/rdf/router/IRequestHandler.java
Java
apache-2.0
1,692
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.spring.test.servicetask; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.activiti.engine.impl.test.JobTestHelper; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.test.Deployment; import org.activiti.spring.impl.test.SpringActivitiTestCase; import org.springframework.test.context.ContextConfiguration; /** */ @ContextConfiguration("classpath:org/activiti/spring/test/servicetask/servicetaskSpringTest-context.xml") public class ServiceTaskSpringDelegationTest extends SpringActivitiTestCase { private void cleanUp() { List<org.activiti.engine.repository.Deployment> deployments = repositoryService.createDeploymentQuery().list(); for (org.activiti.engine.repository.Deployment deployment : deployments) { repositoryService.deleteDeployment(deployment.getId(), true); } } @Override public void tearDown() { cleanUp(); } @Deployment public void testDelegateExpression() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean"); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine"); assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking"); } @Deployment public void testAsyncDelegateExpression() throws Exception { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("delegateExpressionToSpringBean"); assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue(); waitForJobExecutorToProcessAllJobs(5000, 500); Thread.sleep(1000); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("Activiti BPMN 2.0 process engine"); assertThat(runtimeService.getVariable(procInst.getId(), "fieldInjection")).isEqualTo("fieldInjectionWorking"); } @Deployment public void testMethodExpressionOnSpringBean() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean"); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE"); } @Deployment public void testAsyncMethodExpressionOnSpringBean() { ProcessInstance procInst = runtimeService.startProcessInstanceByKey("methodExpressionOnSpringBean"); assertThat(JobTestHelper.areJobsAvailable(managementService)).isTrue(); waitForJobExecutorToProcessAllJobs(5000, 500); assertThat(runtimeService.getVariable(procInst.getId(), "myVar")).isEqualTo("ACTIVITI BPMN 2.0 PROCESS ENGINE"); } @Deployment public void testExecutionAndTaskListenerDelegationExpression() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("executionAndTaskListenerDelegation"); assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerVar")).isEqualTo("working"); assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerVar")).isEqualTo("working"); assertThat(runtimeService.getVariable(processInstance.getId(), "executionListenerField")).isEqualTo("executionListenerInjection"); assertThat(runtimeService.getVariable(processInstance.getId(), "taskListenerField")).isEqualTo("taskListenerInjection"); } }
Activiti/Activiti
activiti-core/activiti-spring/src/test/java/org/activiti/spring/test/servicetask/ServiceTaskSpringDelegationTest.java
Java
apache-2.0
4,086
/** * <copyright> * </copyright> * * $Id$ */ package de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Cpu_usage; import de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.Sys_info_systeminfoPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Cpu usage</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getEContainer_cpu_usage <em>EContainer cpu usage</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getReal <em>Real</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUser <em>User</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getSys <em>Sys</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.impl.Cpu_usageImpl#getUnit <em>Unit</em>}</li> * </ul> * </p> * * @generated */ public class Cpu_usageImpl extends EObjectImpl implements Cpu_usage { /** * The default value of the '{@link #getReal() <em>Real</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReal() * @generated * @ordered */ protected static final double REAL_EDEFAULT = 0.0; /** * The cached value of the '{@link #getReal() <em>Real</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReal() * @generated * @ordered */ protected double real = REAL_EDEFAULT; /** * The default value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected static final double USER_EDEFAULT = 0.0; /** * The cached value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected double user = USER_EDEFAULT; /** * The default value of the '{@link #getSys() <em>Sys</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSys() * @generated * @ordered */ protected static final double SYS_EDEFAULT = 0.0; /** * The cached value of the '{@link #getSys() <em>Sys</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSys() * @generated * @ordered */ protected double sys = SYS_EDEFAULT; /** * The default value of the '{@link #getUnit() <em>Unit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUnit() * @generated * @ordered */ protected static final String UNIT_EDEFAULT = null; /** * The cached value of the '{@link #getUnit() <em>Unit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUnit() * @generated * @ordered */ protected String unit = UNIT_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Cpu_usageImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Sys_info_systeminfoPackage.Literals.CPU_USAGE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System getEContainer_cpu_usage() { if (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE) return null; return (de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)eContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newEContainer_cpu_usage, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEContainer_cpu_usage(de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System newEContainer_cpu_usage) { if (newEContainer_cpu_usage != eInternalContainer() || (eContainerFeatureID() != Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE && newEContainer_cpu_usage != null)) { if (EcoreUtil.isAncestor(this, newEContainer_cpu_usage)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newEContainer_cpu_usage != null) msgs = ((InternalEObject)newEContainer_cpu_usage).eInverseAdd(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs); msgs = basicSetEContainer_cpu_usage(newEContainer_cpu_usage, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE, newEContainer_cpu_usage, newEContainer_cpu_usage)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getReal() { return real; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReal(double newReal) { double oldReal = real; real = newReal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__REAL, oldReal, real)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getUser() { return user; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUser(double newUser) { double oldUser = user; user = newUser; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__USER, oldUser, user)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getSys() { return sys; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSys(double newSys) { double oldSys = sys; sys = newSys; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__SYS, oldSys, sys)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getUnit() { return unit; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUnit(String newUnit) { String oldUnit = unit; unit = newUnit; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Sys_info_systeminfoPackage.CPU_USAGE__UNIT, oldUnit, unit)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return basicSetEContainer_cpu_usage(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return eInternalContainer().eInverseRemove(this, Sys_info_systeminfoPackage.SYSTEM__CPU_USAGE, de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return getEContainer_cpu_usage(); case Sys_info_systeminfoPackage.CPU_USAGE__REAL: return getReal(); case Sys_info_systeminfoPackage.CPU_USAGE__USER: return getUser(); case Sys_info_systeminfoPackage.CPU_USAGE__SYS: return getSys(); case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: return getUnit(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: setReal((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__USER: setUser((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: setSys((Double)newValue); return; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: setUnit((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: setEContainer_cpu_usage((de.hub.clickwatch.specificmodels.brn.sys_info_systeminfo.System)null); return; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: setReal(REAL_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__USER: setUser(USER_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: setSys(SYS_EDEFAULT); return; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: setUnit(UNIT_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Sys_info_systeminfoPackage.CPU_USAGE__ECONTAINER_CPU_USAGE: return getEContainer_cpu_usage() != null; case Sys_info_systeminfoPackage.CPU_USAGE__REAL: return real != REAL_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__USER: return user != USER_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__SYS: return sys != SYS_EDEFAULT; case Sys_info_systeminfoPackage.CPU_USAGE__UNIT: return UNIT_EDEFAULT == null ? unit != null : !UNIT_EDEFAULT.equals(unit); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (real: "); result.append(real); result.append(", user: "); result.append(user); result.append(", sys: "); result.append(sys); result.append(", unit: "); result.append(unit); result.append(')'); return result.toString(); } } //Cpu_usageImpl
markus1978/clickwatch
analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/sys_info_systeminfo/impl/Cpu_usageImpl.java
Java
apache-2.0
14,073
/** * * Copyright 2016 David Strawn * * 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 strawn.longleaf.relay.util; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /** * * @author David Strawn * * This class loads configuration from the file system. * */ public class RelayConfigLoader { private static final String serverConfigLocation = "./resources/serverconfig.properties"; private static final String clientConfigLocation = "./resources/clientconfig.properties"; private final Properties properties; public RelayConfigLoader() { properties = new Properties(); } public void loadServerConfig() throws IOException { loadConfigFromPath(serverConfigLocation); } public void loadClientConfig() throws IOException { loadConfigFromPath(clientConfigLocation); } /** * Use this method if you want to use a different location for the configuration. * @param configFileLocation - location of the configuration file * @throws IOException */ public void loadConfigFromPath(String configFileLocation) throws IOException { FileInputStream fileInputStream = new FileInputStream(configFileLocation); properties.load(fileInputStream); fileInputStream.close(); } public int getPort() { return Integer.parseInt(properties.getProperty("port")); } public String getHost() { return properties.getProperty("host"); } }
strontian/longleaf-relay
src/main/java/strawn/longleaf/relay/util/RelayConfigLoader.java
Java
apache-2.0
2,074
/** * 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.oozie.executor.jpa; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.oozie.CoordinatorActionBean; import org.apache.oozie.CoordinatorJobBean; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.CoordinatorJob; import org.apache.oozie.local.LocalOozie; import org.apache.oozie.service.JPAService; import org.apache.oozie.service.Services; import org.apache.oozie.test.XDataTestCase; import org.apache.oozie.util.XmlUtils; public class TestCoordActionGetForStartJPAExecutor extends XDataTestCase { Services services; @Override protected void setUp() throws Exception { super.setUp(); services = new Services(); services.init(); cleanUpDBTables(); } @Override protected void tearDown() throws Exception { services.destroy(); super.tearDown(); } public void testCoordActionGet() throws Exception { int actionNum = 1; String errorCode = "000"; String errorMessage = "Dummy"; String resourceXmlName = "coord-action-get.xml"; CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false); CoordinatorActionBean action = createCoordAction(job.getId(), actionNum, CoordinatorAction.Status.WAITING, resourceXmlName, 0); // Add extra attributes for action action.setSlaXml(XDataTestCase.slaXml); action.setErrorCode(errorCode); action.setErrorMessage(errorMessage); // Insert the action insertRecordCoordAction(action); Path appPath = new Path(getFsTestCaseDir(), "coord"); String actionXml = getCoordActionXml(appPath, resourceXmlName); Configuration conf = getCoordConf(appPath); // Pass the expected values _testGetForStartX(action.getId(), job.getId(), CoordinatorAction.Status.WAITING, 0, action.getId() + "_E", XDataTestCase.slaXml, resourceXmlName, XmlUtils.prettyPrint(conf).toString(), actionXml, errorCode, errorMessage); } private void _testGetForStartX(String actionId, String jobId, CoordinatorAction.Status status, int pending, String extId, String slaXml, String resourceXmlName, String createdConf, String actionXml, String errorCode, String errorMessage) throws Exception { try { JPAService jpaService = Services.get().get(JPAService.class); assertNotNull(jpaService); CoordActionGetForStartJPAExecutor actionGetCmd = new CoordActionGetForStartJPAExecutor(actionId); CoordinatorActionBean action = jpaService.execute(actionGetCmd); assertNotNull(action); // Check for expected values assertEquals(actionId, action.getId()); assertEquals(jobId, action.getJobId()); assertEquals(status, action.getStatus()); assertEquals(pending, action.getPending()); assertEquals(createdConf, action.getCreatedConf()); assertEquals(slaXml, action.getSlaXml()); assertEquals(actionXml, action.getActionXml()); assertEquals(extId, action.getExternalId()); assertEquals(errorMessage, action.getErrorMessage()); assertEquals(errorCode, action.getErrorCode()); } catch (Exception ex) { ex.printStackTrace(); fail("Unable to GET a record for COORD Action By actionId =" + actionId); } } }
terrancesnyder/oozie-hadoop2
core/src/test/java/org/apache/oozie/executor/jpa/TestCoordActionGetForStartJPAExecutor.java
Java
apache-2.0
4,358
package leetcode.reverse_linked_list_ii; import common.ListNode; public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null) return null; ListNode curRight = head; for(int len = 0; len < n - m; len++){ curRight = curRight.next; } ListNode prevLeft = null; ListNode curLeft = head; for(int len = 0; len < m - 1; len++){ prevLeft = curLeft; curLeft = curLeft.next; curRight = curRight.next; } if(prevLeft == null){ head = curRight; }else{ prevLeft.next = curRight; } for(int len = 0; len < n - m; len++){ ListNode next = curLeft.next; curLeft.next = curRight.next; curRight.next = curLeft; curLeft = next; } return head; } public static void dump(ListNode node){ while(node != null){ System.err.print(node.val + "->"); node = node.next; } System.err.println("null"); } public static void main(String[] args){ final int N = 10; ListNode[] list = new ListNode[N]; for(int m = 1; m <= N; m++){ for(int n = m; n <= N; n++){ for(int i = 0; i < N; i++){ list[i] = new ListNode(i); if(i > 0) list[i - 1].next = list[i]; } dump(new Solution().reverseBetween(list[0], m, n)); } } } }
ckclark/leetcode
java/leetcode/reverse_linked_list_ii/Solution.java
Java
apache-2.0
1,378
/* * 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.giraph.examples.io.formats; import com.google.common.collect.Lists; import org.apache.giraph.edge.Edge; import org.apache.giraph.edge.EdgeFactory; import org.apache.giraph.examples.utils.BrachaTouegDeadlockVertexValue; import org.apache.giraph.graph.Vertex; import org.apache.giraph.io.formats.TextVertexInputFormat; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.List; /** * VertexInputFormat for the Bracha Toueg Deadlock Detection algorithm * specified in JSON format. */ public class LongLongLongLongVertexInputFormat extends TextVertexInputFormat<LongWritable, LongWritable, LongWritable> { @Override public TextVertexReader createVertexReader(InputSplit split, TaskAttemptContext context) { return new JsonLongLongLongLongVertexReader(); } /** * VertexReader use for the Bracha Toueg Deadlock Detection Algorithm. * The files should be in the following JSON format: * JSONArray(<vertex id>, * JSONArray(JSONArray(<dest vertex id>, <edge tag>), ...)) * The tag is use for the N-out-of-M semantics. Two edges with the same tag * are considered to be combined and, hence, represent to combined requests * that need to be both satisfied to continue execution. * Here is an example with vertex id 1, and three edges (requests). * First edge has a destination vertex 2 with tag 0. * Second and third edge have a destination vertex respectively of 3 and 4 * with tag 1. * [1,[[2,0], [3,1], [4,1]]] */ class JsonLongLongLongLongVertexReader extends TextVertexReaderFromEachLineProcessedHandlingExceptions<JSONArray, JSONException> { @Override protected JSONArray preprocessLine(Text line) throws JSONException { return new JSONArray(line.toString()); } @Override protected LongWritable getId(JSONArray jsonVertex) throws JSONException, IOException { return new LongWritable(jsonVertex.getLong(0)); } @Override protected LongWritable getValue(JSONArray jsonVertex) throws JSONException, IOException { return new LongWritable(); } @Override protected Iterable<Edge<LongWritable, LongWritable>> getEdges(JSONArray jsonVertex) throws JSONException, IOException { JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1); /* get the edges */ List<Edge<LongWritable, LongWritable>> edges = Lists.newArrayListWithCapacity(jsonEdgeArray.length()); for (int i = 0; i < jsonEdgeArray.length(); ++i) { LongWritable targetId; LongWritable tag; JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i); targetId = new LongWritable(jsonEdge.getLong(0)); tag = new LongWritable((long) jsonEdge.getLong(1)); edges.add(EdgeFactory.create(targetId, tag)); } return edges; } @Override protected Vertex<LongWritable, LongWritable, LongWritable> handleException(Text line, JSONArray jsonVertex, JSONException e) { throw new IllegalArgumentException( "Couldn't get vertex from line " + line, e); } } }
KidEinstein/giraph
giraph-examples/src/main/java/org/apache/giraph/examples/io/formats/LongLongLongLongVertexInputFormat.java
Java
apache-2.0
4,147
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.json; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import java.io.IOException; import junit.framework.TestCase; /** * Tests {@link GoogleJsonResponseExceptionFactoryTesting} * * @author Eric Mintz */ public class GoogleJsonResponseExceptionFactoryTestingTest extends TestCase { private static final JsonFactory JSON_FACTORY = new GsonFactory(); private static final int HTTP_CODE_NOT_FOUND = 404; private static final String REASON_PHRASE_NOT_FOUND = "NOT FOUND"; public void testCreateException() throws IOException { GoogleJsonResponseException exception = GoogleJsonResponseExceptionFactoryTesting.newMock( JSON_FACTORY, HTTP_CODE_NOT_FOUND, REASON_PHRASE_NOT_FOUND); assertEquals(HTTP_CODE_NOT_FOUND, exception.getStatusCode()); assertEquals(REASON_PHRASE_NOT_FOUND, exception.getStatusMessage()); } }
googleapis/google-api-java-client
google-api-client/src/test/java/com/google/api/client/googleapis/testing/json/GoogleJsonResponseExceptionFactoryTestingTest.java
Java
apache-2.0
1,619
//============================================================================ // // Copyright (C) 2006-2022 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // //============================================================================ package org.talend.components.google.drive.connection; import java.util.EnumSet; import java.util.Set; import org.talend.components.api.component.ConnectorTopology; import org.talend.components.api.component.runtime.ExecutionEngine; import org.talend.components.api.properties.ComponentProperties; import org.talend.components.google.drive.GoogleDriveComponentDefinition; import org.talend.daikon.runtime.RuntimeInfo; public class GoogleDriveConnectionDefinition extends GoogleDriveComponentDefinition { public static final String COMPONENT_NAME = "tGoogleDriveConnection"; //$NON-NLS-1$ public GoogleDriveConnectionDefinition() { super(COMPONENT_NAME); } @Override public Class<? extends ComponentProperties> getPropertyClass() { return GoogleDriveConnectionProperties.class; } @Override public Set<ConnectorTopology> getSupportedConnectorTopologies() { return EnumSet.of(ConnectorTopology.NONE); } @Override public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { assertEngineCompatibility(engine); assertConnectorTopologyCompatibility(connectorTopology); return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_OR_SINK_CLASS); } @Override public boolean isStartable() { return true; } }
Talend/components
components/components-googledrive/components-googledrive-definition/src/main/java/org/talend/components/google/drive/connection/GoogleDriveConnectionDefinition.java
Java
apache-2.0
1,926
package si.majeric.smarthouse.xstream.dao; public class SmartHouseConfigReadError extends RuntimeException { private static final long serialVersionUID = 1L; public SmartHouseConfigReadError(Exception e) { super(e); } }
umajeric/smart-house
smart-house-xstream-impl/src/main/java/si/majeric/smarthouse/xstream/dao/SmartHouseConfigReadError.java
Java
apache-2.0
228
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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.graphhopper.jsprit.core.algorithm; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import org.junit.Test; import com.graphhopper.jsprit.core.algorithm.acceptor.SolutionAcceptor; import com.graphhopper.jsprit.core.algorithm.listener.SearchStrategyModuleListener; import com.graphhopper.jsprit.core.algorithm.selector.SolutionSelector; import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem; import com.graphhopper.jsprit.core.problem.solution.SolutionCostCalculator; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; public class SearchStrategyTest { @Test(expected = IllegalStateException.class) public void whenANullModule_IsAdded_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); strat.addModule(null); } @Test public void whenStratRunsWithOneModule_runItOnes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.run(vrp, null); assertEquals(runs.size(), 1); } @Test public void whenStratRunsWithTwoModule_runItTwice() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; SearchStrategyModule mod2 = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); strat.addModule(mod2); strat.run(vrp, null); assertEquals(runs.size(), 2); } @Test public void whenStratRunsWithNModule_runItNTimes() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); final VehicleRoutingProblemSolution newSol = mock(VehicleRoutingProblemSolution.class); when(select.selectSolution(null)).thenReturn(newSol); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } @Test(expected = IllegalStateException.class) public void whenSelectorDeliversNullSolution_throwException() { SolutionSelector select = mock(SolutionSelector.class); SolutionAcceptor accept = mock(SolutionAcceptor.class); SolutionCostCalculator calc = mock(SolutionCostCalculator.class); final VehicleRoutingProblem vrp = mock(VehicleRoutingProblem.class); when(select.selectSolution(null)).thenReturn(null); int N = new Random().nextInt(1000); final Collection<Integer> runs = new ArrayList<Integer>(); SearchStrategy strat = new SearchStrategy("strat", select, accept, calc); for (int i = 0; i < N; i++) { SearchStrategyModule mod = new SearchStrategyModule() { @Override public VehicleRoutingProblemSolution runAndGetSolution(VehicleRoutingProblemSolution vrpSolution) { runs.add(1); return vrpSolution; } @Override public String getName() { return null; } @Override public void addModuleListener( SearchStrategyModuleListener moduleListener) { } }; strat.addModule(mod); } strat.run(vrp, null); assertEquals(runs.size(), N); } }
balage1551/jsprit
jsprit-core/src/test/java/com/graphhopper/jsprit/core/algorithm/SearchStrategyTest.java
Java
apache-2.0
8,039
package com.apixandru.rummikub.api; /** * @author Alexandru-Constantin Bledea * @since Sep 16, 2015 */ public enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN, TWELVE, THIRTEEN; public int asNumber() { return ordinal() + 1; } @Override public String toString() { return String.format("%2d", asNumber()); } }
apixandru/rummikub-java
rummikub-model/src/main/java/com/apixandru/rummikub/api/Rank.java
Java
apache-2.0
405
/* * Copyright (c) 2008-2015, Hazelcast, 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.hazelcast.simulator.provisioner; import com.hazelcast.simulator.common.AgentsFile; import com.hazelcast.simulator.common.SimulatorProperties; import com.hazelcast.simulator.utils.Bash; import com.hazelcast.simulator.utils.jars.HazelcastJARs; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.jclouds.compute.ComputeService; import static com.hazelcast.simulator.common.SimulatorProperties.PROPERTIES_FILE_NAME; import static com.hazelcast.simulator.utils.CliUtils.initOptionsWithHelp; import static com.hazelcast.simulator.utils.CliUtils.printHelpAndExit; import static com.hazelcast.simulator.utils.CloudProviderUtils.isStatic; import static com.hazelcast.simulator.utils.SimulatorUtils.loadSimulatorProperties; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.isPrepareRequired; import static com.hazelcast.simulator.utils.jars.HazelcastJARs.newInstance; import static java.util.Collections.singleton; final class ProvisionerCli { private final OptionParser parser = new OptionParser(); private final OptionSpec<Integer> scaleSpec = parser.accepts("scale", "Number of Simulator machines to scale to. If the number of machines already exists, the call is ignored. If the" + " desired number of machines is smaller than the actual number of machines, machines are terminated.") .withRequiredArg().ofType(Integer.class); private final OptionSpec installSpec = parser.accepts("install", "Installs Simulator on all provisioned machines."); private final OptionSpec uploadHazelcastSpec = parser.accepts("uploadHazelcast", "If defined --install will upload the Hazelcast JARs as well."); private final OptionSpec<Boolean> enterpriseEnabledSpec = parser.accepts("enterpriseEnabled", "Use JARs of Hazelcast Enterprise Edition.") .withRequiredArg().ofType(Boolean.class).defaultsTo(false); private final OptionSpec listAgentsSpec = parser.accepts("list", "Lists the provisioned machines (from " + AgentsFile.NAME + " file)."); private final OptionSpec<String> downloadSpec = parser.accepts("download", "Download all files from the remote Worker directories. Use --clean to delete all Worker directories.") .withOptionalArg().ofType(String.class).defaultsTo("workers"); private final OptionSpec cleanSpec = parser.accepts("clean", "Cleans the remote Worker directories on the provisioned machines."); private final OptionSpec killSpec = parser.accepts("kill", "Kills the Java processes on all provisioned machines (via killall -9 java)."); private final OptionSpec terminateSpec = parser.accepts("terminate", "Terminates all provisioned machines."); private final OptionSpec<String> propertiesFileSpec = parser.accepts("propertiesFile", "The file containing the Simulator properties. If no file is explicitly configured, first the local working directory" + " is checked for a file '" + PROPERTIES_FILE_NAME + "'. All missing properties are always loaded from" + " '$SIMULATOR_HOME/conf/" + PROPERTIES_FILE_NAME + "'.") .withRequiredArg().ofType(String.class); private ProvisionerCli() { } static Provisioner init(String[] args) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); SimulatorProperties properties = loadSimulatorProperties(options, cli.propertiesFileSpec); ComputeService computeService = isStatic(properties) ? null : new ComputeServiceBuilder(properties).build(); Bash bash = new Bash(properties); HazelcastJARs hazelcastJARs = null; boolean enterpriseEnabled = options.valueOf(cli.enterpriseEnabledSpec); if (options.has(cli.uploadHazelcastSpec)) { String hazelcastVersionSpec = properties.getHazelcastVersionSpec(); if (isPrepareRequired(hazelcastVersionSpec) || !enterpriseEnabled) { hazelcastJARs = newInstance(bash, properties, singleton(hazelcastVersionSpec)); } } return new Provisioner(properties, computeService, bash, hazelcastJARs, enterpriseEnabled); } static void run(String[] args, Provisioner provisioner) { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = initOptionsWithHelp(cli.parser, args); try { if (options.has(cli.scaleSpec)) { int size = options.valueOf(cli.scaleSpec); provisioner.scale(size); } else if (options.has(cli.installSpec)) { provisioner.installSimulator(); } else if (options.has(cli.listAgentsSpec)) { provisioner.listMachines(); } else if (options.has(cli.downloadSpec)) { String dir = options.valueOf(cli.downloadSpec); provisioner.download(dir); } else if (options.has(cli.cleanSpec)) { provisioner.clean(); } else if (options.has(cli.killSpec)) { provisioner.killJavaProcesses(); } else if (options.has(cli.terminateSpec)) { provisioner.terminate(); } else { printHelpAndExit(cli.parser); } } finally { provisioner.shutdown(); } } }
Danny-Hazelcast/hazelcast-stabilizer
simulator/src/main/java/com/hazelcast/simulator/provisioner/ProvisionerCli.java
Java
apache-2.0
6,122
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.DISPID; import com4j.IID; import com4j.VTID; @IID("{B739B750-BFE1-43AF-8DD7-E8E8EFBBED7D}") public abstract interface IDashboardFolderFactory extends IBaseFactoryEx { @DISPID(9) @VTID(17) public abstract IList getChildPagesWithPrivateItems(IList paramIList); } /* Location: D:\Prabu\jars\QC.jar * Qualified Name: qcupdation.IDashboardFolderFactory * JD-Core Version: 0.7.0.1 */
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IDashboardFolderFactory.java
Java
apache-2.0
482
/* * Copyright (C) 2016 QAware GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.qaware.chronix.timeseries.dt; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; import java.util.Arrays; import static de.qaware.chronix.timeseries.dt.ListUtil.*; /** * Implementation of a list with primitive doubles. * * @author f.lautenschlager */ public class DoubleList implements Serializable { private static final long serialVersionUID = -1275724597860546074L; /** * Shared empty array instance used for empty instances. */ private static final double[] EMPTY_ELEMENT_DATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENT_DATA to know how much to inflate when * first element is added. */ private static final double[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {}; private double[] doubles; private int size; /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public DoubleList(int initialCapacity) { if (initialCapacity > 0) { this.doubles = new double[initialCapacity]; } else if (initialCapacity == 0) { this.doubles = EMPTY_ELEMENT_DATA; } else { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. */ public DoubleList() { this.doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; } /** * Constructs a double list from the given values by simple assigning them. * * @param longs the values of the double list. * @param size the index of the last value in the array. */ @SuppressWarnings("all") public DoubleList(double[] longs, int size) { if (longs == null) { throw new IllegalArgumentException("Illegal initial array 'null'"); } if (size < 0) { throw new IllegalArgumentException("Size if negative."); } this.doubles = longs; this.size = size; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; } /** * Returns <tt>true</tt> if this list contains no elements. * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(double o) { return indexOf(o) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the index of the given double element */ public int indexOf(double o) { for (int i = 0; i < size; i++) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o the double value * @return the last index of the given double element */ public int lastIndexOf(double o) { for (int i = size - 1; i >= 0; i--) { if (o == doubles[i]) { return i; } } return -1; } /** * Returns a shallow copy of this <tt>LongList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>LongList</tt> instance */ public DoubleList copy() { DoubleList v = new DoubleList(size); v.doubles = Arrays.copyOf(doubles, size); v.size = size; return v; } /** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * <p> * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * <p> * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this list in * proper sequence */ public double[] toArray() { return Arrays.copyOf(doubles, size); } private void growIfNeeded(int newCapacity) { if (newCapacity != -1) { doubles = Arrays.copyOf(doubles, newCapacity); } } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException */ public double get(int index) { rangeCheck(index, size); return doubles[index]; } /** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException */ public double set(int index, double element) { rangeCheck(index, size); double oldValue = doubles[index]; doubles[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by Collection#add) */ public boolean add(double e) { int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); doubles[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException */ public void add(int index, double element) { rangeCheckForAdd(index, size); int newCapacity = calculateNewCapacity(doubles.length, size + 1); growIfNeeded(newCapacity); System.arraycopy(doubles, index, doubles, index + 1, size - index); doubles[index] = element; size++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException */ public double remove(int index) { rangeCheck(index, size); double oldValue = doubles[index]; int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(double o) { for (int index = 0; index < size; index++) { if (o == doubles[index]) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(doubles, index + 1, doubles, index, numMoved); } --size; } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { doubles = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA; size = 0; } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the * specified collection's Iterator. The behavior of this operation is * undefined if the specified collection is modified while the operation * is in progress. (This implies that the behavior of this call is * undefined if the specified collection is this list, and this * list is nonempty.) * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(DoubleList c) { double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(a, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Appends the long[] at the end of this long list. * * @param otherDoubles the other double[] that is appended * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified array is null */ public boolean addAll(double[] otherDoubles) { int numNew = otherDoubles.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); System.arraycopy(otherDoubles, 0, doubles, size, numNew); size += numNew; return numNew != 0; } /** * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * * @param index index at which to insert the first element from the * specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, DoubleList c) { rangeCheckForAdd(index, size); double[] a = c.toArray(); int numNew = a.length; int newCapacity = calculateNewCapacity(doubles.length, size + numNew); growIfNeeded(newCapacity); int numMoved = size - index; if (numMoved > 0) { System.arraycopy(doubles, index, doubles, index + numNew, numMoved); } System.arraycopy(a, 0, doubles, index, numNew); size += numNew; return numNew != 0; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ public void removeRange(int fromIndex, int toIndex) { int numMoved = size - toIndex; System.arraycopy(doubles, toIndex, doubles, fromIndex, numMoved); size = size - (toIndex - fromIndex); } /** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ private double[] trimToSize(int size, double[] elements) { double[] copy = Arrays.copyOf(elements, elements.length); if (size < elements.length) { copy = (size == 0) ? EMPTY_ELEMENT_DATA : Arrays.copyOf(elements, size); } return copy; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } DoubleList rhs = (DoubleList) obj; double[] thisTrimmed = trimToSize(this.size, this.doubles); double[] otherTrimmed = trimToSize(rhs.size, rhs.doubles); return new EqualsBuilder() .append(thisTrimmed, otherTrimmed) .append(this.size, rhs.size) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(doubles) .append(size) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("doubles", trimToSize(this.size, doubles)) .append("size", size) .toString(); } /** * @return maximum of the values of the list */ public double max() { if (size <= 0) { return Double.NaN; } double max = Double.MIN_VALUE; for (int i = 0; i < size; i++) { max = doubles[i] > max ? doubles[i] : max; } return max; } /** * @return minimum of the values of the list */ public double min() { if (size <= 0) { return Double.NaN; } double min = Double.MAX_VALUE; for (int i = 0; i < size; i++) { min = doubles[i] < min ? doubles[i] : min; } return min; } /** * @return average of the values of the list */ public double avg() { if (size <= 0) { return Double.NaN; } double current = 0; for (int i = 0; i < size; i++) { current += doubles[i]; } return current / size; } /** * @param scale to be applied to the values of this list * @return a new instance scaled with the given parameter */ public DoubleList scale(double scale) { DoubleList scaled = new DoubleList(size); for (int i = 0; i < size; i++) { scaled.add(doubles[i] * scale); } return scaled; } /** * Calculates the standard deviation * * @return the standard deviation */ public double stdDeviation() { if (isEmpty()) { return Double.NaN; } return Math.sqrt(variance()); } private double mean() { double sum = 0.0; for (int i = 0; i < size(); i++) { sum = sum + get(i); } return sum / size(); } private double variance() { double avg = mean(); double sum = 0.0; for (int i = 0; i < size(); i++) { double value = get(i); sum += (value - avg) * (value - avg); } return sum / (size() - 1); } /** * Implemented the quantile type 7 referred to * http://tolstoy.newcastle.edu.au/R/e17/help/att-1067/Quartiles_in_R.pdf * and * http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html * as its the default quantile implementation * <p> * <code> * QuantileType7 = function (v, p) { * v = sort(v) * h = ((length(v)-1)*p)+1 * v[floor(h)]+((h-floor(h))*(v[floor(h)+1]- v[floor(h)])) * } * </code> * * @param percentile - the percentile (0 - 1), e.g. 0.25 * @return the value of the n-th percentile */ public double percentile(double percentile) { double[] copy = toArray(); Arrays.sort(copy);// Attention: this is only necessary because this list is not restricted to non-descending values return evaluateForDoubles(copy, percentile); } private static double evaluateForDoubles(double[] points, double percentile) { //For example: //values = [1,2,2,3,3,3,4,5,6], size = 9, percentile (e.g. 0.25) // size - 1 = 8 * 0.25 = 2 (~ 25% from 9) + 1 = 3 => values[3] => 2 double percentileIndex = ((points.length - 1) * percentile) + 1; double rawMedian = points[floor(percentileIndex - 1)]; double weight = percentileIndex - floor(percentileIndex); if (weight > 0) { double pointDistance = points[floor(percentileIndex - 1) + 1] - points[floor(percentileIndex - 1)]; return rawMedian + weight * pointDistance; } else { return rawMedian; } } /** * Wraps the Math.floor function and casts it to an integer * * @param value - the evaluatedValue * @return the floored evaluatedValue */ private static int floor(double value) { return (int) Math.floor(value); } }
0xhansdampf/chronix.kassiopeia
chronix-kassiopeia-simple/src/main/java/de/qaware/chronix/timeseries/dt/DoubleList.java
Java
apache-2.0
19,873
package de.devisnik.mine.robot.test; import de.devisnik.mine.robot.AutoPlayerTest; import de.devisnik.mine.robot.ConfigurationTest; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("Tests for de.devisnik.mine.robot"); //$JUnit-BEGIN$ suite.addTestSuite(AutoPlayerTest.class); suite.addTestSuite(ConfigurationTest.class); //$JUnit-END$ return suite; } }
devisnik/mines
robot/src/test/java/de/devisnik/mine/robot/test/AllTests.java
Java
apache-2.0
470
package com.beanu.l2_shareutil.share; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by shaohui on 2016/11/18. */ public class SharePlatform { @IntDef({ DEFAULT, QQ, QZONE, WEIBO, WX, WX_TIMELINE }) @Retention(RetentionPolicy.SOURCE) public @interface Platform{} public static final int DEFAULT = 0; public static final int QQ = 1; public static final int QZONE = 2; public static final int WX = 3; public static final int WX_TIMELINE = 4; public static final int WEIBO = 5; }
beanu/smart-farmer-android
l2_shareutil/src/main/java/com/beanu/l2_shareutil/share/SharePlatform.java
Java
apache-2.0
608
package com.blp.minotaurus.utils; import com.blp.minotaurus.Minotaurus; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.plugin.RegisteredServiceProvider; /** * @author TheJeterLP */ public class EconomyManager { private static Economy econ = null; public static boolean setupEconomy() { if (!Minotaurus.getInstance().getServer().getPluginManager().isPluginEnabled("Vault")) return false; RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class); if (rsp == null || rsp.getProvider() == null) return false; econ = rsp.getProvider(); return true; } public static Economy getEcon() { return econ; } }
BossLetsPlays/Minotaurus
src/main/java/com/blp/minotaurus/utils/EconomyManager.java
Java
apache-2.0
756
package eas.com; public interface SomeInterface { String someMethod(String param1, String param2, String param3, String param4); }
xalfonso/res_java
java-reflection-method/src/main/java/eas/com/SomeInterface.java
Java
apache-2.0
137
package com.mobisys.musicplayer.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by Govinda P on 6/3/2016. */ public class MusicFile implements Parcelable { private String title; private String album; private String id; private String singer; private String path; public MusicFile() { } public MusicFile(String title, String album, String id, String singer, String path) { this.title = title; this.album = album; this.id = id; this.singer = singer; this.path = path; } protected MusicFile(Parcel in) { title = in.readString(); album = in.readString(); id = in.readString(); singer = in.readString(); path=in.readString(); } public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() { @Override public MusicFile createFromParcel(Parcel in) { return new MusicFile(in); } @Override public MusicFile[] newArray(int size) { return new MusicFile[size]; } }; public String getTitle() { return title; } public String getAlbum() { return album; } public String getId() { return id; } public String getSinger() { return singer; } public void setTitle(String title) { this.title = title; } public void setAlbum(String album) { this.album = album; } public void setId(String id) { this.id = id; } public void setSinger(String singer) { this.singer = singer; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "MusicFile{" + "title='" + title + '\'' + ", album='" + album + '\'' + ", id='" + id + '\'' + ", singer='" + singer + '\'' + ", path='" + path + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(album); dest.writeString(id); dest.writeString(singer); dest.writeString(path); } }
GovindaPaliwal/android-constraint-Layout
app/src/main/java/com/mobisys/musicplayer/model/MusicFile.java
Java
apache-2.0
2,408
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cognitoidp.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AnalyticsMetadataType JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AnalyticsMetadataTypeJsonUnmarshaller implements Unmarshaller<AnalyticsMetadataType, JsonUnmarshallerContext> { public AnalyticsMetadataType unmarshall(JsonUnmarshallerContext context) throws Exception { AnalyticsMetadataType analyticsMetadataType = new AnalyticsMetadataType(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("AnalyticsEndpointId", targetDepth)) { context.nextToken(); analyticsMetadataType.setAnalyticsEndpointId(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return analyticsMetadataType; } private static AnalyticsMetadataTypeJsonUnmarshaller instance; public static AnalyticsMetadataTypeJsonUnmarshaller getInstance() { if (instance == null) instance = new AnalyticsMetadataTypeJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/AnalyticsMetadataTypeJsonUnmarshaller.java
Java
apache-2.0
2,836
package com.doglandia.animatingtextviewlib; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
ThomasKomarnicki/AnimatingTextView
app/src/androidTest/java/com/doglandia/animatingtextviewlib/ApplicationTest.java
Java
apache-2.0
365
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seongil.mvplife.fragment; import android.os.Bundle; import android.view.View; import com.seongil.mvplife.base.MvpPresenter; import com.seongil.mvplife.base.MvpView; import com.seongil.mvplife.delegate.MvpDelegateCallback; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegate; import com.seongil.mvplife.delegate.fragment.MvpFragmentDelegateImpl; /** * Abstract class for the fragment which is holding a reference of the {@link MvpPresenter} * Also, holding a {@link MvpFragmentDelegate} which is handling the lifecycle of the fragment. * * @param <V> The type of {@link MvpView} * @param <P> The type of {@link MvpPresenter} * * @author seong-il, kim * @since 17. 1. 6 */ public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>> extends CoreFragment implements MvpView, MvpDelegateCallback<V, P> { // ======================================================================== // Constants // ======================================================================== // ======================================================================== // Fields // ======================================================================== private MvpFragmentDelegate mFragmentDelegate; private P mPresenter; // ======================================================================== // Constructors // ======================================================================== // ======================================================================== // Getter & Setter // ======================================================================== // ======================================================================== // Methods for/from SuperClass/Interfaces // ======================================================================== @Override public abstract P createPresenter(); @Override public P getPresenter() { return mPresenter; } @Override public void setPresenter(P presenter) { mPresenter = presenter; } @Override @SuppressWarnings("unchecked") public V getMvpView() { return (V) this; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getMvpDelegate().onViewCreated(view, savedInstanceState); } @Override public void onDestroyView() { getMvpDelegate().onDestroyView(); super.onDestroyView(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMvpDelegate().onCreate(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); getMvpDelegate().onDestroy(); } // ======================================================================== // Methods // ======================================================================== protected MvpFragmentDelegate getMvpDelegate() { if (mFragmentDelegate == null) { mFragmentDelegate = new MvpFragmentDelegateImpl<>(this); } return mFragmentDelegate; } // ======================================================================== // Inner and Anonymous Classes // ======================================================================== }
allsoft777/MVP-with-Firebase
mvplife/src/main/java/com/seongil/mvplife/fragment/BaseMvpFragment.java
Java
apache-2.0
4,046
package org.openstack.atlas.service.domain.exception; public class UniqueLbPortViolationException extends PersistenceServiceException { private final String message; public UniqueLbPortViolationException(final String message) { this.message = message; } @Override public String getMessage() { return message; } }
openstack-atlas/atlas-lb
core-persistence/src/main/java/org/openstack/atlas/service/domain/exception/UniqueLbPortViolationException.java
Java
apache-2.0
356
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver13; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFOxmBsnUdf4MaskedVer13 implements OFOxmBsnUdf4Masked { private static final Logger logger = LoggerFactory.getLogger(OFOxmBsnUdf4MaskedVer13.class); // version: 1.3 final static byte WIRE_VERSION = 4; final static int LENGTH = 12; private final static UDF DEFAULT_VALUE = UDF.ZERO; private final static UDF DEFAULT_VALUE_MASK = UDF.ZERO; // OF message fields private final UDF value; private final UDF mask; // // Immutable default instance final static OFOxmBsnUdf4MaskedVer13 DEFAULT = new OFOxmBsnUdf4MaskedVer13( DEFAULT_VALUE, DEFAULT_VALUE_MASK ); // package private constructor - used by readers, builders, and factory OFOxmBsnUdf4MaskedVer13(UDF value, UDF mask) { if(value == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property value cannot be null"); } if(mask == null) { throw new NullPointerException("OFOxmBsnUdf4MaskedVer13: property mask cannot be null"); } this.value = value; this.mask = mask; } // Accessors for OF message fields @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public UDF getMask() { return mask; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } public OFOxm<UDF> getCanonical() { if (UDF.NO_MASK.equals(mask)) { return new OFOxmBsnUdf4Ver13(value); } else if(UDF.FULL_MASK.equals(mask)) { return null; } else { return this; } } @Override public OFVersion getVersion() { return OFVersion.OF_13; } public OFOxmBsnUdf4Masked.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFOxmBsnUdf4Masked.Builder { final OFOxmBsnUdf4MaskedVer13 parentMessage; // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; BuilderWithParent(OFOxmBsnUdf4MaskedVer13 parentMessage) { this.parentMessage = parentMessage; } @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : parentMessage.value; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : parentMessage.mask; if(mask == null) throw new NullPointerException("Property mask must not be null"); // return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } static class Builder implements OFOxmBsnUdf4Masked.Builder { // OF message fields private boolean valueSet; private UDF value; private boolean maskSet; private UDF mask; @Override public long getTypeLen() { return 0x31908L; } @Override public UDF getValue() { return value; } @Override public OFOxmBsnUdf4Masked.Builder setValue(UDF value) { this.value = value; this.valueSet = true; return this; } @Override public UDF getMask() { return mask; } @Override public OFOxmBsnUdf4Masked.Builder setMask(UDF mask) { this.mask = mask; this.maskSet = true; return this; } @Override public MatchField<UDF> getMatchField() { return MatchField.BSN_UDF4; } @Override public boolean isMasked() { return true; } @Override public OFOxm<UDF> getCanonical()throws UnsupportedOperationException { throw new UnsupportedOperationException("Property canonical not supported in version 1.3"); } @Override public OFVersion getVersion() { return OFVersion.OF_13; } // @Override public OFOxmBsnUdf4Masked build() { UDF value = this.valueSet ? this.value : DEFAULT_VALUE; if(value == null) throw new NullPointerException("Property value must not be null"); UDF mask = this.maskSet ? this.mask : DEFAULT_VALUE_MASK; if(mask == null) throw new NullPointerException("Property mask must not be null"); return new OFOxmBsnUdf4MaskedVer13( value, mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFOxmBsnUdf4Masked> { @Override public OFOxmBsnUdf4Masked readFrom(ChannelBuffer bb) throws OFParseError { // fixed value property typeLen == 0x31908L int typeLen = bb.readInt(); if(typeLen != 0x31908) throw new OFParseError("Wrong typeLen: Expected=0x31908L(0x31908L), got="+typeLen); UDF value = UDF.read4Bytes(bb); UDF mask = UDF.read4Bytes(bb); OFOxmBsnUdf4MaskedVer13 oxmBsnUdf4MaskedVer13 = new OFOxmBsnUdf4MaskedVer13( value, mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", oxmBsnUdf4MaskedVer13); return oxmBsnUdf4MaskedVer13; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFOxmBsnUdf4MaskedVer13Funnel FUNNEL = new OFOxmBsnUdf4MaskedVer13Funnel(); static class OFOxmBsnUdf4MaskedVer13Funnel implements Funnel<OFOxmBsnUdf4MaskedVer13> { private static final long serialVersionUID = 1L; @Override public void funnel(OFOxmBsnUdf4MaskedVer13 message, PrimitiveSink sink) { // fixed value property typeLen = 0x31908L sink.putInt(0x31908); message.value.putTo(sink); message.mask.putTo(sink); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFOxmBsnUdf4MaskedVer13> { @Override public void write(ChannelBuffer bb, OFOxmBsnUdf4MaskedVer13 message) { // fixed value property typeLen = 0x31908L bb.writeInt(0x31908); message.value.write4Bytes(bb); message.mask.write4Bytes(bb); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFOxmBsnUdf4MaskedVer13("); b.append("value=").append(value); b.append(", "); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFOxmBsnUdf4MaskedVer13 other = (OFOxmBsnUdf4MaskedVer13) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((mask == null) ? 0 : mask.hashCode()); return result; } }
o3project/openflowj-otn
src/main/java/org/projectfloodlight/openflow/protocol/ver13/OFOxmBsnUdf4MaskedVer13.java
Java
apache-2.0
10,443
package com.tamirhassan.pdfxtk.comparators; /** * pdfXtk - PDF Extraction Toolkit * Copyright (c) by the authors/contributors. All rights reserved. * This project includes code from PDFBox and TouchGraph. * * 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. * 3. Neither the names pdfXtk or PDF Extraction Toolkit; 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 REGENTS 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. * * http://pdfxtk.sourceforge.net * */ import java.util.Comparator; import com.tamirhassan.pdfxtk.model.GenericSegment; /** * @author Tamir Hassan, pdfanalyser@tamirhassan.com * @version PDF Analyser 0.9 * * Sorts on Xmid coordinate ((x1+x2)/2) */ public class XmidComparator implements Comparator<GenericSegment> { public int compare(GenericSegment obj1, GenericSegment obj2) { // sorts in x order double x1 = obj1.getXmid(); double x2 = obj2.getXmid(); // causes a contract violation (rounding?) // return (int) (x1 - x2); if (x2 > x1) return -1; else if (x2 == x1) return 0; else return 1; } public boolean equals(Object obj) { return obj.equals(this); } }
tamirhassan/pdfxtk
src/com/tamirhassan/pdfxtk/comparators/XmidComparator.java
Java
apache-2.0
2,438
/** * Copyright (C) 2015 meltmedia (christian.trimble@meltmedia.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meltmedia.dropwizard.etcd.json; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Function; import java.util.function.Supplier; import com.codahale.metrics.MetricRegistry; import mousio.etcd4j.EtcdClient; import io.dropwizard.Configuration; import io.dropwizard.ConfiguredBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class EtcdJsonBundle<C extends Configuration> implements ConfiguredBundle<C> { public static class Builder<C extends Configuration> { private Supplier<EtcdClient> client; private Supplier<ScheduledExecutorService> executor; private Function<C, String> directoryAccessor; public Builder<C> withClient(Supplier<EtcdClient> client) { this.client = client; return this; } public Builder<C> withExecutor(Supplier<ScheduledExecutorService> executor) { this.executor = executor; return this; } public Builder<C> withDirectory(Function<C, String> directoryAccessor) { this.directoryAccessor = directoryAccessor; return this; } public EtcdJsonBundle<C> build() { return new EtcdJsonBundle<C>(client, executor, directoryAccessor); } } public static <C extends Configuration> Builder<C> builder() { return new Builder<C>(); } Supplier<EtcdClient> clientSupplier; EtcdJson factory; private Supplier<ScheduledExecutorService> executor; private Function<C, String> directoryAccessor; public EtcdJsonBundle(Supplier<EtcdClient> client, Supplier<ScheduledExecutorService> executor, Function<C, String> directoryAccessor) { this.clientSupplier = client; this.executor = executor; this.directoryAccessor = directoryAccessor; } @Override public void initialize(Bootstrap<?> bootstrap) { } @Override public void run(C configuration, Environment environment) throws Exception { factory = EtcdJson.builder().withClient(clientSupplier).withExecutor(executor.get()) .withBaseDirectory(directoryAccessor.apply(configuration)) .withMapper(environment.getObjectMapper()) .withMetricRegistry(environment.metrics()).build(); environment.lifecycle().manage(new EtcdJsonManager(factory)); environment.healthChecks().register("etcd-watch", new WatchServiceHealthCheck(factory.getWatchService())); } public EtcdJson getFactory() { return this.factory; } }
meltmedia/dropwizard-etcd
bundle/src/main/java/com/meltmedia/dropwizard/etcd/json/EtcdJsonBundle.java
Java
apache-2.0
3,068
import com.google.common.base.Function; import javax.annotation.Nullable; /** * Created by ckale on 10/29/14. */ public class DateValueSortFunction implements Function<PojoDTO, Long>{ @Nullable @Override public Long apply(@Nullable final PojoDTO input) { return input.getDateTime().getMillis(); } }
chax0r/PlayGround
playGround/src/main/java/DateValueSortFunction.java
Java
apache-2.0
329
package ru.stqa.javacourse.mantis.tests; import org.testng.annotations.Test; import ru.stqa.javacourse.mantis.model.Issue; import ru.stqa.javacourse.mantis.model.Project; import javax.xml.rpc.ServiceException; import java.net.MalformedURLException; import java.rmi.RemoteException; import java.util.Set; import static org.testng.Assert.assertEquals; public class SoapTest extends TestBase { @Test public void testGetProjects() throws MalformedURLException, ServiceException, RemoteException { Set<Project> projects = app.soap().getProjects(); System.out.println(projects.size()); for (Project project : projects) { System.out.println(project.getName()); } } @Test public void testCreateIssue() throws RemoteException, ServiceException, MalformedURLException { Set<Project> projects = app.soap().getProjects(); Issue issue=new Issue().withSummary("test issue") .withDescription("test issue description").withProject(projects.iterator().next()); Issue created = app.soap().addIssue(issue); assertEquals(issue.getSummary(),created.getSummary()); } }
Olbar/courseJava
mantis-tests/src/test/java/ru/stqa/javacourse/mantis/tests/SoapTest.java
Java
apache-2.0
1,172
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/customer_conversion_goal_service.proto package com.google.ads.googleads.v10.services; /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation} */ public final class CustomerConversionGoalOperation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation) CustomerConversionGoalOperationOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerConversionGoalOperation.newBuilder() to construct. private CustomerConversionGoalOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerConversionGoalOperation() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerConversionGoalOperation(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CustomerConversionGoalOperation( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder subBuilder = null; if (operationCase_ == 1) { subBuilder = ((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_).toBuilder(); } operation_ = input.readMessage(com.google.ads.googleads.v10.resources.CustomerConversionGoal.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); operation_ = subBuilder.buildPartial(); } operationCase_ = 1; break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class); } private int operationCase_ = 0; private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { UPDATE(1), OPERATION_NOT_SET(0); private final int value; private OperationCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return UPDATE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return getUpdateMask(); } public static final int UPDATE_FIELD_NUMBER = 1; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getUpdateMask()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)) { return super.equals(obj); } com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask() .equals(other.getUpdateMask())) return false; } if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getUpdate() .equals(other.getUpdate())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } switch (operationCase_) { case 1: hash = (37 * hash) + UPDATE_FIELD_NUMBER; hash = (53 * hash) + getUpdate().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (update) on a customer conversion goal. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.CustomerConversionGoalOperation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CustomerConversionGoalOperation) com.google.ads.googleads.v10.services.CustomerConversionGoalOperationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.class, com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.Builder.class); } // Construct using com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v10.services.CustomerConversionGoalServiceProto.internal_static_google_ads_googleads_v10_services_CustomerConversionGoalOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() { return com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation build() { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation buildPartial() { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation result = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(this); if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } if (operationCase_ == 1) { if (updateBuilder_ == null) { result.operation_ = operation_; } else { result.operation_ = updateBuilder_.build(); } } result.operationCase_ = operationCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) { return mergeFrom((com.google.ads.googleads.v10.services.CustomerConversionGoalOperation)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.services.CustomerConversionGoalOperation other) { if (other == com.google.ads.googleads.v10.services.CustomerConversionGoalOperation.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } switch (other.getOperationCase()) { case UPDATE: { mergeUpdate(other.getUpdate()); break; } case OPERATION_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.services.CustomerConversionGoalOperation parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.services.CustomerConversionGoalOperation) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask( com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * <pre> * FieldMask that determines which resource fields are modified in an update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> updateBuilder_; /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return Whether the update field is set. */ @java.lang.Override public boolean hasUpdate() { return operationCase_ == 1; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> * @return The update. */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoal getUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } else { if (operationCase_ == 1) { return updateBuilder_.getMessage(); } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder setUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) { if (updateBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; onChanged(); } else { updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder setUpdate( com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder builderForValue) { if (updateBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { updateBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CustomerConversionGoal value) { if (updateBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance()) { operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.newBuilder((com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { updateBuilder_.mergeFrom(value); } updateBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public Builder clearUpdate() { if (updateBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } updateBuilder_.clear(); } return this; } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ public com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder getUpdateBuilder() { return getUpdateFieldBuilder().getBuilder(); } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder getUpdateOrBuilder() { if ((operationCase_ == 1) && (updateBuilder_ != null)) { return updateBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_; } return com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } } /** * <pre> * Update operation: The customer conversion goal is expected to have a * valid resource name. * </pre> * * <code>.google.ads.googleads.v10.resources.CustomerConversionGoal update = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder> getUpdateFieldBuilder() { if (updateBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v10.resources.CustomerConversionGoal.getDefaultInstance(); } updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.CustomerConversionGoal, com.google.ads.googleads.v10.resources.CustomerConversionGoal.Builder, com.google.ads.googleads.v10.resources.CustomerConversionGoalOrBuilder>( (com.google.ads.googleads.v10.resources.CustomerConversionGoal) operation_, getParentForChildren(), isClean()); operation_ = null; } operationCase_ = 1; onChanged();; return updateBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CustomerConversionGoalOperation) private static final com.google.ads.googleads.v10.services.CustomerConversionGoalOperation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CustomerConversionGoalOperation(); } public static com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerConversionGoalOperation> PARSER = new com.google.protobuf.AbstractParser<CustomerConversionGoalOperation>() { @java.lang.Override public CustomerConversionGoalOperation parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CustomerConversionGoalOperation(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CustomerConversionGoalOperation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerConversionGoalOperation> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.services.CustomerConversionGoalOperation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CustomerConversionGoalOperation.java
Java
apache-2.0
36,172
package org.openjava.upay.web.domain; import java.util.List; public class TablePage<T> { private long start; private int length; private long recordsTotal; private long recordsFiltered; private List<T> data; public TablePage() { } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public long getRecordsTotal() { return recordsTotal; } public void setRecordsTotal(long recordsTotal) { this.recordsTotal = recordsTotal; } public long getRecordsFiltered() { return recordsFiltered; } public void setRecordsFiltered(long recordsFiltered) { this.recordsFiltered = recordsFiltered; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public TablePage wrapData(long total, List<T> data) { this.recordsTotal = total; this.recordsFiltered = total; this.data = data; return this; } }
openjava2017/openjava-upay
upay-server/src/main/java/org/openjava/upay/web/domain/TablePage.java
Java
apache-2.0
1,263
package com.jy.controller.workflow.online.apply; import com.jy.common.ajax.AjaxRes; import com.jy.common.utils.DateUtils; import com.jy.common.utils.base.Const; import com.jy.common.utils.security.AccountShiroUtil; import com.jy.controller.base.BaseController; import com.jy.entity.attendance.WorkRecord; import com.jy.entity.oa.overtime.Overtime; import com.jy.entity.oa.patch.Patch; import com.jy.entity.oa.task.TaskInfo; import com.jy.service.oa.activiti.ActivitiDeployService; import com.jy.service.oa.overtime.OvertimeService; import com.jy.service.oa.patch.PatchService; import com.jy.service.oa.task.TaskInfoService; import org.activiti.engine.IdentityService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 补卡页面 */ @Controller @RequestMapping(value = "/backstage/workflow/online/patch/") public class PatchController extends BaseController<Object> { private static final String SECURITY_URL = "/backstage/workflow/online/patch/index"; @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private TaskInfoService taskInfoService; @Autowired private IdentityService identityService; @Autowired private PatchService patchService; @Autowired private ActivitiDeployService activitiDeployService; /** * 补卡列表 */ @RequestMapping(value = "index") public String index(org.springframework.ui.Model model) { if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) { model.addAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION)); return "/system/workflow/online/apply/patch"; } return Const.NO_AUTHORIZED_URL; } /** * 启动流程 */ @RequestMapping(value = "start", method = RequestMethod.POST) @ResponseBody public AjaxRes startWorkflow(Patch o) { AjaxRes ar = getAjaxRes(); if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU, SECURITY_URL))) { try { String currentUserId = AccountShiroUtil.getCurrentUser().getAccountId(); String[] approvers = o.getApprover().split(","); Map<String, Object> variables = new HashMap<String, Object>(); for (int i = 0; i < approvers.length; i++) { variables.put("approver" + (i + 1), approvers[i]); } String workflowKey = "patch"; identityService.setAuthenticatedUserId(currentUserId); Date now = new Date(); ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId(workflowKey, variables, getCompany()); String pId = processInstance.getId(); String leaveID = get32UUID(); o.setPid(pId); o.setAccountId(currentUserId); o.setCreatetime(now); o.setIsvalid(0); o.setName(AccountShiroUtil.getCurrentUser().getName()); o.setId(leaveID); patchService.insert(o); Task task = taskService.createTaskQuery().processInstanceId(pId).singleResult(); String processDefinitionName = ((ExecutionEntity) processInstance).getProcessInstance().getProcessDefinition().getName(); String subkect = processDefinitionName + "-" + AccountShiroUtil.getCurrentUser().getName() + "-" + DateUtils.formatDate(now, "yyyy-MM-dd HH:mm"); //开始流程 TaskInfo taskInfo = new TaskInfo(); taskInfo.setId(get32UUID()); taskInfo.setBusinesskey(leaveID); taskInfo.setCode("start"); taskInfo.setName("发起申请"); taskInfo.setStatus(0); taskInfo.setPresentationsubject(subkect); taskInfo.setAttr1(processDefinitionName); taskInfo.setCreatetime(DateUtils.addSeconds(now, -1)); taskInfo.setCompletetime(DateUtils.addSeconds(now, -1)); taskInfo.setCreator(currentUserId); taskInfo.setAssignee(currentUserId); taskInfo.setTaskid("0"); taskInfo.setPkey(workflowKey); taskInfo.setExecutionid("0"); taskInfo.setProcessinstanceid(processInstance.getId()); taskInfo.setProcessdefinitionid(processInstance.getProcessDefinitionId()); taskInfoService.insert(taskInfo); //第一级审批流程 taskInfo.setId(get32UUID()); taskInfo.setCode(processInstance.getActivityId()); taskInfo.setName(task.getName()); taskInfo.setStatus(1); taskInfo.setTaskid(task.getId()); taskInfo.setCreatetime(now); taskInfo.setCompletetime(null); taskInfo.setAssignee(approvers[0]); taskInfoService.insert(taskInfo); ar.setSucceedMsg("发起补卡申请成功!"); } catch (Exception e) { logger.error(e.toString(), e); ar.setFailMsg("启动流程失败"); } finally { identityService.setAuthenticatedUserId(null); } } return ar; } }
futureskywei/whale
src/main/java/com/jy/controller/workflow/online/apply/PatchController.java
Java
apache-2.0
5,402
/* * Copyright 2010-2011 Ning, Inc. * * Ning 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.ning.metrics.eventtracker; import com.google.inject.Guice; import com.google.inject.Injector; import com.ning.metrics.serialization.event.ThriftToThriftEnvelopeEvent; import com.ning.metrics.serialization.writer.SyncType; import org.joda.time.DateTime; import org.skife.config.ConfigurationObjectFactory; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.File; import java.util.UUID; @Test(enabled = false) public class TestIntegration { private final File tmpDir = new File(System.getProperty("java.io.tmpdir"), "collector"); @SuppressWarnings("unused") @BeforeTest(alwaysRun = true) private void setupTmpDir() { if (!tmpDir.exists() && !tmpDir.mkdirs()) { throw new RuntimeException("Failed to create: " + tmpDir); } if (!tmpDir.isDirectory()) { throw new RuntimeException("Path points to something that's not a directory: " + tmpDir); } } @SuppressWarnings("unused") @AfterTest(alwaysRun = true) private void cleanupTmpDir() { tmpDir.delete(); } @Test(groups = "slow", enabled = false) public void testGuiceThrift() throws Exception { System.setProperty("eventtracker.type", "SCRIBE"); System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath()); System.setProperty("eventtracker.scribe.host", "127.0.0.1"); System.setProperty("eventtracker.scribe.port", "7911"); final Injector injector = Guice.createInjector(new CollectorControllerModule()); final CollectorController controller = injector.getInstance(CollectorController.class); final ScribeSender sender = (ScribeSender) injector.getInstance(EventSender.class); sender.createConnection(); fireThriftEvents(controller); sender.close(); } @Test(groups = "slow", enabled = false) public void testScribeFactory() throws Exception { System.setProperty("eventtracker.type", "COLLECTOR"); System.setProperty("eventtracker.directory", tmpDir.getAbsolutePath()); System.setProperty("eventtracker.collector.host", "127.0.0.1"); System.setProperty("eventtracker.collector.port", "8080"); final EventTrackerConfig config = new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class); final CollectorController controller = ScribeCollectorFactory.createScribeController( config.getScribeHost(), config.getScribePort(), config.getScribeRefreshRate(), config.getScribeMaxIdleTimeInMinutes(), config.getSpoolDirectoryName(), config.isFlushEnabled(), config.getFlushIntervalInSeconds(), SyncType.valueOf(config.getSyncType()), config.getSyncBatchSize(), config.getMaxUncommittedWriteCount(), config.getMaxUncommittedPeriodInSeconds() ); fireThriftEvents(controller); } private void fireThriftEvents(final CollectorController controller) throws Exception { controller.offerEvent(ThriftToThriftEnvelopeEvent.extractEvent("thrift", new DateTime(), new Click(UUID.randomUUID().toString(), new DateTime().getMillis(), "user agent"))); Assert.assertEquals(controller.getEventsReceived().get(), 1); Assert.assertEquals(controller.getEventsLost().get(), 0); controller.commit(); controller.flush(); Thread.sleep(5000); } }
pierre/eventtracker
scribe/src/test/java/com/ning/metrics/eventtracker/TestIntegration.java
Java
apache-2.0
4,231
package com.nosolojava.fsm.impl.runtime.executable.basic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.nosolojava.fsm.runtime.Context; import com.nosolojava.fsm.runtime.executable.Elif; import com.nosolojava.fsm.runtime.executable.Else; import com.nosolojava.fsm.runtime.executable.Executable; import com.nosolojava.fsm.runtime.executable.If; public class BasicIf extends BasicConditional implements If { private static final long serialVersionUID = -415238773021486012L; private final List<Elif> elifs = new ArrayList<Elif>(); private final Else elseOperation; public BasicIf(String condition) { this(condition, null, null, null); } public BasicIf(String condition, List<Executable> executables) { this(condition, null, null, executables); } public BasicIf(String condition, Else elseOperation, List<Executable> executables) { this(condition, null, elseOperation, executables); } public BasicIf(String condition, List<Elif> elifs, Else elseOperation, List<Executable> executables) { super(condition, executables); if (elifs != null) { this.elifs.addAll(elifs); } this.elseOperation = elseOperation; } @Override public boolean runIf(Context context) { boolean result = false; // if condition fails if (super.runIf(context)) { result = true; } else { // try with elifs boolean enterElif = false; Iterator<Elif> iterElif = elifs.iterator(); Elif elif; while (!enterElif && iterElif.hasNext()) { elif = iterElif.next(); enterElif = elif.runIf(context); } // if no elif and else if (!enterElif && this.elseOperation != null) { elseOperation.run(context); } } return result; } public List<Elif> getElifs() { return this.elifs; } public void addElif(Elif elif) { this.elifs.add(elif); } public void addElifs(List<Elif> elifs) { this.elifs.addAll(elifs); } public void clearAndSetElifs(List<Elif> elifs) { this.elifs.clear(); addElifs(elifs); } }
nosolojava/scxml-java
scxml-java-implementation/src/main/java/com/nosolojava/fsm/impl/runtime/executable/basic/BasicIf.java
Java
apache-2.0
2,082
/** * Copyright 2015 Santhosh Kumar Tekuri * * The JLibs authors license 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 jlibs.wamp4j.spi; import java.io.InputStream; public interface Listener{ public void onMessage(WAMPSocket socket, MessageType type, InputStream is); public void onReadComplete(WAMPSocket socket); public void readyToWrite(WAMPSocket socket); public void onError(WAMPSocket socket, Throwable error); public void onClose(WAMPSocket socket); }
santhosh-tekuri/jlibs
wamp4j-core/src/main/java/jlibs/wamp4j/spi/Listener.java
Java
apache-2.0
1,010
package me.littlepanda.dadbear.core.queue; import java.util.Queue; /** * @author 张静波 myplaylife@icloud.com * */ public interface DistributedQueue<T> extends Queue<T> { /** * <p>如果使用无参构造函数,需要先调用这个方法,队列才能使用</p> * @param queue_name * @param clazz */ abstract public void init(String queue_name, Class<T> clazz); }
myplaylife/dadbear
framework/core/src/main/java/me/littlepanda/dadbear/core/queue/DistributedQueue.java
Java
apache-2.0
402
/* * 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 jp.eisbahn.oauth2.server.spi.servlet; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.junit.Test; public class HttpServletRequestAdapterTest { @Test public void test() { HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getParameter("name1")).andReturn("value1"); expect(request.getHeader("name2")).andReturn("value2"); @SuppressWarnings("serial") Map<String, String[]> map = new HashMap<String, String[]>() { { put("k1", new String[]{"v1"}); put("k2", new String[]{"v2"}); } }; expect(request.getParameterMap()).andReturn(map); replay(request); HttpServletRequestAdapter target = new HttpServletRequestAdapter(request); assertEquals("value1", target.getParameter("name1")); assertEquals("value2", target.getHeader("name2")); Map<String, String[]> parameterMap = target.getParameterMap(); assertEquals(2, parameterMap.size()); assertEquals("v1", parameterMap.get("k1")[0]); assertEquals("v2", parameterMap.get("k2")[0]); verify(request); } }
morozumi-h/oauth2-server
src/test/java/jp/eisbahn/oauth2/server/spi/servlet/HttpServletRequestAdapterTest.java
Java
apache-2.0
1,972
/* * Copyright 2013 Gunnar Kappei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.opengis.gml; /** * An XML MultiSurfaceType(@http://www.opengis.net/gml). * * This is a complex type. */ public interface MultiSurfaceType extends net.opengis.gml.AbstractGeometricAggregateType { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacetypeb44dtype"); /** * Gets a List of "surfaceMember" elements */ java.util.List<net.opengis.gml.SurfacePropertyType> getSurfaceMemberList(); /** * Gets array of all "surfaceMember" elements * @deprecated */ @Deprecated net.opengis.gml.SurfacePropertyType[] getSurfaceMemberArray(); /** * Gets ith "surfaceMember" element */ net.opengis.gml.SurfacePropertyType getSurfaceMemberArray(int i); /** * Returns number of "surfaceMember" element */ int sizeOfSurfaceMemberArray(); /** * Sets array of all "surfaceMember" element */ void setSurfaceMemberArray(net.opengis.gml.SurfacePropertyType[] surfaceMemberArray); /** * Sets ith "surfaceMember" element */ void setSurfaceMemberArray(int i, net.opengis.gml.SurfacePropertyType surfaceMember); /** * Inserts and returns a new empty value (as xml) as the ith "surfaceMember" element */ net.opengis.gml.SurfacePropertyType insertNewSurfaceMember(int i); /** * Appends and returns a new empty value (as xml) as the last "surfaceMember" element */ net.opengis.gml.SurfacePropertyType addNewSurfaceMember(); /** * Removes the ith "surfaceMember" element */ void removeSurfaceMember(int i); /** * Gets the "surfaceMembers" element */ net.opengis.gml.SurfaceArrayPropertyType getSurfaceMembers(); /** * True if has "surfaceMembers" element */ boolean isSetSurfaceMembers(); /** * Sets the "surfaceMembers" element */ void setSurfaceMembers(net.opengis.gml.SurfaceArrayPropertyType surfaceMembers); /** * Appends and returns a new empty "surfaceMembers" element */ net.opengis.gml.SurfaceArrayPropertyType addNewSurfaceMembers(); /** * Unsets the "surfaceMembers" element */ void unsetSurfaceMembers(); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static net.opengis.gml.MultiSurfaceType newInstance() { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static net.opengis.gml.MultiSurfaceType newInstance(org.apache.xmlbeans.XmlOptions options) { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static net.opengis.gml.MultiSurfaceType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
moosbusch/xbLIDO
src/net/opengis/gml/MultiSurfaceType.java
Java
apache-2.0
10,068
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.redshift.model.transform; import org.w3c.dom.Node; import javax.annotation.Generated; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.redshift.model.AuthenticationProfileNotFoundException; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AuthenticationProfileNotFoundExceptionUnmarshaller extends StandardErrorUnmarshaller { public AuthenticationProfileNotFoundExceptionUnmarshaller() { super(AuthenticationProfileNotFoundException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("AuthenticationProfileNotFoundFault")) return null; AuthenticationProfileNotFoundException e = (AuthenticationProfileNotFoundException) super.unmarshall(node); return e; } }
aws/aws-sdk-java
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/AuthenticationProfileNotFoundExceptionUnmarshaller.java
Java
apache-2.0
1,678
package ru.job4j.pro.collections.list; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * NodeListTest class. * * @author Vladimir Ivanov * @version 0.1 * @since 30.08.2017 */ public class NodeListTest { /** * Test list is not cycled. */ @Test public void whenListIsNotCycledThenGetFalse() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); Node<Integer> five = new Node<>(5); first.next = two; two.next = third; third.next = four; four.next = five; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(false)); } /** * Test list is cycled. */ @Test public void whenListIsCycledThenGetTrue() { Node<Integer> first = new Node<>(1); Node<Integer> two = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); first.next = two; two.next = third; third.next = four; four.next = first; NodeList<Integer> list = new NodeList<>(first); boolean result = list.hasCycle(); assertThat(result, is(true)); } /** * Test list is cycled. */ @Test public void whenBigListIsCycledThenGetTrue() { Node<Integer> node = new Node<>(0); Node<Integer> cycleFrom = null; Node<Integer> cycleTo = null; NodeList<Integer> list = new NodeList<>(node); for (int value = 1; value < 10000000; value++) { node.next = new Node<>(value); node = node.next; if (value == 900000) { cycleTo = node; } else if (value == 9990000) { cycleFrom = node; } } cycleFrom.next = cycleTo; boolean result = list.hasCycle(); assertThat(result, is(true)); } }
dimir2/vivanov
part2/ch1/src/test/java/ru/job4j/pro/collections/list/NodeListTest.java
Java
apache-2.0
2,090
package com.intel.media.mts.dao.impl; import org.junit.Assert; import org.junit.Test; import com.intel.media.mts.dao.DaoTestSupport; import com.intel.media.mts.model.Software; public class SoftwareDaoImplTest extends DaoTestSupport { @Test public void test(){ Software s = new Software(); String name = "Ubuntu"; String desc = "OS type 12.04"; s.setName(name); s.setDescription(desc); softwareDao.doSave(s); System.out.println(s); Software s2 = softwareDao.findById(s.getId()); Assert.assertEquals(name, s2.getName()); Assert.assertEquals(desc, s2.getDescription()); } }
zhubinqiang/myTMS
src/test/java/com/intel/media/mts/dao/impl/SoftwareDaoImplTest.java
Java
apache-2.0
598
package com.thinkgem.jeesite.modules.purifier.dao; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.purifier.entity.Ware; /** * 仓库管理dao * * @author addison * @since 2017年03月02日 */ @MyBatisDao public interface WareDao extends CrudDao<Ware> { int deleteByWare(Ware ware); }
cuiqunhao/jeesite
src/main/java/com/thinkgem/jeesite/modules/purifier/dao/WareDao.java
Java
apache-2.0
411
/* * @(#)TIFFHeader.java * * $Date: 2014-03-13 04:15:48 -0400 (Thu, 13 Mar 2014) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * https://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) * Modified BSD License Copyright (c) 2015, Jeremy Wood. 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. * The name of the contributors may not 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 gr.iti.mklab.reveal.forensics.util.ThumbnailExtractor.image.jpeg; import java.io.IOException; import java.io.InputStream; class TIFFHeader { boolean bigEndian; int ifdOffset; TIFFHeader(InputStream in) throws IOException { byte[] array = new byte[4]; if(JPEGMarkerInputStream.readFully(in, array, 2, false)!=2) { throw new IOException("Incomplete TIFF Header"); } if(array[0]==73 && array[1]==73) { //little endian bigEndian = false; } else if(array[0]==77 && array[1]==77) { //big endian bigEndian = true; } else { throw new IOException("Unrecognized endian encoding."); } if(JPEGMarkerInputStream.readFully(in, array, 2, !bigEndian)!=2) { throw new IOException("Incomplete TIFF Header"); } if(!(array[0]==0 && array[1]==42)) { //required byte in TIFF header throw new IOException("Missing required identifier 0x002A."); } if(JPEGMarkerInputStream.readFully(in, array, 4, !bigEndian)!=4) { throw new IOException("Incomplete TIFF Header"); } ifdOffset = ((array[0] & 0xff) << 24) + ((array[1] & 0xff) << 16) + ((array[2] & 0xff) << 8) + ((array[3] & 0xff) << 0) ; } /** The length of this TIFF header. */ int getLength() { return 8; } }
MKLab-ITI/image-forensics
java_service/src/main/java/gr/iti/mklab/reveal/forensics/util/ThumbnailExtractor/image/jpeg/TIFFHeader.java
Java
apache-2.0
3,339
/** * */ /** * @author root * */ package com.amanaje.activities;
damico/amanaje
source-code/Amanaje/src/com/amanaje/activities/package-info.java
Java
apache-2.0
70
package eu.ailao.hub.dialog; import eu.ailao.hub.corefresol.answers.ClueMemorizer; import eu.ailao.hub.corefresol.concepts.ConceptMemorizer; import eu.ailao.hub.questions.Question; import java.util.ArrayList; /** * Created by Petr Marek on 24.02.2016. * Dialog class represents dialog. It contains id of dialog and ids of questions in this dialog. */ public class Dialog { private int id; private ArrayList<Question> questionsOfDialogue; private ConceptMemorizer conceptMemorizer; private ClueMemorizer clueMemorizer; public Dialog(int id) { this.id = id; this.questionsOfDialogue = new ArrayList<>(); this.conceptMemorizer = new ConceptMemorizer(); this.clueMemorizer = new ClueMemorizer(); } /** * Adds question to dialog * @param questionID id of question */ public void addQuestion(Question questionID) { questionsOfDialogue.add(questionID); } public ArrayList<Question> getQuestions() { return questionsOfDialogue; } /** * Gets all question's ids of dialog * @return array list of question's ids in dialog */ public ArrayList<Integer> getQuestionsIDs() { ArrayList<Integer> questionIDs = new ArrayList<Integer>(); for (int i = 0; i < questionsOfDialogue.size(); i++) { questionIDs.add(questionsOfDialogue.get(i).getYodaQuestionID()); } return questionIDs; } public int getId() { return id; } public ConceptMemorizer getConceptMemorizer() { return conceptMemorizer; } public ClueMemorizer getClueMemorizer() { return clueMemorizer; } public boolean hasQuestionWithId(int id) { for (Question question : questionsOfDialogue) { if (question.getYodaQuestionID() == id) { return true; } } return false; } }
brmson/hub
src/main/java/eu/ailao/hub/dialog/Dialog.java
Java
apache-2.0
1,699
// Copyright 2016 Yahoo Inc. // Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms. package com.yahoo.bard.webservice.data.metric; /** * LogicalMetricColumn. */ public class LogicalMetricColumn extends MetricColumn { private final LogicalMetric metric; /** * Constructor. * * @param name The column name * @param metric The logical metric * * @deprecated because LogicalMetricColumn is really only a thing for LogicalTable, so there's no reason for there * to be an alias on the LogicalMetric inside the LogicalTableSchema. */ @Deprecated public LogicalMetricColumn(String name, LogicalMetric metric) { super(name); this.metric = metric; } /** * Constructor. * * @param metric The logical metric */ public LogicalMetricColumn(LogicalMetric metric) { super(metric.getName()); this.metric = metric; } /** * Getter for a logical metric. * * @return logical metric */ public LogicalMetric getLogicalMetric() { return this.metric; } @Override public String toString() { return "{logicalMetric:'" + getName() + "'}"; } }
yahoo/fili
fili-core/src/main/java/com/yahoo/bard/webservice/data/metric/LogicalMetricColumn.java
Java
apache-2.0
1,271
package coop.ekologia.presentation.controller.user; import java.io.IOException; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import coop.ekologia.presentation.EkologiaServlet; import coop.ekologia.presentation.session.LoginSession; /** * Servlet implementation class LoginConnectionServlet */ @WebServlet(LoginDeconnectionServlet.routing) public class LoginDeconnectionServlet extends EkologiaServlet { private static final long serialVersionUID = 1L; public static final String routing = "/login/deconnection"; public static final String routing(HttpServletRequest request) { return getUrl(request, routing); } @Inject LoginSession loginSession; /** * @see HttpServlet#HttpServlet() */ public LoginDeconnectionServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { loginSession.setUser(null); response.sendRedirect(request.getHeader("referer")); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
imie-source/Ekologia
EkologiaGUI/src/coop/ekologia/presentation/controller/user/LoginDeconnectionServlet.java
Java
apache-2.0
1,605
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.cmd; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.activiti.engine.ActivitiObjectNotFoundException; import org.activiti.engine.delegate.event.ActivitiEventType; import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder; import org.activiti.engine.impl.identity.Authentication; import org.activiti.engine.impl.interceptor.Command; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.AttachmentEntity; import org.activiti.engine.impl.persistence.entity.ByteArrayEntity; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.activiti.engine.impl.util.IoUtil; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Attachment; import org.activiti.engine.task.Task; /** */ // Not Serializable public class CreateAttachmentCmd implements Command<Attachment> { protected String attachmentType; protected String taskId; protected String processInstanceId; protected String attachmentName; protected String attachmentDescription; protected InputStream content; protected String url; public CreateAttachmentCmd(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content, String url) { this.attachmentType = attachmentType; this.taskId = taskId; this.processInstanceId = processInstanceId; this.attachmentName = attachmentName; this.attachmentDescription = attachmentDescription; this.content = content; this.url = url; } public Attachment execute(CommandContext commandContext) { if (taskId != null) { verifyTaskParameters(commandContext); } if (processInstanceId != null) { verifyExecutionParameters(commandContext); } return executeInternal(commandContext); } protected Attachment executeInternal(CommandContext commandContext) { AttachmentEntity attachment = commandContext.getAttachmentEntityManager().create(); attachment.setName(attachmentName); attachment.setProcessInstanceId(processInstanceId); attachment.setTaskId(taskId); attachment.setDescription(attachmentDescription); attachment.setType(attachmentType); attachment.setUrl(url); attachment.setUserId(Authentication.getAuthenticatedUserId()); attachment.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime()); commandContext.getAttachmentEntityManager().insert(attachment, false); if (content != null) { byte[] bytes = IoUtil.readInputStream(content, attachmentName); ByteArrayEntity byteArray = commandContext.getByteArrayEntityManager().create(); byteArray.setBytes(bytes); commandContext.getByteArrayEntityManager().insert(byteArray); attachment.setContentId(byteArray.getId()); attachment.setContent(byteArray); } commandContext.getHistoryManager().createAttachmentComment(taskId, processInstanceId, attachmentName, true); if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { // Forced to fetch the process-instance to associate the right // process definition String processDefinitionId = null; if (attachment.getProcessInstanceId() != null) { ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId); if (process != null) { processDefinitionId = process.getProcessDefinitionId(); } } commandContext.getProcessEngineConfiguration().getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, attachment, processInstanceId, processInstanceId, processDefinitionId)); commandContext.getProcessEngineConfiguration().getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, attachment, processInstanceId, processInstanceId, processDefinitionId)); } return attachment; } protected TaskEntity verifyTaskParameters(CommandContext commandContext) { TaskEntity task = commandContext.getTaskEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isSuspended()) { throw new ActivitiException("It is not allowed to add an attachment to a suspended task"); } return task; } protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) { ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(processInstanceId); if (execution == null) { throw new ActivitiObjectNotFoundException("Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class); } if (execution.isSuspended()) { throw new ActivitiException("It is not allowed to add an attachment to a suspended process instance"); } return execution; } }
Activiti/Activiti
activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/cmd/CreateAttachmentCmd.java
Java
apache-2.0
5,884
package org.seasar.doma.internal.jdbc.dialect; import org.seasar.doma.internal.jdbc.sql.SimpleSqlNodeVisitor; import org.seasar.doma.internal.jdbc.sql.node.AnonymousNode; import org.seasar.doma.jdbc.SqlNode; public class StandardCountCalculatingTransformer extends SimpleSqlNodeVisitor<SqlNode, Void> { protected boolean processed; public SqlNode transform(SqlNode sqlNode) { AnonymousNode result = new AnonymousNode(); for (SqlNode child : sqlNode.getChildren()) { result.appendNode(child.accept(this, null)); } return result; } @Override protected SqlNode defaultAction(SqlNode node, Void p) { return node; } }
domaframework/doma
doma-core/src/main/java/org/seasar/doma/internal/jdbc/dialect/StandardCountCalculatingTransformer.java
Java
apache-2.0
656
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.persistence; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.file.OpenOption; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.managers.communication.GridIoMessage; import org.apache.ignite.internal.processors.cache.CacheGroupContext; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage; import org.apache.ignite.internal.processors.cache.persistence.checkpoint.CheckpointHistory; import org.apache.ignite.internal.processors.cache.persistence.file.FileIO; import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory; import org.apache.ignite.internal.util.lang.GridAbsPredicate; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.plugin.extensions.communication.Message; import org.apache.ignite.spi.IgniteSpiException; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Assert; /** * */ public class LocalWalModeChangeDuringRebalancingSelfTest extends GridCommonAbstractTest { /** */ private static boolean disableWalDuringRebalancing = true; /** */ private static final AtomicReference<CountDownLatch> supplyMessageLatch = new AtomicReference<>(); /** */ private static final AtomicReference<CountDownLatch> fileIOLatch = new AtomicReference<>(); /** Replicated cache name. */ private static final String REPL_CACHE = "cache"; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setDataStorageConfiguration( new DataStorageConfiguration() .setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true) .setMaxSize(200 * 1024 * 1024) .setInitialSize(200 * 1024 * 1024) ) // Test verifies checkpoint count, so it is essencial that no checkpoint is triggered by timeout .setCheckpointFrequency(999_999_999_999L) .setFileIOFactory(new TestFileIOFactory(new DataStorageConfiguration().getFileIOFactory())) ); cfg.setCacheConfiguration( new CacheConfiguration(DEFAULT_CACHE_NAME) // Test checks internal state before and after rebalance, so it is configured to be triggered manually .setRebalanceDelay(-1), new CacheConfiguration(REPL_CACHE) .setRebalanceDelay(-1) .setCacheMode(CacheMode.REPLICATED) ); cfg.setCommunicationSpi(new TcpCommunicationSpi() { @Override public void sendMessage(ClusterNode node, Message msg) throws IgniteSpiException { if (msg instanceof GridIoMessage && ((GridIoMessage)msg).message() instanceof GridDhtPartitionSupplyMessage) { int grpId = ((GridDhtPartitionSupplyMessage)((GridIoMessage)msg).message()).groupId(); if (grpId == CU.cacheId(DEFAULT_CACHE_NAME)) { CountDownLatch latch0 = supplyMessageLatch.get(); if (latch0 != null) try { latch0.await(); } catch (InterruptedException ex) { throw new IgniteException(ex); } } } super.sendMessage(node, msg); } @Override public void sendMessage(ClusterNode node, Message msg, IgniteInClosure<IgniteException> ackC) throws IgniteSpiException { if (msg instanceof GridIoMessage && ((GridIoMessage)msg).message() instanceof GridDhtPartitionSupplyMessage) { int grpId = ((GridDhtPartitionSupplyMessage)((GridIoMessage)msg).message()).groupId(); if (grpId == CU.cacheId(DEFAULT_CACHE_NAME)) { CountDownLatch latch0 = supplyMessageLatch.get(); if (latch0 != null) try { latch0.await(); } catch (InterruptedException ex) { throw new IgniteException(ex); } } } super.sendMessage(node, msg, ackC); } }); cfg.setConsistentId(igniteInstanceName); System.setProperty(IgniteSystemProperties.IGNITE_DISABLE_WAL_DURING_REBALANCING, Boolean.toString(disableWalDuringRebalancing)); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); cleanPersistenceDir(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); CountDownLatch msgLatch = supplyMessageLatch.get(); if (msgLatch != null) { while (msgLatch.getCount() > 0) msgLatch.countDown(); supplyMessageLatch.set(null); } CountDownLatch fileLatch = fileIOLatch.get(); if (fileLatch != null) { while (fileLatch.getCount() > 0) fileLatch.countDown(); fileIOLatch.set(null); } stopAllGrids(); cleanPersistenceDir(); disableWalDuringRebalancing = true; } /** * @return Count of entries to be processed within test. */ protected int getKeysCount() { return 10_000; } /** * @throws Exception If failed. */ public void testWalDisabledDuringRebalancing() throws Exception { doTestSimple(); } /** * @throws Exception If failed. */ public void testWalNotDisabledIfParameterSetToFalse() throws Exception { disableWalDuringRebalancing = false; doTestSimple(); } /** * @throws Exception If failed. */ private void doTestSimple() throws Exception { Ignite ignite = startGrids(3); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); int keysCnt = getKeysCount(); for (int k = 0; k < keysCnt; k++) cache.put(k, k); IgniteEx newIgnite = startGrid(3); final CheckpointHistory cpHist = ((GridCacheDatabaseSharedManager)newIgnite.context().cache().context().database()).checkpointHistory(); GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return !cpHist.checkpoints().isEmpty(); } }, 10_000); U.sleep(10); // To ensure timestamp granularity. long newIgniteStartedTimestamp = System.currentTimeMillis(); ignite.cluster().setBaselineTopology(4); CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group(); assertEquals(!disableWalDuringRebalancing, grpCtx.walEnabled()); U.sleep(10); // To ensure timestamp granularity. long rebalanceStartedTimestamp = System.currentTimeMillis(); for (Ignite g : G.allGrids()) g.cache(DEFAULT_CACHE_NAME).rebalance(); awaitPartitionMapExchange(); assertTrue(grpCtx.walEnabled()); U.sleep(10); // To ensure timestamp granularity. long rebalanceFinishedTimestamp = System.currentTimeMillis(); for (Integer k = 0; k < keysCnt; k++) assertEquals("k=" + k, k, cache.get(k)); int checkpointsBeforeNodeStarted = 0; int checkpointsBeforeRebalance = 0; int checkpointsAfterRebalance = 0; for (Long timestamp : cpHist.checkpoints()) { if (timestamp < newIgniteStartedTimestamp) checkpointsBeforeNodeStarted++; else if (timestamp >= newIgniteStartedTimestamp && timestamp < rebalanceStartedTimestamp) checkpointsBeforeRebalance++; else if (timestamp >= rebalanceStartedTimestamp && timestamp <= rebalanceFinishedTimestamp) checkpointsAfterRebalance++; } assertEquals(1, checkpointsBeforeNodeStarted); // checkpoint on start assertEquals(0, checkpointsBeforeRebalance); assertEquals(disableWalDuringRebalancing ? 1 : 0, checkpointsAfterRebalance); // checkpoint if WAL was re-activated } /** * @throws Exception If failed. */ public void testLocalAndGlobalWalStateInterdependence() throws Exception { Ignite ignite = startGrids(3); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); for (int k = 0; k < getKeysCount(); k++) cache.put(k, k); IgniteEx newIgnite = startGrid(3); ignite.cluster().setBaselineTopology(ignite.cluster().nodes()); CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group(); assertFalse(grpCtx.walEnabled()); ignite.cluster().disableWal(DEFAULT_CACHE_NAME); for (Ignite g : G.allGrids()) g.cache(DEFAULT_CACHE_NAME).rebalance(); awaitPartitionMapExchange(); assertFalse(grpCtx.walEnabled()); // WAL is globally disabled ignite.cluster().enableWal(DEFAULT_CACHE_NAME); assertTrue(grpCtx.walEnabled()); } /** * Test that local WAL mode changing works well with exchanges merge. * * @throws Exception If failed. */ public void testWithExchangesMerge() throws Exception { final int nodeCnt = 5; final int keyCnt = getKeysCount(); Ignite ignite = startGrids(nodeCnt); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(REPL_CACHE); for (int k = 0; k < keyCnt; k++) cache.put(k, k); stopGrid(2); stopGrid(3); stopGrid(4); // Rewrite data to trigger further rebalance. for (int k = 0; k < keyCnt; k++) cache.put(k, k * 2); // Start several grids in parallel to trigger exchanges merge. startGridsMultiThreaded(2, 3); for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) { CacheGroupContext grpCtx = grid(nodeIdx).cachex(REPL_CACHE).context().group(); assertFalse(grpCtx.walEnabled()); } // Invoke rebalance manually. for (Ignite g : G.allGrids()) g.cache(REPL_CACHE).rebalance(); awaitPartitionMapExchange(); for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) { CacheGroupContext grpCtx = grid(nodeIdx).cachex(REPL_CACHE).context().group(); assertTrue(grpCtx.walEnabled()); } // Check no data loss. for (int nodeIdx = 2; nodeIdx < nodeCnt; nodeIdx++) { IgniteCache<Integer, Integer> cache0 = grid(nodeIdx).cache(REPL_CACHE); for (int k = 0; k < keyCnt; k++) Assert.assertEquals("nodeIdx=" + nodeIdx + ", key=" + k, (Integer) (2 * k), cache0.get(k)); } } /** * @throws Exception If failed. */ public void testParallelExchangeDuringRebalance() throws Exception { doTestParallelExchange(supplyMessageLatch); } /** * @throws Exception If failed. */ public void testParallelExchangeDuringCheckpoint() throws Exception { doTestParallelExchange(fileIOLatch); } /** * @throws Exception If failed. */ private void doTestParallelExchange(AtomicReference<CountDownLatch> latchRef) throws Exception { Ignite ignite = startGrids(3); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); for (int k = 0; k < getKeysCount(); k++) cache.put(k, k); IgniteEx newIgnite = startGrid(3); CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group(); CountDownLatch latch = new CountDownLatch(1); latchRef.set(latch); ignite.cluster().setBaselineTopology(ignite.cluster().nodes()); for (Ignite g : G.allGrids()) g.cache(DEFAULT_CACHE_NAME).rebalance(); assertFalse(grpCtx.walEnabled()); // TODO : test with client node as well startGrid(4); // Trigger exchange assertFalse(grpCtx.walEnabled()); latch.countDown(); assertFalse(grpCtx.walEnabled()); for (Ignite g : G.allGrids()) g.cache(DEFAULT_CACHE_NAME).rebalance(); awaitPartitionMapExchange(); assertTrue(grpCtx.walEnabled()); } /** * @throws Exception If failed. */ public void testDataClearedAfterRestartWithDisabledWal() throws Exception { Ignite ignite = startGrid(0); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); int keysCnt = getKeysCount(); for (int k = 0; k < keysCnt; k++) cache.put(k, k); IgniteEx newIgnite = startGrid(1); ignite.cluster().setBaselineTopology(2); CacheGroupContext grpCtx = newIgnite.cachex(DEFAULT_CACHE_NAME).context().group(); assertFalse(grpCtx.localWalEnabled()); stopGrid(1); stopGrid(0); newIgnite = startGrid(1); newIgnite.cluster().active(true); newIgnite.cluster().setBaselineTopology(newIgnite.cluster().nodes()); cache = newIgnite.cache(DEFAULT_CACHE_NAME); for (int k = 0; k < keysCnt; k++) assertFalse("k=" + k +", v=" + cache.get(k), cache.containsKey(k)); } /** * @throws Exception If failed. */ public void testWalNotDisabledAfterShrinkingBaselineTopology() throws Exception { Ignite ignite = startGrids(4); ignite.cluster().active(true); IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); int keysCnt = getKeysCount(); for (int k = 0; k < keysCnt; k++) cache.put(k, k); for (Ignite g : G.allGrids()) { CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group(); assertTrue(grpCtx.walEnabled()); } stopGrid(2); ignite.cluster().setBaselineTopology(5); for (Ignite g : G.allGrids()) { CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group(); assertTrue(grpCtx.walEnabled()); g.cache(DEFAULT_CACHE_NAME).rebalance(); } awaitPartitionMapExchange(); for (Ignite g : G.allGrids()) { CacheGroupContext grpCtx = ((IgniteEx)g).cachex(DEFAULT_CACHE_NAME).context().group(); assertTrue(grpCtx.walEnabled()); } } /** * */ private static class TestFileIOFactory implements FileIOFactory { /** */ private final FileIOFactory delegate; /** * @param delegate Delegate. */ TestFileIOFactory(FileIOFactory delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public FileIO create(File file) throws IOException { return new TestFileIO(delegate.create(file)); } /** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { return new TestFileIO(delegate.create(file, modes)); } } /** * */ private static class TestFileIO implements FileIO { /** */ private final FileIO delegate; /** * @param delegate Delegate. */ TestFileIO(FileIO delegate) { this.delegate = delegate; } /** {@inheritDoc} */ @Override public long position() throws IOException { return delegate.position(); } /** {@inheritDoc} */ @Override public void position(long newPosition) throws IOException { delegate.position(newPosition); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf) throws IOException { return delegate.read(destBuf); } /** {@inheritDoc} */ @Override public int read(ByteBuffer destBuf, long position) throws IOException { return delegate.read(destBuf, position); } /** {@inheritDoc} */ @Override public int read(byte[] buf, int off, int len) throws IOException { return delegate.read(buf, off, len); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf) throws IOException { CountDownLatch latch = fileIOLatch.get(); if (latch != null && Thread.currentThread().getName().contains("checkpoint")) try { latch.await(); } catch (InterruptedException ex) { throw new IgniteException(ex); } return delegate.write(srcBuf); } /** {@inheritDoc} */ @Override public int write(ByteBuffer srcBuf, long position) throws IOException { CountDownLatch latch = fileIOLatch.get(); if (latch != null && Thread.currentThread().getName().contains("checkpoint")) try { latch.await(); } catch (InterruptedException ex) { throw new IgniteException(ex); } return delegate.write(srcBuf, position); } /** {@inheritDoc} */ @Override public int write(byte[] buf, int off, int len) throws IOException { CountDownLatch latch = fileIOLatch.get(); if (latch != null && Thread.currentThread().getName().contains("checkpoint")) try { latch.await(); } catch (InterruptedException ex) { throw new IgniteException(ex); } return delegate.write(buf, off, len); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int maxWalSegmentSize) throws IOException { return delegate.map(maxWalSegmentSize); } /** {@inheritDoc} */ @Override public void force() throws IOException { delegate.force(); } /** {@inheritDoc} */ @Override public void force(boolean withMetadata) throws IOException { delegate.force(withMetadata); } /** {@inheritDoc} */ @Override public long size() throws IOException { return delegate.size(); } /** {@inheritDoc} */ @Override public void clear() throws IOException { delegate.clear(); } /** {@inheritDoc} */ @Override public void close() throws IOException { delegate.close(); } } }
irudyak/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/LocalWalModeChangeDuringRebalancingSelfTest.java
Java
apache-2.0
21,207
package marcin_szyszka.mobileseconndhand.models; /** * Created by marcianno on 2016-03-02. */ public class RegisterUserModel { public String Email; public String Password; public String ConfirmPassword; public RegisterUserModel(){ } }
MarcinSzyszka/MobileSecondHand
AndroidStudio_Android/MobileSeconndHand/app/src/main/java/marcin_szyszka/mobileseconndhand/models/RegisterUserModel.java
Java
apache-2.0
260
package org.annoconf; /** * Created by roma on 3/19/17. */ public interface PropertyValueSource { boolean hasValue(String key); String getValue(String key); }
Roma7-7-7/annoconf
src/main/java/org/annoconf/PropertyValueSource.java
Java
apache-2.0
173