repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
NickAndroid/sinaBlog
2016/app/src/main/java/nick/dev/sina/app/content/SettingsActivity.java
759
/* * Copyright (c) 2016 Nick Guo * * 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 nick.dev.sina.app.content; import com.nick.scalpel.ScalpelAutoActivity; public class SettingsActivity extends ScalpelAutoActivity { }
apache-2.0
hairlun/radix-android
src/com/yuntongxun/ecdemo/photoview/gestures/GestureDetector.java
1027
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.yuntongxun.ecdemo.photoview.gestures; import android.view.MotionEvent; public interface GestureDetector { public boolean onTouchEvent(MotionEvent ev); public boolean isScaling(); public void setOnGestureListener(OnGestureListener listener); }
apache-2.0
vivian8725118/IconTabPageIndicator-master
app/src/main/java/mvc/recyclerview/HFRecyclerAdapter.java
1862
package mvc.recyclerview; import android.support.v7.widget.RecyclerView.Adapter; import android.support.v7.widget.RecyclerView.AdapterDataObserver; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.ViewGroup; public class HFRecyclerAdapter extends HFAdapter { private Adapter adapter; public HFRecyclerAdapter(Adapter adapter) { super(); this.adapter = adapter; adapter.registerAdapterDataObserver(adapterDataObserver); } private AdapterDataObserver adapterDataObserver = new AdapterDataObserver() { public void onChanged() { HFRecyclerAdapter.this.notifyDataSetChanged(); } public void onItemRangeChanged(int positionStart, int itemCount) { HFRecyclerAdapter.this.notifyItemRangeChanged(positionStart + getHeadSize(), itemCount); } public void onItemRangeInserted(int positionStart, int itemCount) { HFRecyclerAdapter.this.notifyItemRangeInserted(positionStart + getHeadSize(), itemCount); } public void onItemRangeRemoved(int positionStart, int itemCount) { HFRecyclerAdapter.this.notifyItemRangeRemoved(positionStart + getHeadSize(), itemCount); } public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { HFRecyclerAdapter.this.notifyItemMoved(fromPosition + getHeadSize(), toPosition + getHeadSize()); } }; @Override public ViewHolder onCreateViewHolderHF(ViewGroup viewGroup, int type) { return adapter.onCreateViewHolder(viewGroup, type); } @Override public void onBindViewHolderHF(ViewHolder vh, int position) { adapter.onBindViewHolder(vh, position); } @Override public int getItemCountHF() { return adapter.getItemCount(); } @Override public int getItemViewTypeHF(int position) { return adapter.getItemViewType(position); } @Override public long getItemIdHF(int position) { return adapter.getItemId(position); } }
apache-2.0
tteofili/jackrabbit-oak
oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/tck/RetentionIT.java
1209
/* * 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.jackrabbit.oak.jcr.tck; import junit.framework.Test; import org.apache.jackrabbit.test.ConcurrentTestSuite; public class RetentionIT extends ConcurrentTestSuite { public static Test suite() { return new RetentionIT(); } public RetentionIT() { super("JCR retention tests"); addTest(org.apache.jackrabbit.test.api.retention.TestAll.suite()); } }
apache-2.0
pagefreezer/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/json/GroupMemberReferenceMixin.java
1244
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api.impl.json; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Annotated mixin to add Jackson annotations to GroupMemberReference. * @author Craig Walls */ @JsonIgnoreProperties(ignoreUnknown = true) abstract class GroupMemberReferenceMixin extends FacebookObjectMixin { @JsonCreator GroupMemberReferenceMixin( @JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("administrator") boolean administrator) {} }
apache-2.0
Krunsh07/jpacman-framework
src/main/java/nl/tudelft/jpacman/sprite/ImageSprite.java
2015
package nl.tudelft.jpacman.sprite; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Transparency; import java.awt.image.BufferedImage; /** * Basic implementation of a Sprite, it merely consists of a static image. * * @author Jeroen Roosen */ public class ImageSprite implements Sprite { /** * Internal image. */ private final Image image; /** * Creates a new sprite from an image. * * @param img * The image to create a sprite from. */ public ImageSprite(Image img) { this.image = img; } @Override public void draw(Graphics g, int x, int y, int width, int height) { g.drawImage(image, x, y, x + width, y + height, 0, 0, image.getWidth(null), image.getHeight(null), null); } @Override public Sprite split(int x, int y, int width, int height) { if (withinImage(x, y) && withinImage(x + width - 1, y + height - 1)) { BufferedImage newImage = newImage(width, height); newImage.createGraphics().drawImage(image, 0, 0, width, height, x, y, x + width, y + height, null); return new ImageSprite(newImage); } return new EmptySprite(); } private boolean withinImage(int x, int y) { return x < image.getWidth(null) && x >= 0 && y < image.getHeight(null) && y >= 0; } /** * Creates a new, empty image of the given width and height. Its * transparency will be a bitmask, so no try ARGB image. * @param width The width of the new image. * @param height The height of the new image. * @return The new, empty image. */ private BufferedImage newImage(int width, int height) { GraphicsConfiguration gc = GraphicsEnvironment .getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); return gc.createCompatibleImage(width, height, Transparency.BITMASK); } @Override public int getWidth() { return image.getWidth(null); } @Override public int getHeight() { return image.getHeight(null); } }
apache-2.0
feishuai/PersonLife
src/com/personlife/net/BaseAsyncHttp.java
1919
package com.personlife.net; import android.content.Context; import android.util.Log; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.personlife.utils.Utils; public class BaseAsyncHttp { public static final String HOST = "http://120.26.218.252:8080/v1"; // public static final String HOST = "http://10.10.105.180:9000/v1"; // private static AsyncHttpClient client = new AsyncHttpClient(); public static void postReq(Context context, String host, String url, RequestParams params, JsonHttpResponseHandler hander) { AsyncHttpClient client = new AsyncHttpClient(); client.post(host + url, params, hander); } public static void postReq(Context context, String url, RequestParams params, JsonHttpResponseHandler hander) { AsyncHttpClient client = new AsyncHttpClient(); if (Utils.isNetworkAvailable(context)) client.post(HOST + url, params, hander); else Utils.showLongToast(context, "请连接网络"); } public static void getReq(Context context, String host, String url, RequestParams params, JsonHttpResponseHandler hander) { AsyncHttpClient client = new AsyncHttpClient(); client.get(host + url, params, hander); } public static void getReq(Context context, String url, RequestParams params, JsonHttpResponseHandler hander) { AsyncHttpClient client = new AsyncHttpClient(); if (Utils.isNetworkAvailable(context)) client.get(HOST + url, params, hander); else Utils.showLongToast(context, "请连接网络"); } public static void downloadFile(Context context, String url, FileDownloadHandler handler) { AsyncHttpClient client = new AsyncHttpClient(); if (Utils.isNetworkAvailable(context)) client.get(url, handler); else Utils.showLongToast(context, "请连接网络"); } }
apache-2.0
nao20010128nao/show-java
app/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableInstruction31i.java
2965
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.immutable.instruction; import org.jf.dexlib2.*; import org.jf.dexlib2.iface.instruction.formats.*; import org.jf.dexlib2.util.*; import javax.annotation.*; public class ImmutableInstruction31i extends ImmutableInstruction implements Instruction31i { public static final Format FORMAT = Format.Format31i; protected final int registerA; protected final int literal; public ImmutableInstruction31i(@Nonnull Opcode opcode, int registerA, int literal) { super(opcode); this.registerA = Preconditions.checkByteRegister(registerA); this.literal = literal; } public static ImmutableInstruction31i of(Instruction31i instruction) { if (instruction instanceof ImmutableInstruction31i) { return (ImmutableInstruction31i) instruction; } return new ImmutableInstruction31i( instruction.getOpcode(), instruction.getRegisterA(), instruction.getNarrowLiteral()); } @Override public int getRegisterA() { return registerA; } @Override public int getNarrowLiteral() { return literal; } @Override public long getWideLiteral() { return literal; } @Override public Format getFormat() { return FORMAT; } }
apache-2.0
LightSun/DataIO
DataIO/src/test/java/com/heaven7/java/data/io/utils/MapGsonAdapter.java
4149
package com.heaven7.java.data.io.utils; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.heaven7.java.visitor.FireVisitor; import com.heaven7.java.visitor.collection.KeyValuePair; import com.heaven7.java.visitor.collection.VisitServices; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * map gson adapter * @author heaven7 */ public abstract class MapGsonAdapter<V> extends TypeAdapter<Map<String, V>> { /* like as array "shot_type_score":[ {"mediumShot":1}, {"mediumLongShot":1}, {"default":1.5} ], as simple: "shot_type_score":{ "mediumShot":1, "mediumLongShot":1, "default":1.5 }, */ @Override public void write(final JsonWriter out, Map<String, V> value) throws IOException { if(asArray()) { out.beginArray(); writeObjectsImpl(out, value); out.endArray(); }else { out.beginObject(); writeSimpleImpl(out, value); out.endObject(); } } @Override public Map<String, V> read(JsonReader in) throws IOException { Map<String, V> map = createMap(); if(asArray()) { in.beginArray(); readObjectsImpl(in, map); in.endArray(); }else{ in.beginObject(); readSimpleImpl(in, map); in.endObject(); } return map; } private void readObjectsImpl(JsonReader in, Map<String, V> map) { try { while (in.hasNext()) { in.beginObject(); String name = in.nextName(); V val = readValue(in); map.put(name, val); in.endObject(); } }catch (IOException e){ throw new RuntimeException(e); } } private void readSimpleImpl(JsonReader in, Map<String, V> map) { try { while (in.hasNext()) { String name = in.nextName(); V val = readValue(in); map.put(name, val); } }catch (IOException e){ throw new RuntimeException(e); } } private void writeObjectsImpl(final JsonWriter out, Map<String, V> value) { VisitServices.from(value).mapPair().fire(new FireVisitor<KeyValuePair<String, V>>() { @Override public Boolean visit(KeyValuePair<String, V> pair, Object param) { try { out.beginObject(); out.name(pair.getKey()); writeValue(out, pair.getValue()); out.endObject(); }catch (IOException e){ throw new RuntimeException(e); } return null; } }); } private void writeSimpleImpl(final JsonWriter out, Map<String, V> value) { VisitServices.from(value).mapPair().fire(new FireVisitor<KeyValuePair<String, V>>() { @Override public Boolean visit(KeyValuePair<String, V> pair, Object param) { try { out.name(pair.getKey()); writeValue(out, pair.getValue()); }catch (IOException e){ throw new RuntimeException(e); } return null; } }); } /** * create map * @return the map */ protected Map<String, V> createMap(){ return new HashMap<>(); } /** * read the value. * @param in the json reader * @return value */ protected abstract V readValue(JsonReader in) throws IOException; /** * write the value * @param out the json writer * @param value the value to write */ protected abstract void writeValue(JsonWriter out, V value) throws IOException; /** * make the out json type is array or object. * @return true if as array. default is false as object. */ protected boolean asArray(){ return false; } }
apache-2.0
gturri/dokuJClient
src/main/java/dw/xmlrpc/exception/DokuMethodDoesNotExistsException.java
276
package dw.xmlrpc.exception; public class DokuMethodDoesNotExistsException extends DokuException { private static final long serialVersionUID = 2005563951980285304L; public DokuMethodDoesNotExistsException(String message, Throwable cause){ super(message, cause); } }
apache-2.0
Nachiket90/jmeter-sample
src/core/org/apache/jmeter/engine/util/UndoVariableReplacement.java
1957
/* * 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. * */ /* * Created on May 4, 2003 */ package org.apache.jmeter.engine.util; import java.util.Map; import org.apache.jmeter.functions.InvalidVariableException; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.util.StringUtilities; /** * Replaces ${key} by value extracted from {@link JMeterVariables} if any */ public class UndoVariableReplacement extends AbstractTransformer { public UndoVariableReplacement(CompoundVariable masterFunction, Map<String, String> variables) { super(); setMasterFunction(masterFunction); setVariables(variables); } @Override public JMeterProperty transformValue(JMeterProperty prop) throws InvalidVariableException { String input = prop.getStringValue(); for (Map.Entry<String, String> entry : getVariables().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); input = StringUtilities.substitute(input, "${" + key + "}", value); } return new StringProperty(prop.getName(), input); } }
apache-2.0
leads-project/multicloud-mr
common/src/main/java/eu/leads/processor/common/infinispan/EnsembleCacheUtils.java
23373
package eu.leads.processor.common.infinispan; import eu.leads.processor.common.StringConstants; import eu.leads.processor.common.utils.PrintUtilities; import eu.leads.processor.conf.LQPConfiguration; import eu.leads.processor.core.Tuple; import eu.leads.processor.infinispan.ComplexIntermediateKey; import org.infinispan.Cache; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.util.concurrent.NotifyingFuture; import org.infinispan.ensemble.EnsembleCacheManager; import org.infinispan.ensemble.Site; import org.infinispan.ensemble.cache.EnsembleCache; import org.infinispan.ensemble.cache.distributed.partitioning.HashBasedPartitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; /** * Created by vagvaz on 3/7/15. */ public class EnsembleCacheUtils { private static Logger log = LoggerFactory.getLogger(EnsembleCacheUtils.class); private static boolean useAsync; private static volatile Object mutex = new Object(); private static Boolean initialized = false; private static int batchSize = 20; private static long threadCounter = 0; private static long threadBatch = 3; private static ThreadPoolExecutor auxExecutor; private static ConcurrentLinkedDeque<SyncPutRunnable> runnables; // private static volatile Object runnableMutex = new Object(); private static ConcurrentHashMap<String, Map<String,TupleBuffer>> microclouds; // private static ConcurrentHashMap<String, List<BatchPutAllAsyncThread>> microcloudThreads; private static HashBasedPartitioner partitioner; private static ConcurrentMap<String,EnsembleCacheManager> ensembleManagers; private static InfinispanManager localManager; private static String localMC; private static ThreadPoolExecutor batchPutExecutor; private static ConcurrentLinkedDeque<BatchPutRunnable> microcloudRunnables; private static int totalBatchPutThreads =16; private static String ensembleString =""; private static ConcurrentLinkedQueue<NotifyingFuture> localFutures; private static int localBatchSize =10; private static boolean isSetup=false; private static volatile java.lang.Object runnableMutex = new Object(); private static volatile java.lang.Object batchRunnableMutex = new Object(); public static void initialize() { synchronized (mutex) { if (initialized) { return; } //Initialize auxiliary put useAsync = LQPConfiguration.getInstance().getConfiguration() .getBoolean("node.infinispan.putasync", true); log.info("Using asynchronous put " + useAsync); // concurrentQuue = new ConcurrentLinkedQueue<>(); batchSize = LQPConfiguration.getInstance().getConfiguration() .getInt("node.ensemble.batchsize", 100); threadBatch = LQPConfiguration.getInstance().getConfiguration().getInt( "node.ensemble.threads", 3); auxExecutor = new ThreadPoolExecutor((int)threadBatch,(int)(threadBatch),1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>()); runnables = new ConcurrentLinkedDeque<>(); for (int i = 0; i <= 10 * (threadBatch); i++) { runnables.add(new SyncPutRunnable()); } initialized = true; //Initialize BatchPut Structures totalBatchPutThreads = LQPConfiguration.getInstance().getConfiguration().getInt("node.ensemble.batchput.threads",4); localBatchSize = LQPConfiguration.getInstance().getConfiguration().getInt("node.ensemble.batchput.batchsize",localBatchSize); System.err.println("threads " + threadBatch + " batchSize " + batchSize + " async = " + useAsync +" batchPutThreads " + totalBatchPutThreads + " localBatch " + localBatchSize); batchPutExecutor = new ThreadPoolExecutor(totalBatchPutThreads,totalBatchPutThreads,2000,TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>()); microclouds = new ConcurrentHashMap<>(); // microcloudThreads = new ConcurrentHashMap<>(); microcloudRunnables = new ConcurrentLinkedDeque<>(); for (int index = 0; index < totalBatchPutThreads; index++){ microcloudRunnables.add(new BatchPutRunnable(3)); } ensembleManagers = new ConcurrentHashMap<>(); partitioner = null; localManager = null; localMC =null; localFutures = new ConcurrentLinkedQueue<NotifyingFuture>(); } } public static void clean() throws ExecutionException, InterruptedException { waitForAllPuts(); localFutures.clear(); for(Map.Entry<String,Map<String,TupleBuffer>> mc : microclouds.entrySet()) { mc.getValue().clear(); partitioner = null; } } public static void initialize(EnsembleCacheManager manager){ initialize(manager, true); } public static void initialize(EnsembleCacheManager manager, boolean isEmbedded) { synchronized (mutex) { // if(isSetup) // { // if(check(manager)){ // return; // }else{ // System.err.println("Serious ERROR init with different managers"); // } // } // isSetup =true; ensembleString = ""; ArrayList<EnsembleCache> cachesList = new ArrayList<>(); for (Object s : new ArrayList<>(manager.sites())) { Site site = (Site) s; ensembleString += site.getName(); cachesList.add(site.getCache()); EnsembleCacheManager emanager = ensembleManagers.get(site.getName()); if (emanager == null) { emanager = new EnsembleCacheManager(site.getName()); ensembleManagers.put(site.getName(), emanager); Map<String,TupleBuffer> newMap = new ConcurrentHashMap<>(); microclouds.putIfAbsent(site.getName(), newMap); } } if(localManager == null && isEmbedded){ localManager = InfinispanClusterSingleton.getInstance().getManager(); if(localMC == null) localMC = resolveMCName(); } partitioner = new HashBasedPartitioner(cachesList); } } private static boolean check(EnsembleCacheManager manager) { // ArrayList<EnsembleCache> cachesList = new ArrayList<>(); String str =""; for (Object s : new ArrayList<>(manager.sites())) { Site site = (Site) s; str += site.getName(); } return ensembleString.equals(str); } private static String resolveMCName() { String result = ""; String externalIp = LQPConfiguration.getInstance().getConfiguration().getString( StringConstants.PUBLIC_IP); if(externalIp == null){ externalIp = LQPConfiguration.getInstance().getConfiguration().getString("node.ip"); } int index = ensembleString.indexOf(externalIp); if(index == -1){ result = null; } else { int lastIndex = ensembleString.lastIndexOf(externalIp) + 6 + externalIp.length(); result = ensembleString.substring(index, lastIndex); } return result; } private static String decideMC(String keyString) { EnsembleCache cache = partitioner.locate(keyString); String result = ""; for(Object s : cache.sites()){ Site site = (Site)s; result = site.getName(); } return result; } public static SyncPutRunnable getRunnable(){ SyncPutRunnable result = null; result = runnables.poll(); while(result == null){ try { Thread.sleep(0, 500000); // Thread.yield(); } catch (InterruptedException e) { e.printStackTrace(); } result = runnables.poll(); // } } return result; } public static BatchPutRunnable getBatchPutRunnable(){ BatchPutRunnable result = null; // synchronized (runnableMutex){ result = microcloudRunnables.poll(); while(result == null){ try { Thread.sleep(0,500000); // Thread.yield(); } catch (InterruptedException e) { e.printStackTrace(); } result = microcloudRunnables.poll(); // } } return result; } public static void addRunnable(SyncPutRunnable runnable){ runnables.add(runnable); } public static void addBatchPutRunnable(BatchPutRunnable runnable){ microcloudRunnables.add(runnable); } public void addLocalFuture(NotifyingFuture future){ localFutures.add(future); } public void removeCompleted(){ Iterator<NotifyingFuture> it = localFutures.iterator(); while(it.hasNext()){ NotifyingFuture f = it.next(); if(f.isDone()){ it.remove(); } } } public static void waitForAuxPuts() throws InterruptedException { while(auxExecutor.getActiveCount() > 0) { try { // auxExecutor.awaitTermination(100,TimeUnit.MILLISECONDS); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); PrintUtilities.logStackTrace(log, e.getStackTrace()); throw e; } } } public static void waitForAllPuts() throws InterruptedException, ExecutionException { // profExecute.start("waitForAllPuts"); // synchronized (runnableMutex){era // runnableMutex.notifyAll(); // } //Flush tuple buffers for(Map.Entry<String,Map<String,TupleBuffer>> mc : microclouds.entrySet()) { for (Map.Entry<String, TupleBuffer> cache : mc.getValue().entrySet()) { if(!mc.getKey().equals(localMC) ) { cache.getValue().flushToMC(); } // else{ // cache.getValue().flushToMC(); // vagvaz } else{ if(cache.getValue().getBuffer().size() > 0) { Cache localCache = (Cache) localManager.getPersisentCache(cache.getKey()); cache.getValue().flushToLocalCache(); // cache.getValue().release(); } } } } //flush remotely batchputlisteners for(Map.Entry<String,Map<String,TupleBuffer>> mc : microclouds.entrySet()){ for(Map.Entry<String,TupleBuffer> cache : mc.getValue().entrySet()){ if(!mc.getKey().equals(localMC)) { cache.getValue().flushEndToMC(); // cache.getValue().flushEndToMC(); // cache.getValue().flushEndToMC(); } // else{//vagvaz // cache.getValue().flushEndToMC(); // } } } while(batchPutExecutor.getActiveCount() > 0){ try { // auxExecutor.awaitTermination(100,TimeUnit.MILLISECONDS); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); PrintUtilities.logStackTrace(log,e.getStackTrace()); throw e; } } while(auxExecutor.getActiveCount() > 0) { try { // auxExecutor.awaitTermination(100,TimeUnit.MILLISECONDS); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); PrintUtilities.logStackTrace(log,e.getStackTrace()); throw e; } } for(NotifyingFuture future : localFutures) { try { if(future != null) future.get(); } catch (InterruptedException e) { e.printStackTrace(); PrintUtilities.logStackTrace(log,e.getStackTrace()); throw e; } catch (ExecutionException e) { e.printStackTrace(); PrintUtilities.logStackTrace(log,e.getStackTrace()); throw e; } } localFutures.clear(); } public static void putToCache(BasicCache cache, Object key, Object value) { batchPutToCache(cache, key, value,true); } private static void batchPutToCache(BasicCache cache, Object key, Object value, boolean b) { if( !((key instanceof String )|| (key instanceof ComplexIntermediateKey)) || !(value instanceof Tuple)){ putToCacheDirect(cache, key, value); } if(b){ if(cache instanceof EnsembleCache){ String mc = EnsembleCacheUtils.decideMC(key.toString()); if(mc.equals(localMC)){ //vagvaz putToMC(cache,key,value,localMC); putToLocalMC(cache,key,value); } else{ putToMC(cache,key,value,mc); } } else{ putToLocalMC(cache,key,value); // putToMC(cache,key,value,localMC); } } else{ putToCacheDirect(cache, key, value); } } private static void putToMC(BasicCache cache, Object key, Object value, String mc) { if(mc == null || mc.equals("")){ log.error("Cache is of type " + cache.getClass().toString() + " but mc is " + mc + " using direct put"); putToCacheDirect(cache,key,value); return; } Map<String,TupleBuffer> buffer = microclouds.get(mc); if(buffer == null) { microclouds.put(mc, new ConcurrentHashMap<String, TupleBuffer>()); } TupleBuffer tupleBuffer = buffer.get(cache.getName()); if(tupleBuffer == null){ tupleBuffer= new TupleBuffer(batchSize,cache.getName(),ensembleManagers.get(mc),mc,null); microclouds.get(mc).put(cache.getName(),tupleBuffer); } if(tupleBuffer.getCacheName()==null) { tupleBuffer.setCacheName(cache.getName()); } if(tupleBuffer.add(key, value)){ BatchPutRunnable runnable = getBatchPutRunnable(); runnable.setBuffer(tupleBuffer); batchPutExecutor.submit(runnable); } } private static void putToLocalMC(BasicCache cache, Object key, Object value) { if(localMC == null){ log.error("Cache is of type " + cache.getClass().toString() + " but localMC is " + localMC + " using direct put"); putToCacheDirect(cache,key,value); return; } Map<String,TupleBuffer> mcBufferMap = microclouds.get(localMC); if(mcBufferMap == null) { // create buffer map for localMC microclouds.put(localMC, new ConcurrentHashMap<String, TupleBuffer>()); } // TupleBuffer tupleBuffer = mcBufferMap.get(cache.getName()); // if(tupleBuffer == null){ // create tuple buffer for cache // tupleBuffer= new TupleBuffer(localBatchSize,cache.getName(),ensembleManagers.get(localMC),localMC); // microclouds.get(localMC).put(cache.getName(),tupleBuffer); // } // if(tupleBuffer.getCacheName()==null) // { // tupleBuffer.setCacheName(cache.getName()); // } // if(tupleBuffer.add(key, (Tuple) value)){ // if(tupleBuffer.getMC().equals(localMC)){ Cache localCache = (Cache) localManager.getPersisentCache( cache.getName()); EnsembleCacheUtils.putToCacheDirect(localCache,key,value); // localFutures.add(tupleBuffer.flushToCache(localCache)); // // tupleBuffer.flushToCache(localCache); // while(localFutures.size() > threadBatch){ // Iterator<NotifyingFuture> iterator = localFutures.iterator(); // while(iterator.hasNext()){ // NotifyingFuture future = iterator.next(); // try { // if(future != null) // { // future.get(10,TimeUnit.MILLISECONDS); // iterator.remove(); // } // else{ // iterator.remove(); // } // } catch (InterruptedException e) { // e.printStackTrace(); // } catch (ExecutionException e) { // e.printStackTrace(); // } catch (TimeoutException e) { // e.printStackTrace(); // } // } // } // } // } } public static void putToCacheDirect(BasicCache cache,Object key,Object value){ if (useAsync) { putToCacheAsync(cache, key, value); return; } putToCacheSync(cache, key, value); } private static void putToCacheSync(BasicCache cache, Object key, Object value) { // profExecute.start("putToCache Sync"); boolean isok = false; while (!isok) { try { if (cache != null) { if (key == null || value == null) { log.error( "SERIOUS PROBLEM with key/value null key: " + (key == null) + " value " + (value == null)); if (key != null) { log.error("key " + key.toString()); } if (value != null) { log.error("value: " + value); } isok = true; continue; } cache.put(key, value); // log.error("Successful " + key); isok = true; } else { log.error("CACHE IS NULL IN PUT TO CACHE for " + key.toString() + " " + value .toString()); isok = true; } } catch (Exception e) { isok = false; log.error("PUT TO CACHE " + e.getMessage() + " " + key); log.error("key " + (key == null) + " value " + (value == null) + " cache " + (cache == null) + " log " + (log == null)); System.err.println("PUT TO CACHE " + e.getMessage()); e.printStackTrace(); if (e.getMessage().startsWith("Cannot perform operations on ")) { e.printStackTrace(); System.exit(-1); } } } // profExecute.end(); } private static void putToCacheAsync(final BasicCache cache, final Object key, final Object value) { // counter = (counter + 1) % Long.MAX_VALUE; // profExecute.start("putToCache Async"); boolean isok = false; while (!isok) { try { if (cache != null) { if (key == null || value == null) { log.error( "SERIOUS PROBLEM with key/value null key: " + (key == null) + " value " + (value == null)); if (key != null) { log.error("key " + key.toString()); } if (value != null) { log.error("value: " + value); } isok = true; continue; } SyncPutRunnable putRunnable = EnsembleCacheUtils.getRunnable(); putRunnable.setParameters(cache,key,value); auxExecutor.submit(putRunnable); isok = true; } else { log.error("CACHE IS NULL IN PUT TO CACHE for " + key.toString() + " " + value .toString()); isok = true; } } catch (Exception e) { isok = false; if(e instanceof RejectedExecutionException){ try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } continue; } log.error("PUT TO CACHE " + e.getMessage() + " " + key); log.error("key " + (key == null) + " value " + (value == null) + " cache " + (cache == null) + " log " + (log == null)); System.err.println("PUT TO CACHE " + e.getMessage()); e.printStackTrace(); if (e.getMessage().startsWith("Cannot perform operations on ")) { e.printStackTrace(); System.exit(-1); } } } } public static <KOut> void putIfAbsentToCache(BasicCache cache, KOut key, KOut value) { putToCache(cache, key, value); } public static void removeCache(String cacheName) { synchronized (mutex) { for (Map.Entry<String, Map<String, TupleBuffer>> entry : microclouds.entrySet()) { Iterator iterator = entry.getValue().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, TupleBuffer> buffer = (Map.Entry<String, TupleBuffer>) iterator.next(); if (buffer.getValue().getCacheName().equals(cacheName)) { buffer.getValue().release(); iterator.remove(); } } } } } }
apache-2.0
SAG-KeLP/kelp-core
src/main/java/it/uniroma2/sag/kelp/data/label/Label.java
1341
/* * Copyright 2014 Simone Filice and Giuseppe Castellucci and Danilo Croce and Roberto Basili * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.uniroma2.sag.kelp.data.label; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; /** * A generic Label for supervised learning. It can identify a class in a * classification task or a number in a regression task. * * @author Simone Filice */ @JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.PROPERTY, property = "labelType") @JsonTypeIdResolver(LabelTypeResolver.class) public interface Label extends Serializable{ @Override public boolean equals(Object label); @Override public int hashCode(); }
apache-2.0
reactor/reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxName.java
3463
/* * Copyright (c) 2016-2021 VMware 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. * 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 reactor.core.publisher; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import reactor.core.CoreSubscriber; import reactor.core.Fuseable; import reactor.util.annotation.Nullable; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import static reactor.core.Scannable.Attr.RUN_STYLE; import static reactor.core.Scannable.Attr.RunStyle.SYNC; /** * An operator that just bears a name or a set of tags, which can be retrieved via the * {@link reactor.core.Scannable.Attr#TAGS TAGS} * attribute. * * @author Simon Baslé * @author Stephane Maldini */ final class FluxName<T> extends InternalFluxOperator<T, T> { final String name; final Set<Tuple2<String, String>> tags; @SuppressWarnings("unchecked") static <T> Flux<T> createOrAppend(Flux<T> source, String name) { Objects.requireNonNull(name, "name"); if (source instanceof FluxName) { FluxName<T> s = (FluxName<T>) source; return new FluxName<>(s.source, name, s.tags); } if (source instanceof FluxNameFuseable) { FluxNameFuseable<T> s = (FluxNameFuseable<T>) source; return new FluxNameFuseable<>(s.source, name, s.tags); } if (source instanceof Fuseable) { return new FluxNameFuseable<>(source, name, null); } return new FluxName<>(source, name, null); } @SuppressWarnings("unchecked") static <T> Flux<T> createOrAppend(Flux<T> source, String tagName, String tagValue) { Objects.requireNonNull(tagName, "tagName"); Objects.requireNonNull(tagValue, "tagValue"); Set<Tuple2<String, String>> tags = Collections.singleton(Tuples.of(tagName, tagValue)); if (source instanceof FluxName) { FluxName<T> s = (FluxName<T>) source; if(s.tags != null) { tags = new HashSet<>(tags); tags.addAll(s.tags); } return new FluxName<>(s.source, s.name, tags); } if (source instanceof FluxNameFuseable) { FluxNameFuseable<T> s = (FluxNameFuseable<T>) source; if (s.tags != null) { tags = new HashSet<>(tags); tags.addAll(s.tags); } return new FluxNameFuseable<>(s.source, s.name, tags); } if (source instanceof Fuseable) { return new FluxNameFuseable<>(source, null, tags); } return new FluxName<>(source, null, tags); } FluxName(Flux<? extends T> source, @Nullable String name, @Nullable Set<Tuple2<String, String>> tags) { super(source); this.name = name; this.tags = tags; } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return actual; } @Nullable @Override public Object scanUnsafe(Attr key) { if (key == Attr.NAME) { return name; } if (key == Attr.TAGS && tags != null) { return tags.stream(); } if (key == RUN_STYLE) { return SYNC; } return super.scanUnsafe(key); } }
apache-2.0
SimonCat1989/simoncat-framework
simoncat-framework-serializer/src/main/java/com/simoncat/framework/serializer/config/SimoncatSerializerConfig.java
504
package com.simoncat.framework.serializer.config; import java.io.IOException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.simoncat.framework.serializer.api.SimoncatSerializer; import com.simoncat.framework.serializer.core.SimoncatSerializerImpl; @Configuration public class SimoncatSerializerConfig { @Bean public SimoncatSerializer serializer() throws IOException { return new SimoncatSerializerImpl(); } }
apache-2.0
gajen0981/FHIR-Server
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/DocumentReference.java
77314
package org.hl7.fhir.instance.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Wed, Feb 18, 2015 12:09-0500 for FHIR v0.4.0 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.instance.model.annotations.ResourceDef; import org.hl7.fhir.instance.model.annotations.SearchParamDefinition; import org.hl7.fhir.instance.model.annotations.Block; import org.hl7.fhir.instance.model.annotations.Child; import org.hl7.fhir.instance.model.annotations.Description; /** * A reference to a document. */ @ResourceDef(name="DocumentReference", profile="http://hl7.org/fhir/Profile/DocumentReference") public class DocumentReference extends DomainResource { public enum DocumentReferenceStatus { /** * This is the current reference for this document. */ CURRENT, /** * This reference has been superseded by another reference. */ SUPERCEDED, /** * This reference was created in error. */ ENTEREDINERROR, /** * added to help the parsers */ NULL; public static DocumentReferenceStatus fromCode(String codeString) throws Exception { if (codeString == null || "".equals(codeString)) return null; if ("current".equals(codeString)) return CURRENT; if ("superceded".equals(codeString)) return SUPERCEDED; if ("entered-in-error".equals(codeString)) return ENTEREDINERROR; throw new Exception("Unknown DocumentReferenceStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case CURRENT: return "current"; case SUPERCEDED: return "superceded"; case ENTEREDINERROR: return "entered-in-error"; default: return "?"; } } public String getSystem() { switch (this) { case CURRENT: return ""; case SUPERCEDED: return ""; case ENTEREDINERROR: return ""; default: return "?"; } } public String getDefinition() { switch (this) { case CURRENT: return "This is the current reference for this document."; case SUPERCEDED: return "This reference has been superseded by another reference."; case ENTEREDINERROR: return "This reference was created in error."; default: return "?"; } } public String getDisplay() { switch (this) { case CURRENT: return "current"; case SUPERCEDED: return "superceded"; case ENTEREDINERROR: return "entered-in-error"; default: return "?"; } } } public static class DocumentReferenceStatusEnumFactory implements EnumFactory<DocumentReferenceStatus> { public DocumentReferenceStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("current".equals(codeString)) return DocumentReferenceStatus.CURRENT; if ("superceded".equals(codeString)) return DocumentReferenceStatus.SUPERCEDED; if ("entered-in-error".equals(codeString)) return DocumentReferenceStatus.ENTEREDINERROR; throw new IllegalArgumentException("Unknown DocumentReferenceStatus code '"+codeString+"'"); } public String toCode(DocumentReferenceStatus code) { if (code == DocumentReferenceStatus.CURRENT) return "current"; if (code == DocumentReferenceStatus.SUPERCEDED) return "superceded"; if (code == DocumentReferenceStatus.ENTEREDINERROR) return "entered-in-error"; return "?"; } } public enum DocumentRelationshipType { /** * This document logically replaces or supercedes the target document. */ REPLACES, /** * This document was generated by transforming the target document (e.g. format or language conversion). */ TRANSFORMS, /** * This document is a signature of the target document. */ SIGNS, /** * This document adds additional information to the target document. */ APPENDS, /** * added to help the parsers */ NULL; public static DocumentRelationshipType fromCode(String codeString) throws Exception { if (codeString == null || "".equals(codeString)) return null; if ("replaces".equals(codeString)) return REPLACES; if ("transforms".equals(codeString)) return TRANSFORMS; if ("signs".equals(codeString)) return SIGNS; if ("appends".equals(codeString)) return APPENDS; throw new Exception("Unknown DocumentRelationshipType code '"+codeString+"'"); } public String toCode() { switch (this) { case REPLACES: return "replaces"; case TRANSFORMS: return "transforms"; case SIGNS: return "signs"; case APPENDS: return "appends"; default: return "?"; } } public String getSystem() { switch (this) { case REPLACES: return ""; case TRANSFORMS: return ""; case SIGNS: return ""; case APPENDS: return ""; default: return "?"; } } public String getDefinition() { switch (this) { case REPLACES: return "This document logically replaces or supercedes the target document."; case TRANSFORMS: return "This document was generated by transforming the target document (e.g. format or language conversion)."; case SIGNS: return "This document is a signature of the target document."; case APPENDS: return "This document adds additional information to the target document."; default: return "?"; } } public String getDisplay() { switch (this) { case REPLACES: return "replaces"; case TRANSFORMS: return "transforms"; case SIGNS: return "signs"; case APPENDS: return "appends"; default: return "?"; } } } public static class DocumentRelationshipTypeEnumFactory implements EnumFactory<DocumentRelationshipType> { public DocumentRelationshipType fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("replaces".equals(codeString)) return DocumentRelationshipType.REPLACES; if ("transforms".equals(codeString)) return DocumentRelationshipType.TRANSFORMS; if ("signs".equals(codeString)) return DocumentRelationshipType.SIGNS; if ("appends".equals(codeString)) return DocumentRelationshipType.APPENDS; throw new IllegalArgumentException("Unknown DocumentRelationshipType code '"+codeString+"'"); } public String toCode(DocumentRelationshipType code) { if (code == DocumentRelationshipType.REPLACES) return "replaces"; if (code == DocumentRelationshipType.TRANSFORMS) return "transforms"; if (code == DocumentRelationshipType.SIGNS) return "signs"; if (code == DocumentRelationshipType.APPENDS) return "appends"; return "?"; } } @Block() public static class DocumentReferenceRelatesToComponent extends BackboneElement { /** * The type of relationship that this document has with anther document. */ @Child(name="code", type={CodeType.class}, order=1, min=1, max=1) @Description(shortDefinition="replaces | transforms | signs | appends", formalDefinition="The type of relationship that this document has with anther document." ) protected Enumeration<DocumentRelationshipType> code; /** * The target document of this relationship. */ @Child(name="target", type={DocumentReference.class}, order=2, min=1, max=1) @Description(shortDefinition="Target of the relationship", formalDefinition="The target document of this relationship." ) protected Reference target; /** * The actual object that is the target of the reference (The target document of this relationship.) */ protected DocumentReference targetTarget; private static final long serialVersionUID = -347257495L; public DocumentReferenceRelatesToComponent() { super(); } public DocumentReferenceRelatesToComponent(Enumeration<DocumentRelationshipType> code, Reference target) { super(); this.code = code; this.target = target; } /** * @return {@link #code} (The type of relationship that this document has with anther document.). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value */ public Enumeration<DocumentRelationshipType> getCodeElement() { if (this.code == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReferenceRelatesToComponent.code"); else if (Configuration.doAutoCreate()) this.code = new Enumeration<DocumentRelationshipType>(new DocumentRelationshipTypeEnumFactory()); // bb return this.code; } public boolean hasCodeElement() { return this.code != null && !this.code.isEmpty(); } public boolean hasCode() { return this.code != null && !this.code.isEmpty(); } /** * @param value {@link #code} (The type of relationship that this document has with anther document.). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value */ public DocumentReferenceRelatesToComponent setCodeElement(Enumeration<DocumentRelationshipType> value) { this.code = value; return this; } /** * @return The type of relationship that this document has with anther document. */ public DocumentRelationshipType getCode() { return this.code == null ? null : this.code.getValue(); } /** * @param value The type of relationship that this document has with anther document. */ public DocumentReferenceRelatesToComponent setCode(DocumentRelationshipType value) { if (this.code == null) this.code = new Enumeration<DocumentRelationshipType>(new DocumentRelationshipTypeEnumFactory()); this.code.setValue(value); return this; } /** * @return {@link #target} (The target document of this relationship.) */ public Reference getTarget() { if (this.target == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReferenceRelatesToComponent.target"); else if (Configuration.doAutoCreate()) this.target = new Reference(); // cc return this.target; } public boolean hasTarget() { return this.target != null && !this.target.isEmpty(); } /** * @param value {@link #target} (The target document of this relationship.) */ public DocumentReferenceRelatesToComponent setTarget(Reference value) { this.target = value; return this; } /** * @return {@link #target} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The target document of this relationship.) */ public DocumentReference getTargetTarget() { if (this.targetTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReferenceRelatesToComponent.target"); else if (Configuration.doAutoCreate()) this.targetTarget = new DocumentReference(); // aa return this.targetTarget; } /** * @param value {@link #target} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The target document of this relationship.) */ public DocumentReferenceRelatesToComponent setTargetTarget(DocumentReference value) { this.targetTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("code", "code", "The type of relationship that this document has with anther document.", 0, java.lang.Integer.MAX_VALUE, code)); childrenList.add(new Property("target", "Reference(DocumentReference)", "The target document of this relationship.", 0, java.lang.Integer.MAX_VALUE, target)); } public DocumentReferenceRelatesToComponent copy() { DocumentReferenceRelatesToComponent dst = new DocumentReferenceRelatesToComponent(); copyValues(dst); dst.code = code == null ? null : code.copy(); dst.target = target == null ? null : target.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof DocumentReferenceRelatesToComponent)) return false; DocumentReferenceRelatesToComponent o = (DocumentReferenceRelatesToComponent) other; return compareDeep(code, o.code, true) && compareDeep(target, o.target, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof DocumentReferenceRelatesToComponent)) return false; DocumentReferenceRelatesToComponent o = (DocumentReferenceRelatesToComponent) other; return compareValues(code, o.code, true); } public boolean isEmpty() { return super.isEmpty() && (code == null || code.isEmpty()) && (target == null || target.isEmpty()) ; } } @Block() public static class DocumentReferenceContextComponent extends BackboneElement { /** * This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act. */ @Child(name="event", type={CodeableConcept.class}, order=1, min=0, max=Child.MAX_UNLIMITED) @Description(shortDefinition="Main Clinical Acts Documented", formalDefinition="This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a 'History and Physical Report' in which the procedure being documented is necessarily a 'History and Physical' act." ) protected List<CodeableConcept> event; /** * The time period over which the service that is described by the document was provided. */ @Child(name="period", type={Period.class}, order=2, min=0, max=1) @Description(shortDefinition="Time of service that is being documented", formalDefinition="The time period over which the service that is described by the document was provided." ) protected Period period; /** * The kind of facility where the patient was seen. */ @Child(name="facilityType", type={CodeableConcept.class}, order=3, min=0, max=1) @Description(shortDefinition="Kind of facility where patient was seen", formalDefinition="The kind of facility where the patient was seen." ) protected CodeableConcept facilityType; private static final long serialVersionUID = -1762960949L; public DocumentReferenceContextComponent() { super(); } /** * @return {@link #event} (This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act.) */ public List<CodeableConcept> getEvent() { if (this.event == null) this.event = new ArrayList<CodeableConcept>(); return this.event; } public boolean hasEvent() { if (this.event == null) return false; for (CodeableConcept item : this.event) if (!item.isEmpty()) return true; return false; } /** * @return {@link #event} (This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act.) */ // syntactic sugar public CodeableConcept addEvent() { //3 CodeableConcept t = new CodeableConcept(); if (this.event == null) this.event = new ArrayList<CodeableConcept>(); this.event.add(t); return t; } /** * @return {@link #period} (The time period over which the service that is described by the document was provided.) */ public Period getPeriod() { if (this.period == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReferenceContextComponent.period"); else if (Configuration.doAutoCreate()) this.period = new Period(); // cc return this.period; } public boolean hasPeriod() { return this.period != null && !this.period.isEmpty(); } /** * @param value {@link #period} (The time period over which the service that is described by the document was provided.) */ public DocumentReferenceContextComponent setPeriod(Period value) { this.period = value; return this; } /** * @return {@link #facilityType} (The kind of facility where the patient was seen.) */ public CodeableConcept getFacilityType() { if (this.facilityType == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReferenceContextComponent.facilityType"); else if (Configuration.doAutoCreate()) this.facilityType = new CodeableConcept(); // cc return this.facilityType; } public boolean hasFacilityType() { return this.facilityType != null && !this.facilityType.isEmpty(); } /** * @param value {@link #facilityType} (The kind of facility where the patient was seen.) */ public DocumentReferenceContextComponent setFacilityType(CodeableConcept value) { this.facilityType = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("event", "CodeableConcept", "This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a 'History and Physical Report' in which the procedure being documented is necessarily a 'History and Physical' act.", 0, java.lang.Integer.MAX_VALUE, event)); childrenList.add(new Property("period", "Period", "The time period over which the service that is described by the document was provided.", 0, java.lang.Integer.MAX_VALUE, period)); childrenList.add(new Property("facilityType", "CodeableConcept", "The kind of facility where the patient was seen.", 0, java.lang.Integer.MAX_VALUE, facilityType)); } public DocumentReferenceContextComponent copy() { DocumentReferenceContextComponent dst = new DocumentReferenceContextComponent(); copyValues(dst); if (event != null) { dst.event = new ArrayList<CodeableConcept>(); for (CodeableConcept i : event) dst.event.add(i.copy()); }; dst.period = period == null ? null : period.copy(); dst.facilityType = facilityType == null ? null : facilityType.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof DocumentReferenceContextComponent)) return false; DocumentReferenceContextComponent o = (DocumentReferenceContextComponent) other; return compareDeep(event, o.event, true) && compareDeep(period, o.period, true) && compareDeep(facilityType, o.facilityType, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof DocumentReferenceContextComponent)) return false; DocumentReferenceContextComponent o = (DocumentReferenceContextComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && (event == null || event.isEmpty()) && (period == null || period.isEmpty()) && (facilityType == null || facilityType.isEmpty()); } } /** * Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document. */ @Child(name = "masterIdentifier", type = {Identifier.class}, order = 0, min = 0, max = 1) @Description(shortDefinition="Master Version Specific Identifier", formalDefinition="Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document." ) protected Identifier masterIdentifier; /** * Other identifiers associated with the document, including version independent, source record and workflow related identifiers. */ @Child(name = "identifier", type = {Identifier.class}, order = 1, min = 0, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Other identifiers for the document", formalDefinition="Other identifiers associated with the document, including version independent, source record and workflow related identifiers." ) protected List<Identifier> identifier; /** * Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure). */ @Child(name = "subject", type = {Patient.class, Practitioner.class, Group.class, Device.class}, order = 2, min = 0, max = 1) @Description(shortDefinition="Who|what is the subject of the document", formalDefinition="Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure)." ) protected Reference subject; /** * The actual object that is the target of the reference (Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).) */ protected Resource subjectTarget; /** * The type code specifies the precise type of document from the user perspective. It is recommended that the value Set be drawn from a coding scheme providing a fine level of granularity such as LOINC. (e.g. Patient Summary, Discharge Summary, Prescription, etc.). */ @Child(name = "type", type = {CodeableConcept.class}, order = 3, min = 1, max = 1) @Description(shortDefinition="Precice type of document", formalDefinition="The type code specifies the precise type of document from the user perspective. It is recommended that the value Set be drawn from a coding scheme providing a fine level of granularity such as LOINC. (e.g. Patient Summary, Discharge Summary, Prescription, etc.)." ) protected CodeableConcept type; /** * The class code specifying the high-level use classification of the document type (e.g., Report, Summary, Images, Treatment Plan, Patient Preferences, Workflow). */ @Child(name = "class_", type = {CodeableConcept.class}, order = 4, min = 0, max = 1) @Description(shortDefinition="High-level classification of document", formalDefinition="The class code specifying the high-level use classification of the document type (e.g., Report, Summary, Images, Treatment Plan, Patient Preferences, Workflow)." ) protected CodeableConcept class_; /** * An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType. */ @Child(name = "format", type = {UriType.class}, order = 5, min = 0, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Format/content rules for the document", formalDefinition="An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType." ) protected List<UriType> format; /** * Identifies who is responsible for adding the information to the document. */ @Child(name = "author", type = {Practitioner.class, Organization.class, Device.class, Patient.class, RelatedPerson.class}, order = 6, min = 1, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Who and/or what authored the document", formalDefinition="Identifies who is responsible for adding the information to the document." ) protected List<Reference> author; /** * The actual objects that are the target of the reference (Identifies who is responsible for adding the information to the document.) */ protected List<Resource> authorTarget; /** * Identifies the organization or group who is responsible for ongoing maintenance of and access to the document. */ @Child(name = "custodian", type = {Organization.class}, order = 7, min = 0, max = 1) @Description(shortDefinition="Org which maintains the document", formalDefinition="Identifies the organization or group who is responsible for ongoing maintenance of and access to the document." ) protected Reference custodian; /** * The actual object that is the target of the reference (Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.) */ protected Organization custodianTarget; /** * A reference to a domain or server that manages policies under which the document is accessed and/or made available. */ @Child(name = "policyManager", type = {UriType.class}, order = 8, min = 0, max = 1) @Description(shortDefinition="Manages access policies for the document", formalDefinition="A reference to a domain or server that manages policies under which the document is accessed and/or made available." ) protected UriType policyManager; /** * Which person or organization authenticates that this document is valid. */ @Child(name = "authenticator", type = {Practitioner.class, Organization.class}, order = 9, min = 0, max = 1) @Description(shortDefinition="Who/What authenticated the document", formalDefinition="Which person or organization authenticates that this document is valid." ) protected Reference authenticator; /** * The actual object that is the target of the reference (Which person or organization authenticates that this document is valid.) */ protected Resource authenticatorTarget; /** * When the document was created. */ @Child(name = "created", type = {DateTimeType.class}, order = 10, min = 0, max = 1) @Description(shortDefinition="Document creation time", formalDefinition="When the document was created." ) protected DateTimeType created; /** * When the document reference was created. */ @Child(name = "indexed", type = {InstantType.class}, order = 11, min = 1, max = 1) @Description(shortDefinition="When this document reference created", formalDefinition="When the document reference was created." ) protected InstantType indexed; /** * The status of this document reference. */ @Child(name = "status", type = {CodeType.class}, order = 12, min = 1, max = 1) @Description(shortDefinition="current | superceded | entered-in-error", formalDefinition="The status of this document reference." ) protected Enumeration<DocumentReferenceStatus> status; /** * The status of the underlying document. */ @Child(name = "docStatus", type = {CodeableConcept.class}, order = 13, min = 0, max = 1) @Description(shortDefinition="preliminary | final | appended | amended | entered-in-error", formalDefinition="The status of the underlying document." ) protected CodeableConcept docStatus; /** * Relationships that this document has with other document references that already exist. */ @Child(name = "relatesTo", type = {}, order = 14, min = 0, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Relationships to other documents", formalDefinition="Relationships that this document has with other document references that already exist." ) protected List<DocumentReferenceRelatesToComponent> relatesTo; /** * Human-readable description of the source document. This is sometimes known as the "title". */ @Child(name = "description", type = {StringType.class}, order = 15, min = 0, max = 1) @Description(shortDefinition="Human-readable description (title)", formalDefinition="Human-readable description of the source document. This is sometimes known as the 'title'." ) protected StringType description; /** * A set of Security-Tag codes specifying the level of privacy/security of the Document. */ @Child(name = "confidentiality", type = {CodeableConcept.class}, order = 16, min = 0, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Sensitivity of source document", formalDefinition="A set of Security-Tag codes specifying the level of privacy/security of the Document." ) protected List<CodeableConcept> confidentiality; /** * The document or url to the document along with critical metadata to prove content has integrity. */ @Child(name = "content", type = {Attachment.class}, order = 17, min = 1, max = Child.MAX_UNLIMITED) @Description(shortDefinition="Where to access the document", formalDefinition="The document or url to the document along with critical metadata to prove content has integrity." ) protected List<Attachment> content; /** * The clinical context in which the document was prepared. */ @Child(name = "context", type = {}, order = 18, min = 0, max = 1) @Description(shortDefinition="Clinical context of document", formalDefinition="The clinical context in which the document was prepared." ) protected DocumentReferenceContextComponent context; private static final long serialVersionUID = -392974585L; public DocumentReference() { super(); } public DocumentReference(CodeableConcept type, InstantType indexed, Enumeration<DocumentReferenceStatus> status) { super(); this.type = type; this.indexed = indexed; this.status = status; } /** * @return {@link #masterIdentifier} (Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document.) */ public Identifier getMasterIdentifier() { if (this.masterIdentifier == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.masterIdentifier"); else if (Configuration.doAutoCreate()) this.masterIdentifier = new Identifier(); // cc return this.masterIdentifier; } public boolean hasMasterIdentifier() { return this.masterIdentifier != null && !this.masterIdentifier.isEmpty(); } /** * @param value {@link #masterIdentifier} (Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document.) */ public DocumentReference setMasterIdentifier(Identifier value) { this.masterIdentifier = value; return this; } /** * @return {@link #identifier} (Other identifiers associated with the document, including version independent, source record and workflow related identifiers.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } /** * @return {@link #identifier} (Other identifiers associated with the document, including version independent, source record and workflow related identifiers.) */ // syntactic sugar public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } /** * @return {@link #subject} (Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).) */ public Reference getSubject() { if (this.subject == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.subject"); else if (Configuration.doAutoCreate()) this.subject = new Reference(); // cc return this.subject; } public boolean hasSubject() { return this.subject != null && !this.subject.isEmpty(); } /** * @param value {@link #subject} (Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).) */ public DocumentReference setSubject(Reference value) { this.subject = value; return this; } /** * @return {@link #subject} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).) */ public Resource getSubjectTarget() { return this.subjectTarget; } /** * @param value {@link #subject} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).) */ public DocumentReference setSubjectTarget(Resource value) { this.subjectTarget = value; return this; } /** * @return {@link #type} (The type code specifies the precise type of document from the user perspective. It is recommended that the value Set be drawn from a coding scheme providing a fine level of granularity such as LOINC. (e.g. Patient Summary, Discharge Summary, Prescription, etc.).) */ public CodeableConcept getType() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.type"); else if (Configuration.doAutoCreate()) this.type = new CodeableConcept(); // cc return this.type; } public boolean hasType() { return this.type != null && !this.type.isEmpty(); } /** * @param value {@link #type} (The type code specifies the precise type of document from the user perspective. It is recommended that the value Set be drawn from a coding scheme providing a fine level of granularity such as LOINC. (e.g. Patient Summary, Discharge Summary, Prescription, etc.).) */ public DocumentReference setType(CodeableConcept value) { this.type = value; return this; } /** * @return {@link #class_} (The class code specifying the high-level use classification of the document type (e.g., Report, Summary, Images, Treatment Plan, Patient Preferences, Workflow).) */ public CodeableConcept getClass_() { if (this.class_ == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.class_"); else if (Configuration.doAutoCreate()) this.class_ = new CodeableConcept(); // cc return this.class_; } public boolean hasClass_() { return this.class_ != null && !this.class_.isEmpty(); } /** * @param value {@link #class_} (The class code specifying the high-level use classification of the document type (e.g., Report, Summary, Images, Treatment Plan, Patient Preferences, Workflow).) */ public DocumentReference setClass_(CodeableConcept value) { this.class_ = value; return this; } /** * @return {@link #format} (An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType.) */ public List<UriType> getFormat() { if (this.format == null) this.format = new ArrayList<UriType>(); return this.format; } public boolean hasFormat() { if (this.format == null) return false; for (UriType item : this.format) if (!item.isEmpty()) return true; return false; } /** * @return {@link #format} (An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType.) */ // syntactic sugar public UriType addFormatElement() {//2 UriType t = new UriType(); if (this.format == null) this.format = new ArrayList<UriType>(); this.format.add(t); return t; } /** * @param value {@link #format} (An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType.) */ public DocumentReference addFormat(String value) { //1 UriType t = new UriType(); t.setValue(value); if (this.format == null) this.format = new ArrayList<UriType>(); this.format.add(t); return this; } /** * @param value {@link #format} (An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType.) */ public boolean hasFormat(String value) { if (this.format == null) return false; for (UriType v : this.format) if (v.equals(value)) // uri return true; return false; } /** * @return {@link #author} (Identifies who is responsible for adding the information to the document.) */ public List<Reference> getAuthor() { if (this.author == null) this.author = new ArrayList<Reference>(); return this.author; } public boolean hasAuthor() { if (this.author == null) return false; for (Reference item : this.author) if (!item.isEmpty()) return true; return false; } /** * @return {@link #author} (Identifies who is responsible for adding the information to the document.) */ // syntactic sugar public Reference addAuthor() { //3 Reference t = new Reference(); if (this.author == null) this.author = new ArrayList<Reference>(); this.author.add(t); return t; } /** * @return {@link #author} (The actual objects that are the target of the reference. The reference library doesn't populate this, but you can use this to hold the resources if you resolvethemt. Identifies who is responsible for adding the information to the document.) */ public List<Resource> getAuthorTarget() { if (this.authorTarget == null) this.authorTarget = new ArrayList<Resource>(); return this.authorTarget; } /** * @return {@link #custodian} (Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.) */ public Reference getCustodian() { if (this.custodian == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.custodian"); else if (Configuration.doAutoCreate()) this.custodian = new Reference(); // cc return this.custodian; } public boolean hasCustodian() { return this.custodian != null && !this.custodian.isEmpty(); } /** * @param value {@link #custodian} (Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.) */ public DocumentReference setCustodian(Reference value) { this.custodian = value; return this; } /** * @return {@link #custodian} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.) */ public Organization getCustodianTarget() { if (this.custodianTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.custodian"); else if (Configuration.doAutoCreate()) this.custodianTarget = new Organization(); // aa return this.custodianTarget; } /** * @param value {@link #custodian} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.) */ public DocumentReference setCustodianTarget(Organization value) { this.custodianTarget = value; return this; } /** * @return {@link #policyManager} (A reference to a domain or server that manages policies under which the document is accessed and/or made available.). This is the underlying object with id, value and extensions. The accessor "getPolicyManager" gives direct access to the value */ public UriType getPolicyManagerElement() { if (this.policyManager == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.policyManager"); else if (Configuration.doAutoCreate()) this.policyManager = new UriType(); // bb return this.policyManager; } public boolean hasPolicyManagerElement() { return this.policyManager != null && !this.policyManager.isEmpty(); } public boolean hasPolicyManager() { return this.policyManager != null && !this.policyManager.isEmpty(); } /** * @param value {@link #policyManager} (A reference to a domain or server that manages policies under which the document is accessed and/or made available.). This is the underlying object with id, value and extensions. The accessor "getPolicyManager" gives direct access to the value */ public DocumentReference setPolicyManagerElement(UriType value) { this.policyManager = value; return this; } /** * @return A reference to a domain or server that manages policies under which the document is accessed and/or made available. */ public String getPolicyManager() { return this.policyManager == null ? null : this.policyManager.getValue(); } /** * @param value A reference to a domain or server that manages policies under which the document is accessed and/or made available. */ public DocumentReference setPolicyManager(String value) { if (Utilities.noString(value)) this.policyManager = null; else { if (this.policyManager == null) this.policyManager = new UriType(); this.policyManager.setValue(value); } return this; } /** * @return {@link #authenticator} (Which person or organization authenticates that this document is valid.) */ public Reference getAuthenticator() { if (this.authenticator == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.authenticator"); else if (Configuration.doAutoCreate()) this.authenticator = new Reference(); // cc return this.authenticator; } public boolean hasAuthenticator() { return this.authenticator != null && !this.authenticator.isEmpty(); } /** * @param value {@link #authenticator} (Which person or organization authenticates that this document is valid.) */ public DocumentReference setAuthenticator(Reference value) { this.authenticator = value; return this; } /** * @return {@link #authenticator} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Which person or organization authenticates that this document is valid.) */ public Resource getAuthenticatorTarget() { return this.authenticatorTarget; } /** * @param value {@link #authenticator} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Which person or organization authenticates that this document is valid.) */ public DocumentReference setAuthenticatorTarget(Resource value) { this.authenticatorTarget = value; return this; } /** * @return {@link #created} (When the document was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value */ public DateTimeType getCreatedElement() { if (this.created == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.created"); else if (Configuration.doAutoCreate()) this.created = new DateTimeType(); // bb return this.created; } public boolean hasCreatedElement() { return this.created != null && !this.created.isEmpty(); } public boolean hasCreated() { return this.created != null && !this.created.isEmpty(); } /** * @param value {@link #created} (When the document was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value */ public DocumentReference setCreatedElement(DateTimeType value) { this.created = value; return this; } /** * @return When the document was created. */ public Date getCreated() { return this.created == null ? null : this.created.getValue(); } /** * @param value When the document was created. */ public DocumentReference setCreated(Date value) { if (value == null) this.created = null; else { if (this.created == null) this.created = new DateTimeType(); this.created.setValue(value); } return this; } /** * @return {@link #indexed} (When the document reference was created.). This is the underlying object with id, value and extensions. The accessor "getIndexed" gives direct access to the value */ public InstantType getIndexedElement() { if (this.indexed == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.indexed"); else if (Configuration.doAutoCreate()) this.indexed = new InstantType(); // bb return this.indexed; } public boolean hasIndexedElement() { return this.indexed != null && !this.indexed.isEmpty(); } public boolean hasIndexed() { return this.indexed != null && !this.indexed.isEmpty(); } /** * @param value {@link #indexed} (When the document reference was created.). This is the underlying object with id, value and extensions. The accessor "getIndexed" gives direct access to the value */ public DocumentReference setIndexedElement(InstantType value) { this.indexed = value; return this; } /** * @return When the document reference was created. */ public Date getIndexed() { return this.indexed == null ? null : this.indexed.getValue(); } /** * @param value When the document reference was created. */ public DocumentReference setIndexed(Date value) { if (this.indexed == null) this.indexed = new InstantType(); this.indexed.setValue(value); return this; } /** * @return {@link #status} (The status of this document reference.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Enumeration<DocumentReferenceStatus> getStatusElement() { if (this.status == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.status"); else if (Configuration.doAutoCreate()) this.status = new Enumeration<DocumentReferenceStatus>(new DocumentReferenceStatusEnumFactory()); // bb return this.status; } public boolean hasStatusElement() { return this.status != null && !this.status.isEmpty(); } public boolean hasStatus() { return this.status != null && !this.status.isEmpty(); } /** * @param value {@link #status} (The status of this document reference.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public DocumentReference setStatusElement(Enumeration<DocumentReferenceStatus> value) { this.status = value; return this; } /** * @return The status of this document reference. */ public DocumentReferenceStatus getStatus() { return this.status == null ? null : this.status.getValue(); } /** * @param value The status of this document reference. */ public DocumentReference setStatus(DocumentReferenceStatus value) { if (this.status == null) this.status = new Enumeration<DocumentReferenceStatus>(new DocumentReferenceStatusEnumFactory()); this.status.setValue(value); return this; } /** * @return {@link #docStatus} (The status of the underlying document.) */ public CodeableConcept getDocStatus() { if (this.docStatus == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.docStatus"); else if (Configuration.doAutoCreate()) this.docStatus = new CodeableConcept(); // cc return this.docStatus; } public boolean hasDocStatus() { return this.docStatus != null && !this.docStatus.isEmpty(); } /** * @param value {@link #docStatus} (The status of the underlying document.) */ public DocumentReference setDocStatus(CodeableConcept value) { this.docStatus = value; return this; } /** * @return {@link #relatesTo} (Relationships that this document has with other document references that already exist.) */ public List<DocumentReferenceRelatesToComponent> getRelatesTo() { if (this.relatesTo == null) this.relatesTo = new ArrayList<DocumentReferenceRelatesToComponent>(); return this.relatesTo; } public boolean hasRelatesTo() { if (this.relatesTo == null) return false; for (DocumentReferenceRelatesToComponent item : this.relatesTo) if (!item.isEmpty()) return true; return false; } /** * @return {@link #relatesTo} (Relationships that this document has with other document references that already exist.) */ // syntactic sugar public DocumentReferenceRelatesToComponent addRelatesTo() { //3 DocumentReferenceRelatesToComponent t = new DocumentReferenceRelatesToComponent(); if (this.relatesTo == null) this.relatesTo = new ArrayList<DocumentReferenceRelatesToComponent>(); this.relatesTo.add(t); return t; } /** * @return {@link #description} (Human-readable description of the source document. This is sometimes known as the "title".). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public StringType getDescriptionElement() { if (this.description == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.description"); else if (Configuration.doAutoCreate()) this.description = new StringType(); // bb return this.description; } public boolean hasDescriptionElement() { return this.description != null && !this.description.isEmpty(); } public boolean hasDescription() { return this.description != null && !this.description.isEmpty(); } /** * @param value {@link #description} (Human-readable description of the source document. This is sometimes known as the "title".). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value */ public DocumentReference setDescriptionElement(StringType value) { this.description = value; return this; } /** * @return Human-readable description of the source document. This is sometimes known as the "title". */ public String getDescription() { return this.description == null ? null : this.description.getValue(); } /** * @param value Human-readable description of the source document. This is sometimes known as the "title". */ public DocumentReference setDescription(String value) { if (Utilities.noString(value)) this.description = null; else { if (this.description == null) this.description = new StringType(); this.description.setValue(value); } return this; } /** * @return {@link #confidentiality} (A set of Security-Tag codes specifying the level of privacy/security of the Document.) */ public List<CodeableConcept> getConfidentiality() { if (this.confidentiality == null) this.confidentiality = new ArrayList<CodeableConcept>(); return this.confidentiality; } public boolean hasConfidentiality() { if (this.confidentiality == null) return false; for (CodeableConcept item : this.confidentiality) if (!item.isEmpty()) return true; return false; } /** * @return {@link #confidentiality} (A set of Security-Tag codes specifying the level of privacy/security of the Document.) */ // syntactic sugar public CodeableConcept addConfidentiality() { //3 CodeableConcept t = new CodeableConcept(); if (this.confidentiality == null) this.confidentiality = new ArrayList<CodeableConcept>(); this.confidentiality.add(t); return t; } /** * @return {@link #content} (The document or url to the document along with critical metadata to prove content has integrity.) */ public List<Attachment> getContent() { if (this.content == null) this.content = new ArrayList<Attachment>(); return this.content; } public boolean hasContent() { if (this.content == null) return false; for (Attachment item : this.content) if (!item.isEmpty()) return true; return false; } /** * @return {@link #content} (The document or url to the document along with critical metadata to prove content has integrity.) */ // syntactic sugar public Attachment addContent() { //3 Attachment t = new Attachment(); if (this.content == null) this.content = new ArrayList<Attachment>(); this.content.add(t); return t; } /** * @return {@link #context} (The clinical context in which the document was prepared.) */ public DocumentReferenceContextComponent getContext() { if (this.context == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DocumentReference.context"); else if (Configuration.doAutoCreate()) this.context = new DocumentReferenceContextComponent(); // cc return this.context; } public boolean hasContext() { return this.context != null && !this.context.isEmpty(); } /** * @param value {@link #context} (The clinical context in which the document was prepared.) */ public DocumentReference setContext(DocumentReferenceContextComponent value) { this.context = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("masterIdentifier", "Identifier", "Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document.", 0, java.lang.Integer.MAX_VALUE, masterIdentifier)); childrenList.add(new Property("identifier", "Identifier", "Other identifiers associated with the document, including version independent, source record and workflow related identifiers.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("subject", "Reference(Patient|Practitioner|Group|Device)", "Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure).", 0, java.lang.Integer.MAX_VALUE, subject)); childrenList.add(new Property("type", "CodeableConcept", "The type code specifies the precise type of document from the user perspective. It is recommended that the value Set be drawn from a coding scheme providing a fine level of granularity such as LOINC. (e.g. Patient Summary, Discharge Summary, Prescription, etc.).", 0, java.lang.Integer.MAX_VALUE, type)); childrenList.add(new Property("class", "CodeableConcept", "The class code specifying the high-level use classification of the document type (e.g., Report, Summary, Images, Treatment Plan, Patient Preferences, Workflow).", 0, java.lang.Integer.MAX_VALUE, class_)); childrenList.add(new Property("format", "uri", "An identifier that identifies the the document encoding, structure and template that the document conforms to beyond the base format indicated in the mimeType.", 0, java.lang.Integer.MAX_VALUE, format)); childrenList.add(new Property("author", "Reference(Practitioner|Organization|Device|Patient|RelatedPerson)", "Identifies who is responsible for adding the information to the document.", 0, java.lang.Integer.MAX_VALUE, author)); childrenList.add(new Property("custodian", "Reference(Organization)", "Identifies the organization or group who is responsible for ongoing maintenance of and access to the document.", 0, java.lang.Integer.MAX_VALUE, custodian)); childrenList.add(new Property("policyManager", "uri", "A reference to a domain or server that manages policies under which the document is accessed and/or made available.", 0, java.lang.Integer.MAX_VALUE, policyManager)); childrenList.add(new Property("authenticator", "Reference(Practitioner|Organization)", "Which person or organization authenticates that this document is valid.", 0, java.lang.Integer.MAX_VALUE, authenticator)); childrenList.add(new Property("created", "dateTime", "When the document was created.", 0, java.lang.Integer.MAX_VALUE, created)); childrenList.add(new Property("indexed", "instant", "When the document reference was created.", 0, java.lang.Integer.MAX_VALUE, indexed)); childrenList.add(new Property("status", "code", "The status of this document reference.", 0, java.lang.Integer.MAX_VALUE, status)); childrenList.add(new Property("docStatus", "CodeableConcept", "The status of the underlying document.", 0, java.lang.Integer.MAX_VALUE, docStatus)); childrenList.add(new Property("relatesTo", "", "Relationships that this document has with other document references that already exist.", 0, java.lang.Integer.MAX_VALUE, relatesTo)); childrenList.add(new Property("description", "string", "Human-readable description of the source document. This is sometimes known as the 'title'.", 0, java.lang.Integer.MAX_VALUE, description)); childrenList.add(new Property("confidentiality", "CodeableConcept", "A set of Security-Tag codes specifying the level of privacy/security of the Document.", 0, java.lang.Integer.MAX_VALUE, confidentiality)); childrenList.add(new Property("content", "Attachment", "The document or url to the document along with critical metadata to prove content has integrity.", 0, java.lang.Integer.MAX_VALUE, content)); childrenList.add(new Property("context", "", "The clinical context in which the document was prepared.", 0, java.lang.Integer.MAX_VALUE, context)); } public DocumentReference copy() { DocumentReference dst = new DocumentReference(); copyValues(dst); dst.masterIdentifier = masterIdentifier == null ? null : masterIdentifier.copy(); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.subject = subject == null ? null : subject.copy(); dst.type = type == null ? null : type.copy(); dst.class_ = class_ == null ? null : class_.copy(); if (format != null) { dst.format = new ArrayList<UriType>(); for (UriType i : format) dst.format.add(i.copy()); }; if (author != null) { dst.author = new ArrayList<Reference>(); for (Reference i : author) dst.author.add(i.copy()); }; dst.custodian = custodian == null ? null : custodian.copy(); dst.policyManager = policyManager == null ? null : policyManager.copy(); dst.authenticator = authenticator == null ? null : authenticator.copy(); dst.created = created == null ? null : created.copy(); dst.indexed = indexed == null ? null : indexed.copy(); dst.status = status == null ? null : status.copy(); dst.docStatus = docStatus == null ? null : docStatus.copy(); if (relatesTo != null) { dst.relatesTo = new ArrayList<DocumentReferenceRelatesToComponent>(); for (DocumentReferenceRelatesToComponent i : relatesTo) dst.relatesTo.add(i.copy()); }; dst.description = description == null ? null : description.copy(); if (confidentiality != null) { dst.confidentiality = new ArrayList<CodeableConcept>(); for (CodeableConcept i : confidentiality) dst.confidentiality.add(i.copy()); }; if (content != null) { dst.content = new ArrayList<Attachment>(); for (Attachment i : content) dst.content.add(i.copy()); }; dst.context = context == null ? null : context.copy(); return dst; } protected DocumentReference typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof DocumentReference)) return false; DocumentReference o = (DocumentReference) other; return compareDeep(masterIdentifier, o.masterIdentifier, true) && compareDeep(identifier, o.identifier, true) && compareDeep(subject, o.subject, true) && compareDeep(type, o.type, true) && compareDeep(class_, o.class_, true) && compareDeep(format, o.format, true) && compareDeep(author, o.author, true) && compareDeep(custodian, o.custodian, true) && compareDeep(policyManager, o.policyManager, true) && compareDeep(authenticator, o.authenticator, true) && compareDeep(created, o.created, true) && compareDeep(indexed, o.indexed, true) && compareDeep(status, o.status, true) && compareDeep(docStatus, o.docStatus, true) && compareDeep(relatesTo, o.relatesTo, true) && compareDeep(description, o.description, true) && compareDeep(confidentiality, o.confidentiality, true) && compareDeep(content, o.content, true) && compareDeep(context, o.context, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof DocumentReference)) return false; DocumentReference o = (DocumentReference) other; return compareValues(format, o.format, true) && compareValues(policyManager, o.policyManager, true) && compareValues(created, o.created, true) && compareValues(indexed, o.indexed, true) && compareValues(status, o.status, true) && compareValues(description, o.description, true); } public boolean isEmpty() { return super.isEmpty() && (masterIdentifier == null || masterIdentifier.isEmpty()) && (identifier == null || identifier.isEmpty()) && (subject == null || subject.isEmpty()) && (type == null || type.isEmpty()) && (class_ == null || class_.isEmpty()) && (format == null || format.isEmpty()) && (author == null || author.isEmpty()) && (custodian == null || custodian.isEmpty()) && (policyManager == null || policyManager.isEmpty()) && (authenticator == null || authenticator.isEmpty()) && (created == null || created.isEmpty()) && (indexed == null || indexed.isEmpty()) && (status == null || status.isEmpty()) && (docStatus == null || docStatus.isEmpty()) && (relatesTo == null || relatesTo.isEmpty()) && (description == null || description.isEmpty()) && (confidentiality == null || confidentiality.isEmpty()) && (content == null || content.isEmpty()) && (context == null || context.isEmpty()); } @Override public ResourceType getResourceType() { return ResourceType.DocumentReference; } @SearchParamDefinition(name = "identifier", path = "DocumentReference.masterIdentifier|DocumentReference.identifier", description = "Master Version Specific Identifier", type = "token") public static final String SP_IDENTIFIER = "identifier"; @SearchParamDefinition(name = "period", path = "DocumentReference.context.period", description = "Time of service that is being documented", type = "date") public static final String SP_PERIOD = "period"; @SearchParamDefinition(name = "custodian", path = "DocumentReference.custodian", description = "Org which maintains the document", type = "reference") public static final String SP_CUSTODIAN = "custodian"; @SearchParamDefinition(name="indexed", path="DocumentReference.indexed", description="When this document reference created", type="date" ) public static final String SP_INDEXED = "indexed"; @SearchParamDefinition(name="subject", path="DocumentReference.subject", description="Who|what is the subject of the document", type="reference" ) public static final String SP_SUBJECT = "subject"; @SearchParamDefinition(name="author", path="DocumentReference.author", description="Who and/or what authored the document", type="reference" ) public static final String SP_AUTHOR = "author"; @SearchParamDefinition(name="created", path="DocumentReference.created", description="Document creation time", type="date" ) public static final String SP_CREATED = "created"; @SearchParamDefinition(name="confidentiality", path="DocumentReference.confidentiality", description="Sensitivity of source document", type="token" ) public static final String SP_CONFIDENTIALITY = "confidentiality"; @SearchParamDefinition(name = "format", path = "DocumentReference.format", description = "Format/content rules for the document", type = "token") public static final String SP_FORMAT = "format"; @SearchParamDefinition(name="description", path="DocumentReference.description", description="Human-readable description (title)", type="string" ) public static final String SP_DESCRIPTION = "description"; @SearchParamDefinition(name="language", path="DocumentReference.content.language", description="Human language of the content (BCP-47)", type="token" ) public static final String SP_LANGUAGE = "language"; @SearchParamDefinition(name = "type", path = "DocumentReference.type", description = "Precice type of document", type = "token") public static final String SP_TYPE = "type"; @SearchParamDefinition(name = "relation", path = "DocumentReference.relatesTo.code", description = "replaces | transforms | signs | appends", type = "token") public static final String SP_RELATION = "relation"; @SearchParamDefinition(name = "patient", path = "DocumentReference.subject", description = "Who|what is the subject of the document", type = "reference") public static final String SP_PATIENT = "patient"; @SearchParamDefinition(name = "location", path = "DocumentReference.content.url", description = "Uri where the data can be found", type = "string") public static final String SP_LOCATION = "location"; @SearchParamDefinition(name = "relatesto", path = "DocumentReference.relatesTo.target", description = "Target of the relationship", type = "reference") public static final String SP_RELATESTO = "relatesto"; @SearchParamDefinition(name = "relationship", path = "", description = "Combination of relation and relatesTo", type = "composite") public static final String SP_RELATIONSHIP = "relationship"; @SearchParamDefinition(name = "event", path = "DocumentReference.context.event", description = "Main Clinical Acts Documented", type = "token") public static final String SP_EVENT = "event"; @SearchParamDefinition(name = "class", path = "DocumentReference.class", description = "High-level classification of document", type = "token") public static final String SP_CLASS = "class"; @SearchParamDefinition(name = "authenticator", path = "DocumentReference.authenticator", description = "Who/What authenticated the document", type = "reference") public static final String SP_AUTHENTICATOR = "authenticator"; @SearchParamDefinition(name = "facility", path = "DocumentReference.context.facilityType", description = "Kind of facility where patient was seen", type = "token") public static final String SP_FACILITY = "facility"; @SearchParamDefinition(name = "status", path = "DocumentReference.status", description = "current | superceded | entered-in-error", type = "token") public static final String SP_STATUS = "status"; }
apache-2.0
apache/incubator-asterixdb
asterixdb/asterix-lang-sqlpp/src/main/java/org/apache/asterix/lang/sqlpp/clause/SelectClause.java
3061
/* * 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.asterix.lang.sqlpp.clause; import java.util.Objects; import org.apache.asterix.common.exceptions.CompilationException; import org.apache.asterix.lang.common.base.AbstractClause; import org.apache.asterix.lang.common.visitor.base.ILangVisitor; import org.apache.asterix.lang.sqlpp.visitor.base.ISqlppVisitor; public class SelectClause extends AbstractClause { private SelectElement selectElement; private SelectRegular selectRegular; private boolean distinct; public SelectClause(SelectElement selectElement, SelectRegular selectRegular, boolean distinct) { this.selectElement = selectElement; this.selectRegular = selectRegular; this.distinct = distinct; } @Override public <R, T> R accept(ILangVisitor<R, T> visitor, T arg) throws CompilationException { return ((ISqlppVisitor<R, T>) visitor).visit(this, arg); } @Override public ClauseType getClauseType() { return ClauseType.SELECT_CLAUSE; } public SelectElement getSelectElement() { return selectElement; } public SelectRegular getSelectRegular() { return selectRegular; } public boolean selectElement() { return selectElement != null; } public boolean selectRegular() { return selectRegular != null; } public boolean distinct() { return distinct; } public void setDistinct(boolean distinct) { this.distinct = distinct; } @Override public String toString() { return "select " + (distinct ? "distinct " : "") + (selectElement() ? "element " + selectElement : String.valueOf(selectRegular)); } @Override public int hashCode() { return Objects.hash(distinct, selectElement, selectRegular); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof SelectClause)) { return false; } SelectClause target = (SelectClause) object; return distinct == target.distinct && Objects.equals(selectElement, target.selectElement) && Objects.equals(selectRegular, target.selectRegular); } }
apache-2.0
osinstom/onos
incubator/net/src/test/java/org/onosproject/incubator/net/virtual/impl/VirtualNetworkGroupManagerTest.java
30630
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.incubator.net.virtual.impl; import com.google.common.collect.Iterables; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onlab.junit.TestUtils; import org.onlab.osgi.ServiceDirectory; import org.onlab.osgi.TestServiceDirectory; import org.onlab.packet.MacAddress; import org.onlab.packet.MplsLabel; import org.onosproject.TestApplicationId; import org.onosproject.common.event.impl.TestEventDispatcher; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.core.GroupId; import org.onosproject.event.EventDeliveryService; import org.onosproject.incubator.net.virtual.NetworkId; import org.onosproject.incubator.net.virtual.VirtualNetwork; import org.onosproject.incubator.net.virtual.VirtualNetworkGroupStore; import org.onosproject.incubator.net.virtual.VirtualNetworkStore; import org.onosproject.incubator.net.virtual.impl.provider.VirtualProviderManager; import org.onosproject.incubator.net.virtual.provider.AbstractVirtualProvider; import org.onosproject.incubator.net.virtual.provider.VirtualGroupProvider; import org.onosproject.incubator.net.virtual.provider.VirtualGroupProviderService; import org.onosproject.incubator.net.virtual.provider.VirtualProviderRegistryService; import org.onosproject.incubator.store.virtual.impl.DistributedVirtualNetworkStore; import org.onosproject.incubator.store.virtual.impl.SimpleVirtualGroupStore; import org.onosproject.net.DeviceId; import org.onosproject.net.PortNumber; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.group.DefaultGroup; import org.onosproject.net.group.DefaultGroupBucket; import org.onosproject.net.group.DefaultGroupDescription; import org.onosproject.net.group.DefaultGroupKey; import org.onosproject.net.group.Group; import org.onosproject.net.group.GroupBucket; import org.onosproject.net.group.GroupBuckets; import org.onosproject.net.group.GroupDescription; import org.onosproject.net.group.GroupEvent; import org.onosproject.net.group.GroupKey; import org.onosproject.net.group.GroupListener; import org.onosproject.net.group.GroupOperation; import org.onosproject.net.group.GroupOperations; import org.onosproject.net.group.StoredGroupEntry; import org.onosproject.net.provider.ProviderId; import org.onosproject.store.service.TestStorageService; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.onosproject.incubator.net.virtual.impl.VirtualNetworkTestUtil.*; import static org.onosproject.net.NetTestTools.injectEventDispatcher; /** * Test codifying the virtual group service & group provider service contracts. */ public class VirtualNetworkGroupManagerTest { private VirtualNetworkManager manager; private DistributedVirtualNetworkStore virtualNetworkManagerStore; private ServiceDirectory testDirectory; private VirtualProviderManager providerRegistryService; private EventDeliveryService eventDeliveryService; private VirtualNetworkGroupManager groupManager1; private VirtualNetworkGroupManager groupManager2; private VirtualNetworkGroupStore groupStore; private TestGroupProvider provider = new TestGroupProvider(); private VirtualGroupProviderService providerService1; private VirtualGroupProviderService providerService2; protected TestGroupListener listener1 = new TestGroupListener(); protected TestGroupListener listener2 = new TestGroupListener(); private VirtualNetwork vnet1; private VirtualNetwork vnet2; private ApplicationId appId; @Before public void setUp() throws Exception { virtualNetworkManagerStore = new DistributedVirtualNetworkStore(); CoreService coreService = new TestCoreService(); TestUtils.setField(virtualNetworkManagerStore, "coreService", coreService); TestUtils.setField(virtualNetworkManagerStore, "storageService", new TestStorageService()); virtualNetworkManagerStore.activate(); groupStore = new SimpleVirtualGroupStore(); providerRegistryService = new VirtualProviderManager(); providerRegistryService.registerProvider(provider); manager = new VirtualNetworkManager(); manager.store = virtualNetworkManagerStore; TestUtils.setField(manager, "coreService", coreService); eventDeliveryService = new TestEventDispatcher(); injectEventDispatcher(manager, eventDeliveryService); appId = new TestApplicationId("VirtualGroupManagerTest"); testDirectory = new TestServiceDirectory() .add(VirtualNetworkStore.class, virtualNetworkManagerStore) .add(CoreService.class, coreService) .add(VirtualProviderRegistryService.class, providerRegistryService) .add(EventDeliveryService.class, eventDeliveryService) .add(VirtualNetworkGroupStore.class, groupStore); TestUtils.setField(manager, "serviceDirectory", testDirectory); manager.activate(); vnet1 = setupVirtualNetworkTopology(manager, TID1); vnet2 = setupVirtualNetworkTopology(manager, TID2); groupManager1 = new VirtualNetworkGroupManager(manager, vnet1.id()); groupManager2 = new VirtualNetworkGroupManager(manager, vnet2.id()); groupManager1.addListener(listener1); groupManager2.addListener(listener2); providerService1 = (VirtualGroupProviderService) providerRegistryService.getProviderService(vnet1.id(), VirtualGroupProvider.class); providerService2 = (VirtualGroupProviderService) providerRegistryService.getProviderService(vnet2.id(), VirtualGroupProvider.class); } @After public void tearDown() { providerRegistryService.unregisterProvider(provider); assertFalse("provider should not be registered", providerRegistryService.getProviders().contains(provider.id())); groupManager1.removeListener(listener1); groupManager2.removeListener(listener2); manager.deactivate(); virtualNetworkManagerStore.deactivate(); } /** * Tests group creation before the device group AUDIT completes. */ @Test public void testGroupServiceBasics() { // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testGroupCreationBeforeAudit(vnet2.id(), VDID1); } /** * Tests initial device group AUDIT process. */ @Test public void testGroupServiceInitialAudit() { // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testGroupCreationBeforeAudit(vnet2.id(), VDID1); // Test initial group audit process testInitialAuditWithPendingGroupRequests(vnet1.id(), VDID1); testInitialAuditWithPendingGroupRequests(vnet2.id(), VDID1); } /** * Tests deletion process of any extraneous groups. */ @Test public void testGroupServiceAuditExtraneous() { // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testGroupCreationBeforeAudit(vnet2.id(), VDID1); // Test audit with extraneous and missing groups testAuditWithExtraneousMissingGroups(vnet1.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet2.id(), VDID1); } /** * Tests re-apply process of any missing groups tests execution of * any pending group creation request after the device group AUDIT completes * and tests event notifications after receiving confirmation for any * operations from data plane. */ @Test public void testGroupServiceAuditConfirmed() { // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testGroupCreationBeforeAudit(vnet2.id(), VDID1); // Test audit with extraneous and missing groups testAuditWithExtraneousMissingGroups(vnet1.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet2.id(), VDID1); // Test audit with confirmed groups testAuditWithConfirmedGroups(vnet1.id(), VDID1); testAuditWithConfirmedGroups(vnet2.id(), VDID1); } /** * Tests group Purge Operation. */ @Test public void testPurgeGroups() { // Tests for virtual network 1 // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet1.id(), VDID1); // Test group add bucket operations testAddBuckets(vnet1.id(), VDID1); // Test group Purge operations testPurgeGroupEntry(vnet1.id(), VDID1); // Tests for virtual network 2 // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet2.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet2.id(), VDID1); // Test group add bucket operations testAddBuckets(vnet2.id(), VDID1); // Test group Purge operations testPurgeGroupEntry(vnet2.id(), VDID1); } /** * Tests group bucket modifications (additions and deletions) and * Tests group deletion. */ @Test public void testGroupServiceBuckets() { // Tests for virtual network 1 // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet1.id(), VDID1); // Test group add bucket operations testAddBuckets(vnet1.id(), VDID1); // Test group remove bucket operations testRemoveBuckets(vnet1.id(), VDID1); // Test group remove operations testRemoveGroup(vnet1.id(), VDID1); // Tests for virtual network 2 // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet2.id(), VDID1); testAuditWithExtraneousMissingGroups(vnet2.id(), VDID1); // Test group add bucket operations testAddBuckets(vnet2.id(), VDID1); // Test group remove bucket operations testRemoveBuckets(vnet2.id(), VDID1); // Test group remove operations testRemoveGroup(vnet2.id(), VDID1); } /** * Tests group creation before the device group AUDIT completes with fallback * provider. */ @Test public void testGroupServiceFallbackBasics() { // Test Group creation before AUDIT process testGroupCreationBeforeAudit(vnet1.id(), VDID2); testGroupCreationBeforeAudit(vnet2.id(), VDID2); } // Test Group creation before AUDIT process private void testGroupCreationBeforeAudit(NetworkId networkId, DeviceId deviceId) { PortNumber[] ports1 = {PortNumber.portNumber(31), PortNumber.portNumber(32)}; PortNumber[] ports2 = {PortNumber.portNumber(41), PortNumber.portNumber(42)}; GroupKey key = new DefaultGroupKey("group1BeforeAudit".getBytes()); List<GroupBucket> buckets = new ArrayList<>(); List<PortNumber> outPorts = new ArrayList<>(); outPorts.addAll(Arrays.asList(ports1)); outPorts.addAll(Arrays.asList(ports2)); for (PortNumber portNumber : outPorts) { TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder(); tBuilder.setOutput(portNumber) .setEthDst(MacAddress.valueOf("00:00:00:00:00:02")) .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01")) .pushMpls() .setMpls(MplsLabel.mplsLabel(106)); buckets.add(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); } GroupBuckets groupBuckets = new GroupBuckets(buckets); GroupDescription newGroupDesc = new DefaultGroupDescription(deviceId, Group.Type.SELECT, groupBuckets, key, null, appId); VirtualNetworkGroupManager groupManager; if (networkId.id() == 1) { groupManager = groupManager1; } else { groupManager = groupManager2; } groupManager.addGroup(newGroupDesc); assertEquals(null, groupManager.getGroup(deviceId, key)); assertEquals(0, Iterables.size(groupManager.getGroups(deviceId, appId))); } // Test initial AUDIT process with pending group requests private void testInitialAuditWithPendingGroupRequests(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; } else { groupManager = groupManager2; providerService = providerService2; } PortNumber[] ports1 = {PortNumber.portNumber(31), PortNumber.portNumber(32)}; PortNumber[] ports2 = {PortNumber.portNumber(41), PortNumber.portNumber(42)}; GroupId gId1 = new GroupId(1); Group group1 = createSouthboundGroupEntry(gId1, Arrays.asList(ports1), 0, deviceId); GroupId gId2 = new GroupId(2); // Non zero reference count will make the group manager to queue // the extraneous groups until reference count is zero. Group group2 = createSouthboundGroupEntry(gId2, Arrays.asList(ports2), 2, deviceId); List<Group> groupEntries = Arrays.asList(group1, group2); providerService.pushGroupMetrics(deviceId, groupEntries); // First group metrics would trigger the device audit completion // post which all pending group requests are also executed. GroupKey key = new DefaultGroupKey("group1BeforeAudit".getBytes()); Group createdGroup = groupManager.getGroup(deviceId, key); int createdGroupId = createdGroup.id().id(); assertNotEquals(gId1.id().intValue(), createdGroupId); assertNotEquals(gId2.id().intValue(), createdGroupId); List<GroupOperation> expectedGroupOps = Arrays.asList( GroupOperation.createDeleteGroupOperation(gId1, Group.Type.SELECT), GroupOperation.createAddGroupOperation( createdGroup.id(), Group.Type.SELECT, createdGroup.buckets())); if (deviceId.equals(VDID1)) { provider.validate(networkId, deviceId, expectedGroupOps); } } // Test AUDIT process with extraneous groups and missing groups private void testAuditWithExtraneousMissingGroups(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; } else { groupManager = groupManager2; providerService = providerService2; } PortNumber[] ports1 = {PortNumber.portNumber(31), PortNumber.portNumber(32)}; PortNumber[] ports2 = {PortNumber.portNumber(41), PortNumber.portNumber(42)}; GroupId gId1 = new GroupId(1); Group group1 = createSouthboundGroupEntry(gId1, Arrays.asList(ports1), 0, deviceId); GroupId gId2 = new GroupId(2); Group group2 = createSouthboundGroupEntry(gId2, Arrays.asList(ports2), 0, deviceId); List<Group> groupEntries = Arrays.asList(group1, group2); providerService.pushGroupMetrics(deviceId, groupEntries); GroupKey key = new DefaultGroupKey("group1BeforeAudit".getBytes()); Group createdGroup = groupManager.getGroup(deviceId, key); List<GroupOperation> expectedGroupOps = Arrays.asList( GroupOperation.createDeleteGroupOperation(gId1, Group.Type.SELECT), GroupOperation.createDeleteGroupOperation(gId2, Group.Type.SELECT), GroupOperation.createAddGroupOperation(createdGroup.id(), Group.Type.SELECT, createdGroup.buckets())); if (deviceId.equals(VDID1)) { provider.validate(networkId, deviceId, expectedGroupOps); } } // Test AUDIT with confirmed groups private void testAuditWithConfirmedGroups(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; TestGroupListener listener; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; listener = listener1; } else { groupManager = groupManager2; providerService = providerService2; listener = listener2; } GroupKey key = new DefaultGroupKey("group1BeforeAudit".getBytes()); Group createdGroup = groupManager.getGroup(deviceId, key); createdGroup = new DefaultGroup(createdGroup.id(), deviceId, Group.Type.SELECT, createdGroup.buckets()); List<Group> groupEntries = Collections.singletonList(createdGroup); providerService.pushGroupMetrics(deviceId, groupEntries); listener.validateEvent(Collections.singletonList(GroupEvent.Type.GROUP_ADDED)); } private Group createSouthboundGroupEntry(GroupId gId, List<PortNumber> ports, long referenceCount, DeviceId deviceId) { List<PortNumber> outPorts = new ArrayList<>(); outPorts.addAll(ports); List<GroupBucket> buckets = new ArrayList<>(); for (PortNumber portNumber : outPorts) { TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder(); tBuilder.setOutput(portNumber) .setEthDst(MacAddress.valueOf("00:00:00:00:00:02")) .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01")) .pushMpls() .setMpls(MplsLabel.mplsLabel(106)); buckets.add(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); } GroupBuckets groupBuckets = new GroupBuckets(buckets); StoredGroupEntry group = new DefaultGroup( gId, deviceId, Group.Type.SELECT, groupBuckets); group.setReferenceCount(referenceCount); return group; } // Test group add bucket operations private void testAddBuckets(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; TestGroupListener listener; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; listener = listener1; } else { groupManager = groupManager2; providerService = providerService2; listener = listener2; } GroupKey addKey = new DefaultGroupKey("group1AddBuckets".getBytes()); GroupKey prevKey = new DefaultGroupKey("group1BeforeAudit".getBytes()); Group createdGroup = groupManager.getGroup(deviceId, prevKey); List<GroupBucket> buckets = new ArrayList<>(); buckets.addAll(createdGroup.buckets().buckets()); PortNumber[] addPorts = {PortNumber.portNumber(51), PortNumber.portNumber(52)}; List<PortNumber> outPorts; outPorts = new ArrayList<>(); outPorts.addAll(Arrays.asList(addPorts)); List<GroupBucket> addBuckets; addBuckets = new ArrayList<>(); for (PortNumber portNumber : outPorts) { TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder(); tBuilder.setOutput(portNumber) .setEthDst(MacAddress.valueOf("00:00:00:00:00:02")) .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01")) .pushMpls() .setMpls(MplsLabel.mplsLabel(106)); addBuckets.add(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); buckets.add(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); } GroupBuckets groupAddBuckets = new GroupBuckets(addBuckets); groupManager.addBucketsToGroup(deviceId, prevKey, groupAddBuckets, addKey, appId); GroupBuckets updatedBuckets = new GroupBuckets(buckets); List<GroupOperation> expectedGroupOps = Collections.singletonList( GroupOperation.createModifyGroupOperation(createdGroup.id(), Group.Type.SELECT, updatedBuckets)); if (deviceId.equals(VDID1)) { provider.validate(networkId, deviceId, expectedGroupOps); } Group existingGroup = groupManager.getGroup(deviceId, addKey); List<Group> groupEntries = Collections.singletonList(existingGroup); providerService.pushGroupMetrics(deviceId, groupEntries); listener.validateEvent(Collections.singletonList(GroupEvent.Type.GROUP_UPDATED)); } // Test purge group entry operations private void testPurgeGroupEntry(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; if (networkId.id() == 1) { groupManager = groupManager1; } else { groupManager = groupManager2; } assertEquals(1, Iterables.size(groupManager.getGroups(deviceId, appId))); groupManager.purgeGroupEntries(deviceId); assertEquals(0, Iterables.size(groupManager.getGroups(deviceId, appId))); } // Test group remove bucket operations private void testRemoveBuckets(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; TestGroupListener listener; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; listener = listener1; } else { groupManager = groupManager2; providerService = providerService2; listener = listener2; } GroupKey removeKey = new DefaultGroupKey("group1RemoveBuckets".getBytes()); GroupKey prevKey = new DefaultGroupKey("group1AddBuckets".getBytes()); Group createdGroup = groupManager.getGroup(deviceId, prevKey); List<GroupBucket> buckets = new ArrayList<>(); buckets.addAll(createdGroup.buckets().buckets()); PortNumber[] removePorts = {PortNumber.portNumber(31), PortNumber.portNumber(32)}; List<PortNumber> outPorts = new ArrayList<>(); outPorts.addAll(Arrays.asList(removePorts)); List<GroupBucket> removeBuckets = new ArrayList<>(); for (PortNumber portNumber : outPorts) { TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder(); tBuilder.setOutput(portNumber) .setEthDst(MacAddress.valueOf("00:00:00:00:00:02")) .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01")) .pushMpls() .setMpls(MplsLabel.mplsLabel(106)); removeBuckets.add(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); buckets.remove(DefaultGroupBucket.createSelectGroupBucket( tBuilder.build())); } GroupBuckets groupRemoveBuckets = new GroupBuckets(removeBuckets); groupManager.removeBucketsFromGroup(deviceId, prevKey, groupRemoveBuckets, removeKey, appId); GroupBuckets updatedBuckets = new GroupBuckets(buckets); List<GroupOperation> expectedGroupOps = Collections.singletonList( GroupOperation.createModifyGroupOperation(createdGroup.id(), Group.Type.SELECT, updatedBuckets)); if (deviceId.equals(VDID1)) { provider.validate(networkId, deviceId, expectedGroupOps); } Group existingGroup = groupManager.getGroup(deviceId, removeKey); List<Group> groupEntries = Collections.singletonList(existingGroup); providerService.pushGroupMetrics(deviceId, groupEntries); listener.validateEvent(Collections.singletonList(GroupEvent.Type.GROUP_UPDATED)); } // Test group remove operations private void testRemoveGroup(NetworkId networkId, DeviceId deviceId) { VirtualNetworkGroupManager groupManager; VirtualGroupProviderService providerService; TestGroupListener listener; if (networkId.id() == 1) { groupManager = groupManager1; providerService = providerService1; listener = listener1; } else { groupManager = groupManager2; providerService = providerService2; listener = listener2; } GroupKey currKey = new DefaultGroupKey("group1RemoveBuckets".getBytes()); Group existingGroup = groupManager.getGroup(deviceId, currKey); groupManager.removeGroup(deviceId, currKey, appId); List<GroupOperation> expectedGroupOps = Collections.singletonList( GroupOperation.createDeleteGroupOperation(existingGroup.id(), Group.Type.SELECT)); if (deviceId.equals(VDID1)) { provider.validate(networkId, deviceId, expectedGroupOps); } List<Group> groupEntries = Collections.emptyList(); providerService.pushGroupMetrics(deviceId, groupEntries); listener.validateEvent(Collections.singletonList(GroupEvent.Type.GROUP_REMOVED)); } private class TestGroupProvider extends AbstractVirtualProvider implements VirtualGroupProvider { NetworkId lastNetworkId; DeviceId lastDeviceId; List<GroupOperation> groupOperations = new ArrayList<>(); protected TestGroupProvider() { super(new ProviderId("test", "org.onosproject.virtual.testprovider")); } @Override public void performGroupOperation(NetworkId networkId, DeviceId deviceId, GroupOperations groupOps) { lastNetworkId = networkId; lastDeviceId = deviceId; groupOperations.addAll(groupOps.operations()); } public void validate(NetworkId expectedNetworkId, DeviceId expectedDeviceId, List<GroupOperation> expectedGroupOps) { if (expectedGroupOps == null) { assertTrue("events generated", groupOperations.isEmpty()); return; } assertEquals(lastNetworkId, expectedNetworkId); assertEquals(lastDeviceId, expectedDeviceId); assertTrue((this.groupOperations.containsAll(expectedGroupOps) && expectedGroupOps.containsAll(groupOperations))); groupOperations.clear(); lastDeviceId = null; lastNetworkId = null; } } private static class TestGroupListener implements GroupListener { final List<GroupEvent> events = new ArrayList<>(); @Override public void event(GroupEvent event) { events.add(event); } public void validateEvent(List<GroupEvent.Type> expectedEvents) { int i = 0; System.err.println("events :" + events); for (GroupEvent e : events) { assertEquals("unexpected event", expectedEvents.get(i), e.type()); i++; } assertEquals("mispredicted number of events", expectedEvents.size(), events.size()); events.clear(); } } }
apache-2.0
MaiconV/locadora-veiculo-web-inicial
src/main/java/com/algaworks/curso/jpa2/modelo/Fabricante.java
1367
package com.algaworks.curso.jpa2.modelo; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Fabricante implements Serializable { /** * */ private static final long serialVersionUID = 1L; /* * @Id * * @TableGenerator(name="fabricante_generator", table="GERADOR_CODIGO", * pkColumnName="ENTIDADE", valueColumnName="ALOCACAO", allocationSize=5) * * @GeneratedValue(generator="fabricante_generator", * strategy=GenerationType.TABLE) */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long codigo; private String nome; public long getCodigo() { return codigo; } public void setCodigo(long codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (codigo ^ (codigo >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Fabricante other = (Fabricante) obj; if (codigo != other.codigo) return false; return true; } }
apache-2.0
JeromeRocheteau/emit
emit-monitoring/emit-services/src/main/java/fr/icam/emit/services/users/Create.java
1187
package fr.icam.emit.services.users; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.github.jeromerocheteau.JdbcUpdateServlet; public class Create extends JdbcUpdateServlet<Boolean> { private static final long serialVersionUID = 201711031818003L; @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Boolean done = this.doProcess(request); this.doWrite(done, response.getWriter()); } @Override public void doFill(PreparedStatement statement, HttpServletRequest request) throws Exception { String username = request.getParameter("username"); String rolename = request.getParameter("rolename"); String password = request.getParameter("password"); statement.setString(1, username); statement.setString(2, rolename); statement.setString(3, password); } @Override protected Boolean doMap(HttpServletRequest request, int count, ResultSet resultSet) throws Exception { return count > 0; } }
apache-2.0
hopestar720/Smartools
src/com/xhsoft/android/common/utils/FlashLightUtil.java
927
package com.xhsoft.android.common.utils; import android.hardware.Camera; import android.hardware.Camera.Parameters; public class FlashLightUtil { private static FlashLightUtil instance = null; private static Camera camera = null; private FlashLightUtil() { if (camera == null) { camera = Camera.open(); camera.startPreview(); } } public static FlashLightUtil getInstance() { if (instance == null) { instance = new FlashLightUtil(); } return instance; } /** * ´ò¿ªÉÁ¹âµÆ */ public void open() { Parameters params = camera.getParameters(); params.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(params); } /** * ¹Ø±ÕÉÁ¹âµÆ */ public void close() { Parameters params = camera.getParameters(); params.setFlashMode(Parameters.FLASH_MODE_OFF); camera.setParameters(params); } public void release() { if (camera != null) { camera.release(); } } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-run/v1/1.31.0/com/google/api/services/run/v1/model/GoogleRpcStatus.java
4475
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.run.v1.model; /** * The `Status` type defines a logical error model that is suitable for different programming * environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). * Each `Status` message contains three pieces of data: error code, error message, and error * details. You can find out more about this error model and how to work with it in the [API Design * Guide](https://cloud.google.com/apis/design/errors). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Run Admin API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleRpcStatus extends com.google.api.client.json.GenericJson { /** * The status code, which should be an enum value of google.rpc.Code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer code; /** * A list of messages that carry the error details. There is a common set of message types for * APIs to use. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.util.Map<String, java.lang.Object>> details; /** * A developer-facing error message, which should be in English. Any user-facing error message * should be localized and sent in the google.rpc.Status.details field, or localized by the * client. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * The status code, which should be an enum value of google.rpc.Code. * @return value or {@code null} for none */ public java.lang.Integer getCode() { return code; } /** * The status code, which should be an enum value of google.rpc.Code. * @param code code or {@code null} for none */ public GoogleRpcStatus setCode(java.lang.Integer code) { this.code = code; return this; } /** * A list of messages that carry the error details. There is a common set of message types for * APIs to use. * @return value or {@code null} for none */ public java.util.List<java.util.Map<String, java.lang.Object>> getDetails() { return details; } /** * A list of messages that carry the error details. There is a common set of message types for * APIs to use. * @param details details or {@code null} for none */ public GoogleRpcStatus setDetails(java.util.List<java.util.Map<String, java.lang.Object>> details) { this.details = details; return this; } /** * A developer-facing error message, which should be in English. Any user-facing error message * should be localized and sent in the google.rpc.Status.details field, or localized by the * client. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * A developer-facing error message, which should be in English. Any user-facing error message * should be localized and sent in the google.rpc.Status.details field, or localized by the * client. * @param message message or {@code null} for none */ public GoogleRpcStatus setMessage(java.lang.String message) { this.message = message; return this; } @Override public GoogleRpcStatus set(String fieldName, Object value) { return (GoogleRpcStatus) super.set(fieldName, value); } @Override public GoogleRpcStatus clone() { return (GoogleRpcStatus) super.clone(); } }
apache-2.0
luoyan35714/BeyondTool
menu/com/freud/tool/menu/file/OpenMenuItem.java
325
package com.freud.tool.menu.file; import java.awt.event.ActionEvent; import com.freud.tool.extension.MenuItemActionListener; import com.freud.tool.ui.utils.UISupport; public class OpenMenuItem extends MenuItemActionListener { @Override public void actionPerformed(ActionEvent e) { UISupport.showMessage("Open"); } }
apache-2.0
gosu-lang/old-gosu-repo
gosu-core/src/main/java/gw/internal/gosu/ir/transform/statement/AssignmentStatementTransformer.java
5005
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.internal.gosu.ir.transform.statement; import gw.lang.ir.IRExpression; import gw.lang.ir.IRStatement; import gw.lang.ir.IRType; import gw.internal.gosu.ir.nodes.IRProperty; import gw.internal.gosu.ir.nodes.IRPropertyFactory; import gw.lang.ir.expression.IRNullLiteral; import gw.internal.gosu.ir.transform.ExpressionTransformer; import gw.internal.gosu.ir.transform.TopLevelTransformationContext; import gw.internal.gosu.parser.CapturedSymbol; import gw.internal.gosu.parser.DynamicPropertySymbol; import gw.internal.gosu.parser.DynamicSymbol; import gw.internal.gosu.parser.ScopedDynamicSymbol; import gw.internal.gosu.parser.AbstractDynamicSymbol; import gw.lang.parser.ISymbol; import gw.lang.parser.statements.IAssignmentStatement; import gw.lang.reflect.IType; import gw.lang.reflect.gs.IExternalSymbolMap; import java.util.Arrays; /** */ public class AssignmentStatementTransformer extends AbstractStatementTransformer<IAssignmentStatement> { public static IRStatement compile( TopLevelTransformationContext cc, IAssignmentStatement stmt ) { AssignmentStatementTransformer gen = new AssignmentStatementTransformer( cc, stmt ); return gen.compile(); } private AssignmentStatementTransformer( TopLevelTransformationContext cc, IAssignmentStatement stmt ) { super( cc, stmt ); } @Override protected IRStatement compile_impl() { ISymbol symbol = _stmt().getIdentifier().getSymbol(); IType type = symbol.getType(); if ( _cc().isExternalSymbol( symbol.getName() ) ) { IRExpression setterCall = callMethod( IExternalSymbolMap.class, "setValue", new Class[]{String.class, Object.class}, pushExternalSymbolsMap(), Arrays.asList( pushConstant( symbol.getName() ), boxValue( _stmt().getExpression().getType(), ExpressionTransformer.compile( _stmt().getExpression(), _cc() ) ) ) ); return buildMethodCall( setterCall ); } else if( symbol instanceof ScopedDynamicSymbol ) { return setScopedSymbolValue( symbol, _stmt().getExpression() ); } else if( symbol instanceof DynamicPropertySymbol ) { // Lhs is a Property final DynamicPropertySymbol dps = (DynamicPropertySymbol)symbol; IRProperty irProperty = IRPropertyFactory.createIRProperty(dps); IRExpression rhsValue = transformRHS( symbol ); IRExpression root= pushRoot(dps, irProperty); return buildMethodCall( callMethod( irProperty.getSetterMethod(), root, exprList( rhsValue ) ) ); } else { IRExpression rhsValue = transformRHS( symbol ); if( symbol instanceof DynamicSymbol ) { // Lhs is a Field DynamicSymbol field = (DynamicSymbol)symbol; IRProperty irProperty = IRPropertyFactory.createIRProperty( symbol ); IRExpression root = pushRoot(field, irProperty); return setField( irProperty, root, rhsValue ); } else if( symbol instanceof CapturedSymbol ) { // Captured symbol is stored as a Field on an anonymous inner class (one elem array of symbol's type) // e.g., val$myFiield[0] = value IRProperty irProp = IRPropertyFactory.createIRProperty( getGosuClass(), symbol ); return buildArrayStore( getField( irProp, pushThis() ), numericLiteral(0), rhsValue, irProp.getType().getComponentType() ); } else if( symbol.getIndex() >= 0 ) { // Lhs is a local var if( symbol.isValueBoxed() ) { // Local var is captured in an anonymous inner class. // Symbol's value maintained as a one elem array of symbol's type. return buildArrayStore( identifier( _cc().getSymbol( symbol.getName() ) ), numericLiteral( 0 ), rhsValue, getDescriptor( type ) ); } else { // Simple local var return buildAssignment( _cc().getSymbol( symbol.getName() ), rhsValue ); } } else { throw new IllegalStateException("Found a symbol that we didn't know how to handle"); } } } private IRExpression pushRoot(AbstractDynamicSymbol dps, IRProperty irProperty) { IRExpression root; if ( irProperty.isStatic() ) { root = null; } else if ( isMemberOnEnclosingType( dps ) != null ) { root = pushOuter( dps.getGosuClass() ); } else { root = pushThis(); } return root; } private IRExpression transformRHS(ISymbol symbol) { IRExpression rhsValue = ExpressionTransformer.compile( _stmt().getExpression(), _cc() ); IRType symbolType = getDescriptor(symbol.getType()); if (!(rhsValue instanceof IRNullLiteral) && !symbolType.isAssignableFrom(rhsValue.getType())) { rhsValue = buildCast( symbolType, rhsValue ); } return rhsValue; } }
apache-2.0
aantu/PopularMovies
app/src/main/java/com/arthurantunes/popularmovies/api/ApiClient.java
1382
/* * Copyright (c) 2017 Arthur Antunes. * * 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.arthurantunes.popularmovies.api; import com.arthurantunes.popularmovies.BuildConfig; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private static final String BASE_URL = "http://api.themoviedb.org/3/"; public static final String POSTER_IMAGE_BASE_URL = "https://image.tmdb.org/t/p/"; public static final String POSTER_IMAGE_SIZE = "w185"; public static final String API_KEY = BuildConfig.THE_MOVIE_DB_API_KEY; private static Retrofit retrofit; public static Retrofit getClient() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
apache-2.0
googleapis/java-compute
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/RegionInstanceGroupsSetNamedPortsRequest.java
41558
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest} */ public final class RegionInstanceGroupsSetNamedPortsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) RegionInstanceGroupsSetNamedPortsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use RegionInstanceGroupsSetNamedPortsRequest.newBuilder() to construct. private RegionInstanceGroupsSetNamedPortsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RegionInstanceGroupsSetNamedPortsRequest() { fingerprint_ = ""; namedPorts_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new RegionInstanceGroupsSetNamedPortsRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RegionInstanceGroupsSetNamedPortsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; 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 1877428002: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; fingerprint_ = s; break; } case -874177438: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { namedPorts_ = new java.util.ArrayList<com.google.cloud.compute.v1.NamedPort>(); mutable_bitField0_ |= 0x00000002; } namedPorts_.add( input.readMessage( com.google.cloud.compute.v1.NamedPort.parser(), extensionRegistry)); 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 { if (((mutable_bitField0_ & 0x00000002) != 0)) { namedPorts_ = java.util.Collections.unmodifiableList(namedPorts_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_RegionInstanceGroupsSetNamedPortsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_RegionInstanceGroupsSetNamedPortsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest.class, com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest.Builder.class); } private int bitField0_; public static final int FINGERPRINT_FIELD_NUMBER = 234678500; private volatile java.lang.Object fingerprint_; /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return Whether the fingerprint field is set. */ @java.lang.Override public boolean hasFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The fingerprint. */ @java.lang.Override public java.lang.String getFingerprint() { java.lang.Object ref = fingerprint_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fingerprint_ = s; return s; } } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The bytes for fingerprint. */ @java.lang.Override public com.google.protobuf.ByteString getFingerprintBytes() { java.lang.Object ref = fingerprint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NAMED_PORTS_FIELD_NUMBER = 427598732; private java.util.List<com.google.cloud.compute.v1.NamedPort> namedPorts_; /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ @java.lang.Override public java.util.List<com.google.cloud.compute.v1.NamedPort> getNamedPortsList() { return namedPorts_; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.compute.v1.NamedPortOrBuilder> getNamedPortsOrBuilderList() { return namedPorts_; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ @java.lang.Override public int getNamedPortsCount() { return namedPorts_.size(); } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ @java.lang.Override public com.google.cloud.compute.v1.NamedPort getNamedPorts(int index) { return namedPorts_.get(index); } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ @java.lang.Override public com.google.cloud.compute.v1.NamedPortOrBuilder getNamedPortsOrBuilder(int index) { return namedPorts_.get(index); } 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 (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 234678500, fingerprint_); } for (int i = 0; i < namedPorts_.size(); i++) { output.writeMessage(427598732, namedPorts_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(234678500, fingerprint_); } for (int i = 0; i < namedPorts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(427598732, namedPorts_.get(i)); } 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest other = (com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) obj; if (hasFingerprint() != other.hasFingerprint()) return false; if (hasFingerprint()) { if (!getFingerprint().equals(other.getFingerprint())) return false; } if (!getNamedPortsList().equals(other.getNamedPortsList())) return false; 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 (hasFingerprint()) { hash = (37 * hash) + FINGERPRINT_FIELD_NUMBER; hash = (53 * hash) + getFingerprint().hashCode(); } if (getNamedPortsCount() > 0) { hash = (37 * hash) + NAMED_PORTS_FIELD_NUMBER; hash = (53 * hash) + getNamedPortsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest 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> * </pre> * * Protobuf type {@code google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_RegionInstanceGroupsSetNamedPortsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_RegionInstanceGroupsSetNamedPortsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest.class, com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest.Builder.class); } // Construct using // com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getNamedPortsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); fingerprint_ = ""; bitField0_ = (bitField0_ & ~0x00000001); if (namedPortsBuilder_ == null) { namedPorts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { namedPortsBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_RegionInstanceGroupsSetNamedPortsRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest build() { com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest buildPartial() { com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest result = new com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { to_bitField0_ |= 0x00000001; } result.fingerprint_ = fingerprint_; if (namedPortsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { namedPorts_ = java.util.Collections.unmodifiableList(namedPorts_); bitField0_ = (bitField0_ & ~0x00000002); } result.namedPorts_ = namedPorts_; } else { result.namedPorts_ = namedPortsBuilder_.build(); } result.bitField0_ = to_bitField0_; 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) { return mergeFrom( (com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest other) { if (other == com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest .getDefaultInstance()) return this; if (other.hasFingerprint()) { bitField0_ |= 0x00000001; fingerprint_ = other.fingerprint_; onChanged(); } if (namedPortsBuilder_ == null) { if (!other.namedPorts_.isEmpty()) { if (namedPorts_.isEmpty()) { namedPorts_ = other.namedPorts_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureNamedPortsIsMutable(); namedPorts_.addAll(other.namedPorts_); } onChanged(); } } else { if (!other.namedPorts_.isEmpty()) { if (namedPortsBuilder_.isEmpty()) { namedPortsBuilder_.dispose(); namedPortsBuilder_ = null; namedPorts_ = other.namedPorts_; bitField0_ = (bitField0_ & ~0x00000002); namedPortsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getNamedPortsFieldBuilder() : null; } else { namedPortsBuilder_.addAllMessages(other.namedPorts_); } } } 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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object fingerprint_ = ""; /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return Whether the fingerprint field is set. */ public boolean hasFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The fingerprint. */ public java.lang.String getFingerprint() { java.lang.Object ref = fingerprint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fingerprint_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The bytes for fingerprint. */ public com.google.protobuf.ByteString getFingerprintBytes() { java.lang.Object ref = fingerprint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @param value The fingerprint to set. * @return This builder for chaining. */ public Builder setFingerprint(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; fingerprint_ = value; onChanged(); return this; } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return This builder for chaining. */ public Builder clearFingerprint() { bitField0_ = (bitField0_ & ~0x00000001); fingerprint_ = getDefaultInstance().getFingerprint(); onChanged(); return this; } /** * * * <pre> * The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @param value The bytes for fingerprint to set. * @return This builder for chaining. */ public Builder setFingerprintBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000001; fingerprint_ = value; onChanged(); return this; } private java.util.List<com.google.cloud.compute.v1.NamedPort> namedPorts_ = java.util.Collections.emptyList(); private void ensureNamedPortsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { namedPorts_ = new java.util.ArrayList<com.google.cloud.compute.v1.NamedPort>(namedPorts_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.NamedPort, com.google.cloud.compute.v1.NamedPort.Builder, com.google.cloud.compute.v1.NamedPortOrBuilder> namedPortsBuilder_; /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public java.util.List<com.google.cloud.compute.v1.NamedPort> getNamedPortsList() { if (namedPortsBuilder_ == null) { return java.util.Collections.unmodifiableList(namedPorts_); } else { return namedPortsBuilder_.getMessageList(); } } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public int getNamedPortsCount() { if (namedPortsBuilder_ == null) { return namedPorts_.size(); } else { return namedPortsBuilder_.getCount(); } } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public com.google.cloud.compute.v1.NamedPort getNamedPorts(int index) { if (namedPortsBuilder_ == null) { return namedPorts_.get(index); } else { return namedPortsBuilder_.getMessage(index); } } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder setNamedPorts(int index, com.google.cloud.compute.v1.NamedPort value) { if (namedPortsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamedPortsIsMutable(); namedPorts_.set(index, value); onChanged(); } else { namedPortsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder setNamedPorts( int index, com.google.cloud.compute.v1.NamedPort.Builder builderForValue) { if (namedPortsBuilder_ == null) { ensureNamedPortsIsMutable(); namedPorts_.set(index, builderForValue.build()); onChanged(); } else { namedPortsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder addNamedPorts(com.google.cloud.compute.v1.NamedPort value) { if (namedPortsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamedPortsIsMutable(); namedPorts_.add(value); onChanged(); } else { namedPortsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder addNamedPorts(int index, com.google.cloud.compute.v1.NamedPort value) { if (namedPortsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNamedPortsIsMutable(); namedPorts_.add(index, value); onChanged(); } else { namedPortsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder addNamedPorts(com.google.cloud.compute.v1.NamedPort.Builder builderForValue) { if (namedPortsBuilder_ == null) { ensureNamedPortsIsMutable(); namedPorts_.add(builderForValue.build()); onChanged(); } else { namedPortsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder addNamedPorts( int index, com.google.cloud.compute.v1.NamedPort.Builder builderForValue) { if (namedPortsBuilder_ == null) { ensureNamedPortsIsMutable(); namedPorts_.add(index, builderForValue.build()); onChanged(); } else { namedPortsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder addAllNamedPorts( java.lang.Iterable<? extends com.google.cloud.compute.v1.NamedPort> values) { if (namedPortsBuilder_ == null) { ensureNamedPortsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, namedPorts_); onChanged(); } else { namedPortsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder clearNamedPorts() { if (namedPortsBuilder_ == null) { namedPorts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { namedPortsBuilder_.clear(); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public Builder removeNamedPorts(int index) { if (namedPortsBuilder_ == null) { ensureNamedPortsIsMutable(); namedPorts_.remove(index); onChanged(); } else { namedPortsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public com.google.cloud.compute.v1.NamedPort.Builder getNamedPortsBuilder(int index) { return getNamedPortsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public com.google.cloud.compute.v1.NamedPortOrBuilder getNamedPortsOrBuilder(int index) { if (namedPortsBuilder_ == null) { return namedPorts_.get(index); } else { return namedPortsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public java.util.List<? extends com.google.cloud.compute.v1.NamedPortOrBuilder> getNamedPortsOrBuilderList() { if (namedPortsBuilder_ != null) { return namedPortsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(namedPorts_); } } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public com.google.cloud.compute.v1.NamedPort.Builder addNamedPortsBuilder() { return getNamedPortsFieldBuilder() .addBuilder(com.google.cloud.compute.v1.NamedPort.getDefaultInstance()); } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public com.google.cloud.compute.v1.NamedPort.Builder addNamedPortsBuilder(int index) { return getNamedPortsFieldBuilder() .addBuilder(index, com.google.cloud.compute.v1.NamedPort.getDefaultInstance()); } /** * * * <pre> * The list of named ports to set for this instance group. * </pre> * * <code>repeated .google.cloud.compute.v1.NamedPort named_ports = 427598732;</code> */ public java.util.List<com.google.cloud.compute.v1.NamedPort.Builder> getNamedPortsBuilderList() { return getNamedPortsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.NamedPort, com.google.cloud.compute.v1.NamedPort.Builder, com.google.cloud.compute.v1.NamedPortOrBuilder> getNamedPortsFieldBuilder() { if (namedPortsBuilder_ == null) { namedPortsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.NamedPort, com.google.cloud.compute.v1.NamedPort.Builder, com.google.cloud.compute.v1.NamedPortOrBuilder>( namedPorts_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); namedPorts_ = null; } return namedPortsBuilder_; } @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.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest) private static final com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest(); } public static com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RegionInstanceGroupsSetNamedPortsRequest> PARSER = new com.google.protobuf.AbstractParser<RegionInstanceGroupsSetNamedPortsRequest>() { @java.lang.Override public RegionInstanceGroupsSetNamedPortsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RegionInstanceGroupsSetNamedPortsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RegionInstanceGroupsSetNamedPortsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RegionInstanceGroupsSetNamedPortsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.RegionInstanceGroupsSetNamedPortsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
ssantan2/apollo_engine
Apollo-common/src/main/java/apollo/common/templates/Book.java
5865
package apollo.common.templates; import java.util.Set; /** * Book Class manages the book of bids and asks. * A book can manage any set of bid and asks (1-tier) So it is up to users to manage upper levels. * Created by santana on 7/28/14. */ public class Book<V extends SwapMapper, T extends Swap> { //Map of a set of bids that are asking for the swap that is mapped (some has a swap and they want to what people are offering for it) private volatile BookMap<V, T> bids = null; //Map of a set of bids that match the mapping of that bid (someone wants a swap and they want to see what are available) private volatile BookMap<V, T> asks = null; //Map of a set of swaps that people are asking for in exchange for the bid (key) private volatile BookMap<V, T> goals = null; //amount of bids that have been placed in this book private volatile int swapSize = 0; /** * Book constructor that initializes the ask, bid and goal maps */ public Book() { bids = new BookMap<V, T>(); asks = new BookMap<V, T>(); goals = new BookMap<V, T>(); } /** * Searches for a swap matching the ask criteria that wants what the bid is. * If a match is found. it removes the match from the engine and send the matching swap back, linking two to each other. * If nothing exists, return null * @param bid * The swap the person has * @param ask * The swap the person wants * @return * an actual swap that matches the ask */ public T fillBook(T bid, T ask) { T match = bids.get(bid, ask); if(match != null) { removeFromBook(bid, match); } return match; } /** * Searches for a swap matching the ask criteria that wants what the bid is, without editing the book. * If nothing exists, it returns null. * @param bid * The swap the person has * @param ask * The swap the person wants * @return * an actual swap that matches the ask */ public T match(T bid, T ask) { return bids.check(bid, ask); } /** * Searches for a swap matching the ask criteria. * If a match is found it will flag that swap, remove it from the book and return it. * If nothing exists, it returns null. * @param ask * The swap that you want * @return * A match to the swap you are looking for */ public T grab(T ask) { return asks.get(ask); } /** * gets a list of all the swaps that someone will trade bid for. * @param bid * The swap that is looking to be sold * @return * set of swaps that people want who have bid */ public Set<T> getAsks(T bid) { return goals.getSet(bid); } /** * gets a list of all the swaps that match bid that are in this book. * @param bid * The swap that matches the criteria you are looking for * @return * set of swaps that people are selling that match the bid criteria */ public Set<T> getBids(T bid) { return bids.getSet(bid); } /** * get all bids that are in this book. * @return * A set of all bids in this book. */ public Set<T> getAllBids() { return bids.getAll(); } /** * Adds the bid and ask to the book * @param bid * The swap that someone is willing to trade * @param ask * The swap that someone wants in return. */ public void addToBook(T bid, T ask) { //only add to the asks book if the bid is for sale if(bid.isForSale()) { addToMap(bid, bid, asks); } addToMap(ask, bid, bids); addToMap(bid, ask, goals); swapSize++; } /** * removes the bid and ask from the book * @param bid * The swap that someone is willing to trade * @param ask * The swap that someone wants in return. */ private void removeFromBook(T bid, T ask) { removeFromMap(ask, ask, asks); removeFromMap(bid, ask, bids); removeFromMap(ask, bid, goals); swapSize--; } /** * Adds the specific key swap and value swap to the map for the book * @param key * The swap you want to map the entry swap to. * @param entry * The swap that you are storing in the map * @param map * the map you are adding the key/value pair to */ private void addToMap(T key, T entry, BookMap<V,T> map) { if(key != null && entry != null && map != null) { map.put(key, entry); } } /** * removes the specific key swap and value swap to the map for the book * @param key * The swap you want to map the entry swap to. * @param entry * The swap that you are removing in the map * @param map * the map you are removing the key/value pair to */ private void removeFromMap(T key, T entry,BookMap<V, T> map) { if(key != null && entry != null && map != null) { map.remove(key, entry); } } /** * Returns whether or not the book has no bids * @return * True - If book is empty */ public boolean isEmpty() { if(swapSize == 0) { return true; } return false; } /** * how many bids are in the book. * @return * the amount of bids in the book. */ public int size() { return swapSize; } /** * clears all the maps and sets the swapSize to zero */ public void flush() { bids.clear(); asks.clear(); goals.clear(); swapSize = 0; } }
apache-2.0
Appdynamics/iPlanet-monitoring-extension
src/main/java/com/appdynamics/monitors/iPlanet/beans/VirtualServer.java
1682
/* * Copyright 2014. AppDynamics LLC and its affiliates. * All Rights Reserved. * This is unpublished proprietary source code of AppDynamics LLC and its affiliates. * The copyright notice above does not evidence any actual or intended publication of such source code. */ package com.appdynamics.monitors.iPlanet.beans; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; import java.util.List; @XStreamAlias("virtual-server") public class VirtualServer { @XStreamAsAttribute() private String mode; @XStreamAlias("request-bucket") private RequestBucket requestBucket; @XStreamImplicit(itemFieldName = "profile-bucket") private List<ProfileBucket> profileBuckets; @XStreamImplicit(itemFieldName = "web-app-bucket") private List<WebAppBucket> webAppBuckets; public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public RequestBucket getRequestBucket() { return requestBucket; } public void setRequestBucket(RequestBucket requestBucket) { this.requestBucket = requestBucket; } public List<ProfileBucket> getProfileBuckets() { return profileBuckets; } public void setProfileBuckets(List<ProfileBucket> profileBuckets) { this.profileBuckets = profileBuckets; } public List<WebAppBucket> getWebAppBuckets() { return webAppBuckets; } public void setWebAppBuckets(List<WebAppBucket> webAppBuckets) { this.webAppBuckets = webAppBuckets; } }
apache-2.0
SEEG-Oxford/ABRAID-MP
src/Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/domain/DiseaseProcessTypeTest.java
871
package uk.ac.ox.zoo.seeg.abraid.mp.common.domain; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for EffectCurveCovariateInfluence. * Copyright (c) 2014 University of Oxford */ public class DiseaseProcessTypeTest { @Test public void isAutomatic() throws Exception { assertThat(DiseaseProcessType.AUTOMATIC.isAutomatic()).isTrue(); assertThat(DiseaseProcessType.MANUAL.isAutomatic()).isFalse(); assertThat(DiseaseProcessType.MANUAL_GOLD_STANDARD.isAutomatic()).isFalse(); } @Test public void isGoldStandard() throws Exception { assertThat(DiseaseProcessType.AUTOMATIC.isGoldStandard()).isFalse(); assertThat(DiseaseProcessType.MANUAL.isGoldStandard()).isFalse(); assertThat(DiseaseProcessType.MANUAL_GOLD_STANDARD.isGoldStandard()).isTrue(); } }
apache-2.0
Koziolek/koziolekweb
guava/prog_funkcyjne/src/main/java/pl/koziolekweb/guava/AbstractDecorator.java
746
package pl.koziolekweb.guava; import com.google.common.base.Function; import com.google.common.base.Preconditions; import static com.google.common.base.Preconditions.checkNotNull; /** * TODO write JAVADOC!!! * User: koziolek */ public abstract class AbstractDecorator<I, O> implements Function<I, O> { protected final Function<I, O> originalFunction; protected AbstractDecorator(Function<I, O> originalFunction) { checkNotNull(originalFunction); this.originalFunction = originalFunction; } protected abstract void before(I input); protected abstract void after(I input, O output); @Override public O apply(I input) { before(input); O output = originalFunction.apply(input); after(input, output); return output; } }
apache-2.0
gazman-sdk/SQLite-Assets-Helper
library/src/main/java/com/gazman/db/CursorList.java
717
package com.gazman.db; import android.database.Cursor; import android.text.TextUtils; import androidx.annotation.NonNull; import java.util.ArrayList; /** * Created by Ilya Gazman on 7/9/2016. */ public abstract class CursorList<E> extends ArrayList<E> { public CursorList(Cursor cursor) { if (cursor.moveToFirst()) { initColumnIndexes(cursor); do { add(processRaw(cursor)); } while (cursor.moveToNext()); } } protected abstract void initColumnIndexes(Cursor cursor); protected abstract E processRaw(Cursor cursor); @NonNull @Override public String toString() { return TextUtils.join(",", this); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/InventoryResultEntityJsonUnmarshaller.java
3193
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * InventoryResultEntity JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InventoryResultEntityJsonUnmarshaller implements Unmarshaller<InventoryResultEntity, JsonUnmarshallerContext> { public InventoryResultEntity unmarshall(JsonUnmarshallerContext context) throws Exception { InventoryResultEntity inventoryResultEntity = new InventoryResultEntity(); 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("Id", targetDepth)) { context.nextToken(); inventoryResultEntity.setId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Data", targetDepth)) { context.nextToken(); inventoryResultEntity.setData(new MapUnmarshaller<String, InventoryResultItem>(context.getUnmarshaller(String.class), InventoryResultItemJsonUnmarshaller.getInstance()).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 inventoryResultEntity; } private static InventoryResultEntityJsonUnmarshaller instance; public static InventoryResultEntityJsonUnmarshaller getInstance() { if (instance == null) instance = new InventoryResultEntityJsonUnmarshaller(); return instance; } }
apache-2.0
franck-benault/test-java-collection
01-javacollection/src/test/java/net/franckbenault/testcollection/ListTestCase.java
562
package net.franckbenault.testcollection; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.junit.Test; public class ListTestCase { @Test public void testEmptyList() { List<String> strings = Collections.emptyList(); assertTrue(strings.isEmpty()); } @Test(expected=UnsupportedOperationException.class) public void testEmptyList_UnsupportedOperationException() { List<String> strings = Collections.emptyList(); assertTrue(strings.isEmpty()); strings.add("foo"); } }
apache-2.0
ycaihua/omicron
omicron-common/src/main/java/com/datagre/apps/omicron/common/constants/ReleaseOperationContext.java
343
package com.datagre.apps.omicron.common.constants; /** * @author Jason Song(song_s@ctrip.com) */ public interface ReleaseOperationContext { String SOURCE_BRANCH = "sourceBranch"; String RULES = "rules"; String OLD_RULES = "oldRules"; String BASE_RELEASE_ID = "baseReleaseId"; String IS_EMERGENCY_PUBLISH = "isEmergencyPublish"; }
apache-2.0
riccardove/easyjasub
easyjasub-lib/src/main/java/com/github/riccardove/easyjasub/EasyJaSubCssTemplateParameter.java
2899
package com.github.riccardove.easyjasub; /* * #%L * easyjasub-lib * %% * Copyright (C) 2014 Riccardo Vestrini * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ class EasyJaSubCssTemplateParameter { private String kanaFont; public String getKanaFont() { return kanaFont; } public void setKanaFont(String kanaFont) { this.kanaFont = kanaFont; } public String getKanjiFont() { return kanjiFont; } public void setKanjiFont(String kanjiFont) { this.kanjiFont = kanjiFont; } public String getTranslationFont() { return translationFont; } public void setTranslationFont(String translationFont) { this.translationFont = translationFont; } public int getShadow() { return shadow; } public void setShadow(int shadow) { this.shadow = shadow; } public int getKanjiSize() { return kanjiSize; } public void setKanjiSize(int kanjiSize) { this.kanjiSize = kanjiSize; } public int getHiraganaSize() { return hiraganaSize; } public void setHiraganaSize(int hiraganaSize) { this.hiraganaSize = hiraganaSize; } public int getDictionarySize() { return dictionarySize; } public void setDictionarySize(int dictionarySize) { this.dictionarySize = dictionarySize; } public int getFuriganaSize() { return furiganaSize; } public void setFuriganaSize(int furiganaSize) { this.furiganaSize = furiganaSize; } public int getTranslation() { return translation; } public void setTranslation(int translation) { this.translation = translation; } public int getLineHeight() { return lineHeight; } public void setLineHeight(int lineHeight) { this.lineHeight = lineHeight; } public int getKanjiSpacing() { return kanjiSpacing; } public void setKanjiSpacing(int kanjiSpacing) { this.kanjiSpacing = kanjiSpacing; } public int getHiraganaSpacing() { return hiraganaSpacing; } public void setHiraganaSpacing(int hiraganaSpacing) { this.hiraganaSpacing = hiraganaSpacing; } private String kanjiFont; private String translationFont; private int shadow; private int kanjiSize; private int hiraganaSize; private int dictionarySize; private int furiganaSize; private int translation; private int lineHeight; private int kanjiSpacing; private int hiraganaSpacing; }
apache-2.0
jeffpsherman/projecteuler
src/com/shermanconsulting/projecteuler/mathUtils/BigNumbers.java
978
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.shermanconsulting.projecteuler.mathUtils; /** * * @author sherman */ public class BigNumbers { public static byte[] convertStringToBytes(final String digits) { byte[] asBytes = new byte[digits.length()]; byte[] raw = digits.getBytes(); byte zeroOffset = '0'; for (int x=0; x< raw.length; x++) { asBytes[x] = (byte)((int)raw[x] - (int)zeroOffset); } return asBytes; } public static long largestProduct(byte[] digits, int size) { long highestProduct = 0; for (int x=0; x+size < digits.length; x++) { long newVal = digits[x]; for (int y = 1; y < size; y++) { newVal *= digits[x+y]; } if (newVal > highestProduct) { highestProduct = newVal; } } return highestProduct; } }
apache-2.0
amottier/qmrb
backend/src/main/java/com/quelmarabout/dto/Phone.java
577
package com.quelmarabout.dto; public class Phone { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } private String number; private PhoneType phoneType; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public PhoneType getPhoneType() { return phoneType; } public void setPhoneType(PhoneType phoneType) { this.phoneType = phoneType; } }
apache-2.0
uvsystem/rumkit-java-client
src/main/java/com/dbsys/rs/client/frame/TambahPasien.java
13920
package com.dbsys.rs.client.frame; import com.dbsys.rs.client.DateUtil; import com.dbsys.rs.client.entity.Penduduk; import com.dbsys.rs.connector.ServiceException; import com.dbsys.rs.connector.service.PendudukService; import java.awt.Color; import java.sql.Date; import java.util.Calendar; import javax.swing.JOptionPane; /** * * @author Deddy Christoper Kakunsi */ public final class TambahPasien extends javax.swing.JFrame { private final PendudukService pendudukService = PendudukService.getInstance(); private Penduduk penduduk; /** * Creates new form TambahPasien */ public TambahPasien() { initComponents(); setData(null); setCustomSize(); } /** * Creates new form TambahPasien * @param penduduk */ public TambahPasien(Penduduk penduduk) { initComponents(); setData(penduduk); setCustomSize(); } private void setCustomSize() { this.setSize(450, 650); } private void setData(Penduduk penduduk) { if (penduduk == null) { txtPendudukKode.setText(Penduduk.createKode()); txtPendudukNik.setText(null); txtPendudukNama.setText(null); cbPendudukKelamin.setSelectedIndex(0); txtPendudukTanggalLahir.setSelectedDate(null); txtPendudukDarah.setText(null); txtPendudukAgama.setText(null); txtPendudukTelepon.setText(null); txtPendudukAlamat.setText(null); txtPendudukPekerjaan.setText(null); txtPendudukJenisKartu.setText(null); Calendar now = Calendar.getInstance(); now.setTime(DateUtil.getDate()); txtPendudukTanggalDaftar.setSelectedDate(now); } else { txtPendudukKode.setText(penduduk.getKode()); txtPendudukNik.setText(penduduk.getNik()); txtPendudukNama.setText(penduduk.getNama()); cbPendudukKelamin.setSelectedItem(penduduk.getKelamin().toString()); txtPendudukDarah.setText(penduduk.getDarah()); txtPendudukAgama.setText(penduduk.getAgama()); txtPendudukTelepon.setText(penduduk.getTelepon()); txtPendudukAlamat.setText(penduduk.getAlamat()); txtPendudukPekerjaan.setText(penduduk.getPekerjaan()); txtPendudukJenisKartu.setText(penduduk.getJenisKartu()); Calendar tanggalLahir = Calendar.getInstance(); tanggalLahir.setTime(penduduk.getTanggalLahir()); txtPendudukTanggalLahir.setSelectedDate(tanggalLahir); if (penduduk.getTanggalDaftar() != null) { Calendar tanggalDaftar = Calendar.getInstance(); tanggalDaftar.setTime(penduduk.getTanggalDaftar()); txtPendudukTanggalDaftar.setSelectedDate(tanggalDaftar); } } this.penduduk = penduduk; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnlDetail = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); txtPendudukKode = new javax.swing.JTextField(); txtPendudukNik = new javax.swing.JTextField(); txtPendudukNama = new javax.swing.JTextField(); cbPendudukKelamin = new javax.swing.JComboBox(); txtPendudukDarah = new javax.swing.JTextField(); txtPendudukAgama = new javax.swing.JTextField(); txtPendudukTelepon = new javax.swing.JTextField(); txtPendudukTanggalLahir = new datechooser.beans.DateChooserCombo(); txtPendudukTanggalDaftar = new datechooser.beans.DateChooserCombo(); txtPendudukAlamat = new javax.swing.JTextField(); txtPendudukPekerjaan = new javax.swing.JTextField(); txtPendudukJenisKartu = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); btnPendudukClean = new javax.swing.JButton(); btnPendudukSimpan = new javax.swing.JButton(); lblBackground = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("TAMBAH REKAM MEDIK"); setMaximumSize(new java.awt.Dimension(437, 605)); setMinimumSize(new java.awt.Dimension(437, 605)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); pnlDetail.setBackground(Utama.colorTransparentPanel); pnlDetail.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "DATA REKAM MEDIK", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N pnlDetail.setBackground(new Color(0,0,0,20)); pnlDetail.setLayout(null); jLabel4.setText("NO. MEDREK"); pnlDetail.add(jLabel4); jLabel4.setBounds(20, 30, 100, 25); jLabel5.setText("NO. JAMINAN"); pnlDetail.add(jLabel5); jLabel5.setBounds(20, 60, 100, 25); jLabel6.setText("NAMA"); pnlDetail.add(jLabel6); jLabel6.setBounds(20, 90, 100, 25); jLabel7.setText("KELAMIN"); pnlDetail.add(jLabel7); jLabel7.setBounds(20, 120, 100, 25); jLabel8.setText("TANGGAL LAHIR"); pnlDetail.add(jLabel8); jLabel8.setBounds(20, 150, 100, 25); jLabel9.setText("GOL. DARAH"); pnlDetail.add(jLabel9); jLabel9.setBounds(20, 180, 100, 25); jLabel10.setText("AGAMA"); pnlDetail.add(jLabel10); jLabel10.setBounds(20, 210, 100, 25); jLabel11.setText("TELEPON"); pnlDetail.add(jLabel11); jLabel11.setBounds(20, 240, 100, 25); txtPendudukKode.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukKode); txtPendudukKode.setBounds(130, 30, 250, 25); txtPendudukNik.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukNik); txtPendudukNik.setBounds(130, 60, 250, 25); txtPendudukNama.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukNama); txtPendudukNama.setBounds(130, 90, 250, 25); cbPendudukKelamin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- Pilih -", "PRIA", "WANITA" })); cbPendudukKelamin.setBorder(null); pnlDetail.add(cbPendudukKelamin); cbPendudukKelamin.setBounds(130, 120, 250, 25); txtPendudukDarah.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukDarah); txtPendudukDarah.setBounds(130, 180, 250, 25); txtPendudukAgama.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukAgama); txtPendudukAgama.setBounds(130, 210, 250, 25); txtPendudukTelepon.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukTelepon); txtPendudukTelepon.setBounds(130, 240, 250, 25); pnlDetail.add(txtPendudukTanggalLahir); txtPendudukTanggalLahir.setBounds(130, 150, 250, 25); pnlDetail.add(txtPendudukTanggalDaftar); txtPendudukTanggalDaftar.setBounds(130, 360, 250, 25); txtPendudukAlamat.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukAlamat); txtPendudukAlamat.setBounds(130, 270, 250, 25); txtPendudukPekerjaan.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukPekerjaan); txtPendudukPekerjaan.setBounds(130, 300, 250, 25); txtPendudukJenisKartu.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlDetail.add(txtPendudukJenisKartu); txtPendudukJenisKartu.setBounds(130, 330, 250, 25); jLabel12.setText("ALAMAT"); pnlDetail.add(jLabel12); jLabel12.setBounds(20, 270, 100, 25); jLabel13.setText("PEKERJAAN"); pnlDetail.add(jLabel13); jLabel13.setBounds(20, 300, 100, 25); jLabel14.setText("JENIS KARTU"); pnlDetail.add(jLabel14); jLabel14.setBounds(20, 330, 100, 25); jLabel15.setText("TANGGAL DAFTAR"); pnlDetail.add(jLabel15); jLabel15.setBounds(20, 360, 100, 25); getContentPane().add(pnlDetail, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 400, 400)); btnPendudukClean.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_reset.png"))); // NOI18N btnPendudukClean.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPendudukCleanActionPerformed(evt); } }); getContentPane().add(btnPendudukClean, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 560, 80, 30)); btnPendudukSimpan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_simpan.png"))); // NOI18N btnPendudukSimpan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPendudukSimpanActionPerformed(evt); } }); getContentPane().add(btnPendudukSimpan, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 560, 80, 30)); lblBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/bg_main.png"))); // NOI18N getContentPane().add(lblBackground, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 800)); pack(); }// </editor-fold>//GEN-END:initComponents private void btnPendudukSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPendudukSimpanActionPerformed if (penduduk == null) penduduk = new Penduduk(); String kelamin = cbPendudukKelamin.getSelectedItem().toString(); Calendar calendarTanggalLahir = txtPendudukTanggalLahir.getSelectedDate(); long lTimeTanggalLahir = calendarTanggalLahir.getTimeInMillis(); Calendar calendarTanggalDaftar = txtPendudukTanggalDaftar.getSelectedDate(); long lTimeTanggalDaftar = calendarTanggalDaftar.getTimeInMillis(); penduduk.setKode(txtPendudukKode.getText()); penduduk.setNik(txtPendudukNik.getText().equals("") ? null : txtPendudukNik.getText()); penduduk.setNama(txtPendudukNama.getText()); penduduk.setKelamin(Penduduk.Kelamin.valueOf(kelamin)); penduduk.setTanggalLahir(new Date(lTimeTanggalLahir)); penduduk.setDarah(txtPendudukDarah.getText()); penduduk.setAgama(txtPendudukAgama.getText()); penduduk.setTelepon(txtPendudukTelepon.getText()); penduduk.setAlamat(txtPendudukAlamat.getText()); penduduk.setPekerjaan(txtPendudukPekerjaan.getText()); penduduk.setJenisKartu(txtPendudukJenisKartu.getText()); penduduk.setTanggalDaftar(new Date(lTimeTanggalDaftar)); try { penduduk = pendudukService.simpan(penduduk); this.dispose(); JOptionPane.showMessageDialog(this, "Berhasil menyimpan data rekam medik"); } catch (ServiceException ex) { JOptionPane.showMessageDialog(this, ex.getMessage()); } }//GEN-LAST:event_btnPendudukSimpanActionPerformed private void btnPendudukCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPendudukCleanActionPerformed setData(null); // Reset Form }//GEN-LAST:event_btnPendudukCleanActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnPendudukClean; private javax.swing.JButton btnPendudukSimpan; private javax.swing.JComboBox cbPendudukKelamin; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel lblBackground; private javax.swing.JPanel pnlDetail; private javax.swing.JTextField txtPendudukAgama; private javax.swing.JTextField txtPendudukAlamat; private javax.swing.JTextField txtPendudukDarah; private javax.swing.JTextField txtPendudukJenisKartu; private javax.swing.JTextField txtPendudukKode; private javax.swing.JTextField txtPendudukNama; private javax.swing.JTextField txtPendudukNik; private javax.swing.JTextField txtPendudukPekerjaan; private datechooser.beans.DateChooserCombo txtPendudukTanggalDaftar; private datechooser.beans.DateChooserCombo txtPendudukTanggalLahir; private javax.swing.JTextField txtPendudukTelepon; // End of variables declaration//GEN-END:variables }
apache-2.0
consulo/consulo-java
java-impl/src/main/java/com/siyeh/ig/assignment/AssignmentToCollectionFieldFromParameterInspection.java
4183
/* * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.assignment; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.psiutils.CollectionUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.*; public class AssignmentToCollectionFieldFromParameterInspection extends BaseInspection { /** * @noinspection PublicField */ public boolean ignorePrivateMethods = true; @Nonnull public String getID() { return "AssignmentToCollectionOrArrayFieldFromParameter"; } @Nonnull public String getDisplayName() { return InspectionGadgetsBundle.message( "assignment.collection.array.field.from.parameter.display.name"); } @Nonnull public String buildErrorString(Object... infos) { final PsiExpression rhs = (PsiExpression)infos[0]; final PsiField field = (PsiField)infos[1]; final PsiType type = field.getType(); if (type instanceof PsiArrayType) { return InspectionGadgetsBundle.message( "assignment.collection.array.field.from.parameter.problem.descriptor.array", rhs.getText()); } else { return InspectionGadgetsBundle.message( "assignment.collection.array.field.from.parameter.problem.descriptor.collection", rhs.getText()); } } @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel( InspectionGadgetsBundle.message( "assignment.collection.array.field.option"), this, "ignorePrivateMethods"); } public BaseInspectionVisitor buildVisitor() { return new AssignmentToCollectionFieldFromParameterVisitor(); } private class AssignmentToCollectionFieldFromParameterVisitor extends BaseInspectionVisitor { @Override public void visitAssignmentExpression(@Nonnull PsiAssignmentExpression expression) { super.visitAssignmentExpression(expression); final PsiExpression rhs = expression.getRExpression(); if (!(rhs instanceof PsiReferenceExpression)) { return; } final IElementType tokenType = expression.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.EQ)) { return; } final PsiExpression lhs = expression.getLExpression(); if (!(lhs instanceof PsiReferenceExpression)) { return; } if (ignorePrivateMethods) { final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class); if (containingMethod == null || containingMethod.hasModifierProperty( PsiModifier.PRIVATE)) { return; } } final PsiElement element = ((PsiReference)rhs).resolve(); if (!(element instanceof PsiParameter)) { return; } if (!(element.getParent() instanceof PsiParameterList)) { return; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)lhs; final PsiElement referent = referenceExpression.resolve(); if (!(referent instanceof PsiField)) { return; } final PsiField field = (PsiField)referent; if (!CollectionUtils.isArrayOrCollectionField(field)) { return; } registerError(lhs, rhs, field); } } }
apache-2.0
galeb/galeb-next
health/src/main/java/io/galeb/health/Application.java
859
/* * Copyright (c) 2014-2017 Globo.com - ATeam * All rights reserved. * * This source is subject to the Apache License, Version 2.0. * Please see the LICENSE file for more information. * * Authors: See AUTHORS file * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.galeb.health; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String args[]) { SpringApplication.run(Application.class, args); } }
apache-2.0
inferjay/ATeahour.fm
Teahour.fm/src/main/java/com/inferjay/teahour/fm/android/adapter/TFMNavDrawerListAdapter.java
3114
/** * Copyright 2014 inferjay (http://www.inferjay.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.inferjay.teahour.fm.android.adapter; import java.util.ArrayList; import android.content.Context; import android.content.res.ColorStateList; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.inferjay.teahour.fm.android.R; public class TFMNavDrawerListAdapter extends BaseAdapter { private ArrayList<String> mRssItemTitleList; private LayoutInflater mInflater; private ColorStateList mTitleDfaultColor; private ColorStateList mTitleSelectColor; private ListView mListView; public TFMNavDrawerListAdapter (Context context, ListView listView, ArrayList<String> list) { this.mListView = listView; mRssItemTitleList = list; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mTitleDfaultColor = context.getResources().getColorStateList(R.color.color_drawer_list_item_text_normal); mTitleSelectColor = context.getResources().getColorStateList(R.color.color_drawer_list_item_text_select); } @Override public int getCount() { return mRssItemTitleList != null ? mRssItemTitleList.size() : 0; } @Override public Object getItem(int position) { return mRssItemTitleList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ItemViewHolder itemViewHolder; if (convertView == null) { itemViewHolder = new ItemViewHolder(); itemViewHolder.itemView = (TextView)mInflater.inflate(R.layout.item_nav_drawer_list, parent, false); convertView = itemViewHolder.itemView; convertView.setTag(itemViewHolder); } else { itemViewHolder = (ItemViewHolder) convertView.getTag(); } bindDataToView(convertView, itemViewHolder, position); return convertView; } private void bindDataToView(View convertView, ItemViewHolder itemViewHolder, int position) { itemViewHolder.itemView.setText(mRssItemTitleList.get(position)); if (mListView.isItemChecked(position)) { itemViewHolder.itemView.setTextColor(mTitleSelectColor); // convertView.setBackgroundResource(R.drawable.nav_drawer_list_item_gray_rectangle); } else { itemViewHolder.itemView.setTextColor(mTitleDfaultColor); // convertView.setBackgroundDrawable(null); } } static class ItemViewHolder { TextView itemView; } }
apache-2.0
ezbake/ezbake-security-registration
src/test/java/ezbake/security/service/registration/handler/GetAppTest.java
5589
/* Copyright (C) 2013-2014 Computer Sciences Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ezbake.security.service.registration.handler; import ezbake.base.thrift.EzSecurityToken; import ezbake.security.thrift.*; import org.apache.thrift.TException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; /** * User: jhastings * Date: 4/8/14 * Time: 3:00 PM */ public class GetAppTest extends HandlerBaseTest { @Test public void testRegisterAndGet() throws RegistrationException, SecurityIDExistsException, TException, SecurityIDNotFoundException, PermissionDeniedException { EzSecurityToken token = getTestEzSecurityToken(false); final String appName = "Dune"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); String id = handler.registerApp(token, appName, appClass, appAuths, null, null, "app dn"); ApplicationRegistration reg = handler.getRegistration(token, id); Assert.assertEquals(id, reg.getId()); Assert.assertEquals(appName, reg.getAppName()); Assert.assertEquals(token.getTokenPrincipal().getPrincipal(), reg.getOwner()); Assert.assertEquals(appClass, reg.getClassification()); Assert.assertArrayEquals(appAuths.toArray(), reg.getAuthorizations().toArray()); } @Test public void testGetRegistrationsAdminSeesAll() throws RegistrationException, SecurityIDExistsException, TException { EzSecurityToken adminToken = getTestEzSecurityToken(true); EzSecurityToken user1Token = getTestEzSecurityToken(false, "User1"); EzSecurityToken user2Token = getTestEzSecurityToken(false, "User2"); final String appName = "TestApp1"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); handler.registerApp(user1Token, appName, appClass, appAuths, null,null, "app dn"); handler.registerApp(user2Token, appName, appClass, appAuths, null,null, "app dn"); List<ApplicationRegistration> registrations = handler.getRegistrations(adminToken); Assert.assertEquals(2, registrations.size()); } @Test public void testOneUserDoesntSeeOtherUsers() throws RegistrationException, SecurityIDExistsException, TException { EzSecurityToken user1Token = getTestEzSecurityToken(false, "User1"); EzSecurityToken user2Token = getTestEzSecurityToken(false, "User2"); final String appName = "TestApp1"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); handler.registerApp(user1Token, appName, appClass, appAuths, null,null, "app dn"); handler.registerApp(user2Token, appName, appClass, appAuths, null,null, "app dn"); List<ApplicationRegistration> registrations = handler.getRegistrations(user1Token); Assert.assertEquals(1, registrations.size()); } @Test(expected=SecurityIDNotFoundException.class) public void testOneUserDoesntSeeOtherUsersWhenQueryById() throws RegistrationException, SecurityIDExistsException, TException, SecurityIDNotFoundException, PermissionDeniedException { EzSecurityToken user1Token = getTestEzSecurityToken(false, "User1"); EzSecurityToken user2Token = getTestEzSecurityToken(false, "User2"); final String appName = "TestApp1"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); handler.registerApp(user1Token, appName, appClass, appAuths, null,null, "app dn"); String hiddenID = handler.registerApp(user2Token, appName, appClass, appAuths, null,null, "app dn"); ApplicationRegistration registrations = handler.getRegistration(user1Token, hiddenID); Assert.assertNull(registrations); } @Test public void testGetAllReturnsPendingWithFilter() throws RegistrationException, SecurityIDExistsException, TException { EzSecurityToken user1Token = getTestEzSecurityToken(false, "User1"); final String appName = "TestApp1"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); handler.registerApp(user1Token, appName, appClass, appAuths, null,null, "app dn"); List<ApplicationRegistration> registrations = handler.getAllRegistrations(user1Token, RegistrationStatus.PENDING); Assert.assertEquals(1, registrations.size()); } @Test public void testGetAllReturnsPendingWithoutFilter() throws RegistrationException, SecurityIDExistsException, TException { EzSecurityToken user1Token = getTestEzSecurityToken(false, "User1"); final String appName = "TestApp1"; final String appClass = "U"; final List<String> appAuths = Arrays.asList("U"); handler.registerApp(user1Token, appName, appClass, appAuths, null,null, "app dn"); List<ApplicationRegistration> registrations = handler.getAllRegistrations(user1Token); Assert.assertEquals(1, registrations.size()); } }
apache-2.0
ramizdemiurge/website-javaee2
src/main/java/Controllers/RegisterController.java
5767
package Controllers; import config.DataConfig; import entity.User; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import service.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; @Controller @RequestMapping("/reg") public class RegisterController { @RequestMapping(method = RequestMethod.POST) public void RegistererContr(HttpServletRequest req, HttpServletResponse resp) throws IOException { String[] string_datas = new String[4]; string_datas[0] = req.getParameter("login").trim().toLowerCase(); string_datas[1] = req.getParameter("email").trim().toLowerCase(); string_datas[2] = req.getParameter("passwd"); string_datas[3] = req.getParameter("passwd2"); if (!(string_datas[0].equals(null) || string_datas[0].equals(""))) { if (!(string_datas[1].equals(null) || string_datas[1].equals(""))) { if (!(string_datas[2].equals(null) || string_datas[2].equals(""))) { if (!(string_datas[3].equals(null) || string_datas[3].equals(""))) { if (string_datas[2].equals(string_datas[3])) { /** * Тут надо чекнуть, если ли в бд юзер с таким именем. * Работаем с базой данных */ ApplicationContext context = new AnnotationConfigApplicationContext(DataConfig.class); UserService userService = context.getBean(UserService.class); User user = userService.getByUsername(string_datas[0]); if (user == null) { /** * Теперь чекаю, есть ли в бд юзер с таким e-mail * база данных */ user = userService.getByEmail(string_datas[1]); if (user == null) { /** * Итак, все поля введены. Пароль и подтверждение совпадают. * В базе нет пользователей с совпадающим username и email. * Пожалуй, можно занести данные в бд. Следовало бы символы проверить. * Но это в будущем. */ Date date = new Date(); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); string_datas[2] = DigestUtils.sha1Hex(string_datas[2]); User user1 = new User(); user1.setUsername(string_datas[0]); user1.setEmail(string_datas[1]); user1.setPassword(string_datas[2]); user1.setRegDate(sqlDate); user1.setReg_date(date.toString()); userService.addUser(user1); req.getSession().setAttribute("messages", "You have registered.<br>Your username: " + string_datas[0]); resp.sendRedirect("/index.html"); } else { req.getSession().setAttribute("messages", "Try another email adress."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Try another username."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Password and password confirmation values are not same."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Enter your password confirmation."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Enter your password."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Enter your email."); resp.sendRedirect("/index.html"); } } else { req.getSession().setAttribute("messages", "Enter your login."); resp.sendRedirect("/index.html"); } } }
apache-2.0
bwolf/imapprowler
src/main/java/org/antbear/imapprowler/cache/MessageCacheManager.java
4707
package org.antbear.imapprowler.cache; import org.antbear.imapprowler.util.VoidFunction; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.validation.constraints.NotNull; import java.io.*; import java.util.Map; import static org.antbear.imapprowler.util.InvariantException.invariantNotNull; import static org.antbear.imapprowler.util.InvariantException.invariantNotNullOrEmpty; @Named @Singleton public class MessageCacheManager { private final static Logger log = LoggerFactory.getLogger(MessageCacheManager.class); @Inject private DefaultMessageCache cache; private String filePath; private void validateState() { invariantNotNull(this.cache, "cache"); invariantNotNullOrEmpty(this.filePath, "filePath"); } @NotNull public synchronized MessageCache getCache() { validateState(); if (isState(MessageCacheState.CACHE_EMPTY)) { sync(); } return cache; } public synchronized void setCache(@NotNull final DefaultMessageCache cache) { this.cache = cache; } public void withCache(final VoidFunction<MessageCache> func) { validateState(); if (isState(MessageCacheState.CACHE_EMPTY)) { sync(); } try { func.apply(this.cache); } catch (Exception e) { log.error("withCache exception", e); } if (isState(MessageCacheState.CACHE_DIRTY)) { sync(); } } @NotNull public String getFilePath() { return filePath; } public void setFilePath(@NotNull final String filePath) { this.filePath = filePath; } private boolean isState(final MessageCacheState state) { return state.equals(this.cache.getState()); } private void setState(final MessageCacheState state) { this.cache.setState(state); } private void sync() { final MessageCacheState state = this.cache.getState(); log.debug("Syncing cache in state " + state); if (isState(MessageCacheState.CACHE_EMPTY)) { final File f = new File(this.filePath); if (!f.exists()) { log.debug("Not loading missing cache file from disk"); setState(MessageCacheState.CACHE_SYNC); return; } load(); setState(MessageCacheState.CACHE_SYNC); log.debug("Loaded cache from disc {}", this.cache); } else if (isState(MessageCacheState.CACHE_DIRTY)) { save(); setState(MessageCacheState.CACHE_SYNC); } else if (isState(MessageCacheState.CACHE_SYNC)) { //noinspection UnnecessaryReturnStatement return; } else { throw new MessageCacheException("Unhandled cache state " + state); } } private void save() { log.debug("Saving cache " + this.cache); ObjectOutputStream os = null; try { os = new ObjectOutputStream(new FileOutputStream(this.filePath)); os.writeObject(this.cache.getCache()); } catch (IOException ioe) { throw new MessageCacheException("Save error", ioe); } finally { if (null != os) { try { os.flush(); os.close(); } catch (IOException ioe) { //noinspection ThrowFromFinallyBlock throw new MessageCacheException("Failed close", ioe); } } } } private void load() { log.debug("Loading cache {}", this.cache); ObjectInputStream is = null; try { is = new ObjectInputStream(new FileInputStream(this.filePath)); @SuppressWarnings("unchecked") final Map<Integer, DateTime> cache = (Map<Integer, DateTime>) is.readObject(); this.cache.setCache(cache); } catch (IOException ioe) { throw new MessageCacheException("Load error", ioe); } catch (ClassNotFoundException e) { throw new MessageCacheException("Serialization error, class not found; Code change, remove cache file: " + this.filePath); } finally { if (null != is) { try { is.close(); } catch (IOException ioe) { //noinspection ThrowFromFinallyBlock throw new MessageCacheException("Failed close", ioe); } } } } }
apache-2.0
missioncommand/mil-sym-java
service/mil-sym-service/src/main/java/sec/web/renderer/services/imaging/ImageGeneratorController.java
21079
package sec.web.renderer.services.imaging; import ArmyC2.C2SD.Utilities.MilStdAttributes; import ArmyC2.C2SD.Utilities.RendererSettings; import ArmyC2.C2SD.Utilities.SymbolUtilities; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import sec.web.json.utilities.JSONArray; import sec.web.json.utilities.JSONObject; import sec.web.renderer.SECRenderer; import sec.web.renderer.SECWebRenderer; import sec.web.renderer.model.RenderingDataEnums; import sec.web.renderer.utilities.JavaRendererUtilities; import sec.web.renderer.utilities.PNGInfo; import sec.web.renderer.utils.ImagingUtils; import sec.web.renderer.utils.MultiPointUtils; import sec.web.renderer.utils.ResourceUtils; @Controller @SuppressWarnings("unused") public class ImageGeneratorController { public final String EMPTY_STRING = ""; public ImageGeneratorController() { try {//READ PROPERTIES Properties props = ResourceUtils.loadResource("properties/prop.properties", this.getClass().getClassLoader()); //get rendering standard//////////////////////////////////// String symStd = props.getProperty("symStd"); System.out.println("SymStd: " + symStd); if(SymbolUtilities.isNumber(symStd)) { RendererSettings.getInstance().setSymbologyStandard(Integer.parseInt(symStd)); } SECRenderer.getInstance().printManifestInfo(); //get textBackgroundMethod////////////////////////////////// String textBackgroundMethod = props.getProperty("textBackgroundMethod"); System.out.println("textBackgroundMethod: " + textBackgroundMethod); if(SymbolUtilities.isNumber(textBackgroundMethod)) { RendererSettings.getInstance().setTextBackgroundMethod(Integer.parseInt(textBackgroundMethod)); } //autoCollapseModifiers///////////////////////////////////// String autoCollapseModifiers = props.getProperty("autoCollapseModifiers"); System.out.println("autoCollapseModifiers: " + autoCollapseModifiers); RendererSettings.getInstance().setAutoCollapseModifiers(Boolean.parseBoolean(autoCollapseModifiers)); //autoCollapseModifiers///////////////////////////////////// String operationalConditionModifierType = props.getProperty("operationalConditionModifierType"); System.out.println("operationalConditionModifierType: " + operationalConditionModifierType); RendererSettings.getInstance().setOperationalConditionModifierType(Integer.parseInt(operationalConditionModifierType)); SECRenderer.getInstance().printManifestInfo(); } catch (Exception exc1) { System.err.println(exc1.getMessage()); exc1.printStackTrace(); } try { ImagingUtils.reloadPlugins(); } catch (Exception exc2) { System.err.println(exc2.getMessage()); exc2.printStackTrace(); } } @RequestMapping(value = "/{type}/{symbolId}", method = RequestMethod.GET, produces = "image/png", headers = "Accept=text/html,image/png") @ResponseBody public void getContent(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathVariable("type") String type, @PathVariable("symbolId") String symbolId) throws Exception { byte[] png = null; PNGInfo pi = null; String kml = null; String svg = null; String svgz = null; int svgDrawMode = 0; Boolean isIcon = false; Map<String, String> params = null; switch (RenderingDataEnums.fromString(type)) { case IMAGE: response.setContentType("image/png"); // response.setHeader("Content-Type", "image/png"); png = ImagingUtils.getMilStd2525PngBytes(symbolId, ImagingUtils.getURLParameters(request)); break; case KML: kml = ImagingUtils.getKmlString(request.getRequestURL().toString(), symbolId, ImagingUtils.getURLParameters(request)); break; case SVG: response.setContentType("image/svg+xml"); // response.setHeader("Content-Type", "image/png"); params = ImagingUtils.getURLParameters(request); if(params.containsKey("ICON") && (Boolean.parseBoolean(params.get("ICON")) == true)) { //svgDrawMode = 0; params = JavaRendererUtilities.parseIconParameters(symbolId, params); symbolId = JavaRendererUtilities.sanitizeSymbolID(symbolId); isIcon = true; } pi = ImagingUtils.getMilStd2525Png(symbolId, params); if(isIcon) pi = pi.squareImage(); else { if(params.containsKey("CENTER") && (Boolean.parseBoolean(params.get("CENTER")) == true)) { svgDrawMode = 1; } else if(params.containsKey("SQUARE") && (Boolean.parseBoolean(params.get("SQUARE")) == true)) { svgDrawMode = 2; } } svg = pi.toSVG(svgDrawMode); break; case SVGZ: response.setContentType("image/svg+xml"); // response.setHeader("Content-Type", "image/png"); params = ImagingUtils.getURLParameters(request); pi = ImagingUtils.getMilStd2525Png(symbolId, params); if(params.containsKey("ICON") && (Boolean.parseBoolean(params.get("ICON")) == true)) { //svgDrawMode = 0; params = JavaRendererUtilities.parseIconParameters(symbolId, params); pi = pi.squareImage(); } if(params.containsKey("CENTER") && (Boolean.parseBoolean(params.get("CENTER")) == true)) { svgDrawMode = 1; } else if(params.containsKey("SQAURE") && (Boolean.parseBoolean(params.get("SQAURE")) == true)) { svgDrawMode = 2; } svgz = pi.toSVG(svgDrawMode);//*/ break; default: break; } if (png != null)// write image data { response.getOutputStream().write(png); response.getOutputStream().close(); } else if(kml != null){ // write kml response response.setContentType("application/xml");// //response.setContentType("application/xml");// boolean gzip = false; String acceptEncoding = request.getHeader("Accept-Encoding"); // System.out.println(String.valueOf(acceptEncoding)); if (acceptEncoding != null && acceptEncoding.contains("gzip")) gzip = true; // disable compression for now. maybe use when we create a batch call. //for local testing response.setHeader("Access-Control-Allow-Origin", "*");//headers.set("Access-Control-Allow-Origin", "*") gzip = false; if (gzip == true) { kml = compress(kml); response.setHeader("Content-Length", Integer.toString(kml.length())); response.setHeader("Content-Encoding", "gzip"); }// */ PrintWriter out = response.getWriter(); out.print(kml); out.close(); } else if(svg != null) { response.setContentType("image/svg+xml"); PrintWriter out = response.getWriter(); out.print(svg); out.close(); } else if(svgz != null) { response.setContentType("image/svg+xml"); boolean gzip = false; String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) gzip = true; if (gzip == true) { svgz = compress(svgz); response.setHeader("Content-Length", Integer.toString(svgz.length())); response.setHeader("Content-Encoding", "gzip"); } PrintWriter out = response.getWriter(); out.print(svgz); out.close(); } } @RequestMapping(value = "/{type}/{symbolId}", method = RequestMethod.POST, headers = "Accept=text/html,text/plain,application/xml,application/json") @ResponseBody public void getMultiPointGraphic(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathVariable("type") String type, @PathVariable("symbolId") String symbolId) throws Exception { String kml = null; try { switch (RenderingDataEnums.fromString(type)) { case MP3D: kml = MultiPointUtils.RenderSymbol(symbolId, ImagingUtils.getURLParameters(request)); break; case MP2D: kml = MultiPointUtils.RenderSymbol2D(symbolId, ImagingUtils.getURLParameters(request)); break; default: break; } boolean gzip = false; String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) gzip = true; //gzip = false; if (gzip == true) { int gzipMethod = 1;//0 string, 1 byte array //0 method doesn't work with special characters if(gzipMethod == 0)//gzip string { if (kml.startsWith("<")) { response.setContentType("application/xml"); } else if (kml.startsWith("{")) { response.setContentType("application/json"); } kml = compress(kml); response.setHeader("Content-Length",Integer.toString(kml.length())); response.setHeader("Content-Encoding", "gzip"); PrintWriter out = response.getWriter(); out.print(kml); out.close();//*/ } else//gzip byte array { if (kml.startsWith("<")) { //response.setContentType("application/xml"); response.setContentType("application/xml; charset=utf-8"); } else if (kml.startsWith("{")) { //response.setContentType("application/json"); response.setContentType("application/json; charset=utf-8"); } //response.setHeader("Content-Length",Integer.toString(kml.length())); response.setHeader("Content-Encoding", "gzip");//*/ ServletOutputStream sos = response.getOutputStream(); compressBinary(kml, sos); } } else { //plain string////////////////////////////////////// /*if (kml.startsWith("<")) { response.setContentType("application/xml; charset=utf-8"); } else if (kml.startsWith("{")) { response.setContentType("application/json; charset=utf-8"); } PrintWriter out = response.getWriter(); out.print(kml); out.close();//*/ //byte array//////////////////////////////////////// if (kml.startsWith("<")) { response.setContentType("application/xml; charset=utf-8"); } else if (kml.startsWith("{")) { response.setContentType("application/json; charset=utf-8"); } ServletOutputStream sos = response.getOutputStream(); sos.write(kml.getBytes("UTF-8")); sos.flush(); sos.close(); } } catch (Exception exc) { System.err.println(exc.getMessage()); exc.printStackTrace(); } } @RequestMapping(value = "/{type}", method = RequestMethod.POST, headers = "Accept=text/html,text/plain,application/xml,application/json") @ResponseBody public void getSinglePointBatchInfo(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathVariable("type") String type) throws Exception { String json = null; Map<String, String> params = null; try { switch (RenderingDataEnums.fromString(type)) { case SPBI: params = ImagingUtils.getURLParameters(request); if (params != null && params.containsKey("ICONURLS")) { json = getSinglePointInfoBatch(params.get("ICONURLS")); } else { json = ""; } break; default: break; } response.setContentType("application/json"); boolean gzip = false; String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) gzip = true; if (gzip == true) { json = compress(json); response.setHeader("Content-Length", Integer.toString(json.length())); response.setHeader("Content-Encoding", "gzip"); response.setHeader("Content-Charset", "gzip"); } PrintWriter out = response.getWriter(); out.println(json); out.close(); } catch (Exception exc) { System.err.println(exc.getMessage()); exc.printStackTrace(); } } /** * Compress a regular string into a GZIP compressed string. * @param str * @return * function kills special characters. Haven't figured out how to * prevent that. */ private String compress(String str) { if (str == null || str.length() == 0) { return str; } String outStr = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes(""));//() gzip.close(); outStr = out.toString("ISO-8859-1");//ISO-8859-1 } catch (Exception exc) { } return outStr; } /** * Compress a string into a byte array * @param str * @param os */ private void compressBinary(String str, OutputStream os) { try { if (str == null || str.length() == 0) { os.close(); return; } GZIPOutputStream gzip = new GZIPOutputStream(os);//out gzip.write(str.getBytes("UTF-8"));//UTF-8 gzip.flush(); gzip.close(); } catch (Exception exc) { } //return outStr; } /** * Decompress a gzip copmressed string into a regular string. * @param str * @return */ private String decompress(String str) { if (str == null || str.length() == 0) { return str; } String outStr = null; try { GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("ISO-8859-1"))); BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "ISO-8859-1")); outStr = ""; String line = null; while ((line = bf.readLine()) != null) { outStr += line; } } catch (Exception exc) { } return outStr; } private void printParamMap(Map<String, String[]> map) { String message = ""; if (map != null) { for (Map.Entry<String, String[]> entry : map.entrySet()) { String key = entry.getKey(); String[] val = entry.getValue(); message += key + " : "; for (String foo : val) { message += foo + " "; } message += "\n"; } } System.out.println(message); } /** * Given a symbol code meant for a single point symbol, returns the * anchor point at which to display that image based off the image returned * from the URL of the SinglePointServer. * @param batch like {"iconURLs":["SFGP------*****?size=35&T=Hello","SHGPE-----*****?size=50"]} * @return like {"singlepoints":[{"x":0,"y":0,"boundsx":0,"boundsy":0,"boundswidth":35,"boundsheight":35,"iconwidth":35,"iconwidth":35}, ... ]} */ public String getSinglePointInfoBatch(String batch) { String info = ""; Point2D anchor = new Point2D.Double(); Rectangle2D symbolBounds = new Rectangle2D.Double(); Dimension2D iconSize = new Dimension(); JSONObject symbolInfo = null; StringBuilder sb = new StringBuilder(); try { // must escape '=' so that JSONObject can parse string batch = batch.replaceAll("=", "%3D"); String data = null; JSONObject jsonSPString = new JSONObject(batch); JSONArray jsa = jsonSPString.getJSONArray("iconURLs"); int len = jsa.length(); sb.append("{\"singlepoints\":["); String item = null; for (int i = 0; i < len; i++) { if (i > 0) { sb.append(","); } info = jsa.get(i).toString(); info = info.replaceAll("%3D", "="); anchor = new Point2D.Double(); symbolBounds = new Rectangle2D.Double(); // System.out.println("url: " + info); PNGInfo pngInfo = SECRenderer.getInstance().getSymbolImageFromURL(info); iconSize = new Dimension(pngInfo.getImage().getWidth(), pngInfo.getImage().getHeight()); item = SECWebRenderer.SymbolDimensionsToJSON(pngInfo.getCenterPoint(), pngInfo.getSymbolBounds(), iconSize); sb.append(item); } } catch (Exception exc) { System.out.println(exc.getMessage()); exc.printStackTrace(); } finally { sb.append("]}"); } return sb.toString(); } }
apache-2.0
jc6212/Android-UTubeTV
UTubeTVProject - Eclipse/Utube/src/com/klogicapps/tv/misc/ConnectionMonitor.java
2161
package com.klogicapps.tv.misc; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import de.greenrobot.event.EventBus; public class ConnectionMonitor { Context mContext; ConnectivityManager mConnectivityManager; boolean mConnected = true; // assume we have a connection, send event if not connected public ConnectionMonitor(Context context) { mContext = context.getApplicationContext(); mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean debug = false; if (debug) { boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); DUtils.log("noConnectivity: " + (noConnectivity ? "true" : "false")); DUtils.log("reason: " + reason); DUtils.log("isFailover: " + (isFailover ? "true" : "false")); } boolean isConnected = hasNetworkConnection(); if (mConnected != isConnected) { mConnected = isConnected; EventBus.getDefault().post(new BusEvents.ConnectionChanged()); } } }; mContext.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } public boolean hasNetworkConnection() { NetworkInfo activeNetwork = mConnectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // could add this later (from dev sample) // if (isConnected) { // boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; // // Debug.log("got wifi"); // } return isConnected; } }
apache-2.0
SeekerResource/hbase
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StripeStoreFileManager.java
42384
/** * * 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.hadoop.hbase.regionserver; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.regionserver.compactions.StripeCompactionPolicy; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ConcatenatedLists; import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; /** * Stripe implementation of StoreFileManager. * Not thread safe - relies on external locking (in HStore). Collections that this class * returns are immutable or unique to the call, so they should be safe. * Stripe store splits the key space of the region into non-overlapping stripes, as well as * some recent files that have all the keys (level 0). Each stripe contains a set of files. * When L0 is compacted, it's split into the files corresponding to existing stripe boundaries, * that can thus be added to stripes. * When scan or get happens, it only has to read the files from the corresponding stripes. * See StripeCompationPolicy on how the stripes are determined; this class doesn't care. * * This class should work together with StripeCompactionPolicy and StripeCompactor. * With regard to how they work, we make at least the following (reasonable) assumptions: * - Compaction produces one file per new stripe (if any); that is easy to change. * - Compaction has one contiguous set of stripes both in and out, except if L0 is involved. */ @InterfaceAudience.Private public class StripeStoreFileManager implements StoreFileManager, StripeCompactionPolicy.StripeInformationProvider { private static final Log LOG = LogFactory.getLog(StripeStoreFileManager.class); /** * The file metadata fields that contain the stripe information. */ public static final byte[] STRIPE_START_KEY = Bytes.toBytes("STRIPE_START_KEY"); public static final byte[] STRIPE_END_KEY = Bytes.toBytes("STRIPE_END_KEY"); private final static Bytes.RowEndKeyComparator MAP_COMPARATOR = new Bytes.RowEndKeyComparator(); /** * The key value used for range boundary, indicating that the boundary is open (i.e. +-inf). */ public final static byte[] OPEN_KEY = HConstants.EMPTY_BYTE_ARRAY; final static byte[] INVALID_KEY = null; /** * The state class. Used solely to replace results atomically during * compactions and avoid complicated error handling. */ private static class State { /** * The end rows of each stripe. The last stripe end is always open-ended, so it's not stored * here. It is invariant that the start row of the stripe is the end row of the previous one * (and is an open boundary for the first one). */ public byte[][] stripeEndRows = new byte[0][]; /** * Files by stripe. Each element of the list corresponds to stripeEndRow element with the * same index, except the last one. Inside each list, the files are in reverse order by * seqNum. Note that the length of this is one higher than that of stripeEndKeys. */ public ArrayList<ImmutableList<StoreFile>> stripeFiles = new ArrayList<ImmutableList<StoreFile>>(); /** Level 0. The files are in reverse order by seqNum. */ public ImmutableList<StoreFile> level0Files = ImmutableList.<StoreFile>of(); /** Cached list of all files in the structure, to return from some calls */ public ImmutableList<StoreFile> allFilesCached = ImmutableList.<StoreFile>of(); } private State state = null; /** Cached file metadata (or overrides as the case may be) */ private HashMap<StoreFile, byte[]> fileStarts = new HashMap<StoreFile, byte[]>(); private HashMap<StoreFile, byte[]> fileEnds = new HashMap<StoreFile, byte[]>(); /** Normally invalid key is null, but in the map null is the result for "no key"; so use * the following constant value in these maps instead. Note that this is a constant and * we use it to compare by reference when we read from the map. */ private static final byte[] INVALID_KEY_IN_MAP = new byte[0]; private final CellComparator cellComparator; private StripeStoreConfig config; private final int blockingFileCount; public StripeStoreFileManager( CellComparator kvComparator, Configuration conf, StripeStoreConfig config) { this.cellComparator = kvComparator; this.config = config; this.blockingFileCount = conf.getInt( HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT); } @Override public void loadFiles(List<StoreFile> storeFiles) { loadUnclassifiedStoreFiles(storeFiles); } @Override public Collection<StoreFile> getStorefiles() { return state.allFilesCached; } @Override public void insertNewFiles(Collection<StoreFile> sfs) throws IOException { CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(true); cmc.mergeResults(null, sfs); debugDumpState("Added new files"); } @Override public ImmutableCollection<StoreFile> clearFiles() { ImmutableCollection<StoreFile> result = state.allFilesCached; this.state = new State(); this.fileStarts.clear(); this.fileEnds.clear(); return result; } @Override public int getStorefileCount() { return state.allFilesCached.size(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} * for details on this methods. */ @Override public Iterator<StoreFile> getCandidateFilesForRowKeyBefore(final KeyValue targetKey) { KeyBeforeConcatenatedLists result = new KeyBeforeConcatenatedLists(); // Order matters for this call. result.addSublist(state.level0Files); if (!state.stripeFiles.isEmpty()) { int lastStripeIndex = findStripeForRow(targetKey.getRow(), false); for (int stripeIndex = lastStripeIndex; stripeIndex >= 0; --stripeIndex) { result.addSublist(state.stripeFiles.get(stripeIndex)); } } return result.iterator(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} and * {@link StoreFileManager#updateCandidateFilesForRowKeyBefore(Iterator, KeyValue, Cell)} * for details on this methods. */ @Override public Iterator<StoreFile> updateCandidateFilesForRowKeyBefore( Iterator<StoreFile> candidateFiles, final KeyValue targetKey, final Cell candidate) { KeyBeforeConcatenatedLists.Iterator original = (KeyBeforeConcatenatedLists.Iterator)candidateFiles; assert original != null; ArrayList<List<StoreFile>> components = original.getComponents(); for (int firstIrrelevant = 0; firstIrrelevant < components.size(); ++firstIrrelevant) { StoreFile sf = components.get(firstIrrelevant).get(0); byte[] endKey = endOf(sf); // Entries are ordered as such: L0, then stripes in reverse order. We never remove // level 0; we remove the stripe, and all subsequent ones, as soon as we find the // first one that cannot possibly have better candidates. if (!isInvalid(endKey) && !isOpen(endKey) && (nonOpenRowCompare(endKey, targetKey.getRow()) <= 0)) { original.removeComponents(firstIrrelevant); break; } } return original; } @Override /** * Override of getSplitPoint that determines the split point as the boundary between two * stripes, unless it causes significant imbalance between split sides' sizes. In that * case, the split boundary will be chosen from the middle of one of the stripes to * minimize imbalance. * @return The split point, or null if no split is possible. */ public byte[] getSplitPoint() throws IOException { if (this.getStorefileCount() == 0) return null; if (state.stripeFiles.size() <= 1) { return getSplitPointFromAllFiles(); } int leftIndex = -1, rightIndex = state.stripeFiles.size(); long leftSize = 0, rightSize = 0; long lastLeftSize = 0, lastRightSize = 0; while (rightIndex - 1 != leftIndex) { if (leftSize >= rightSize) { --rightIndex; lastRightSize = getStripeFilesSize(rightIndex); rightSize += lastRightSize; } else { ++leftIndex; lastLeftSize = getStripeFilesSize(leftIndex); leftSize += lastLeftSize; } } if (leftSize == 0 || rightSize == 0) { String errMsg = String.format("Cannot split on a boundary - left index %d size %d, " + "right index %d size %d", leftIndex, leftSize, rightIndex, rightSize); debugDumpState(errMsg); LOG.warn(errMsg); return getSplitPointFromAllFiles(); } double ratio = (double)rightSize / leftSize; if (ratio < 1) { ratio = 1 / ratio; } if (config.getMaxSplitImbalance() > ratio) return state.stripeEndRows[leftIndex]; // If the difference between the sides is too large, we could get the proportional key on // the a stripe to equalize the difference, but there's no proportional key method at the // moment, and it's not extremely important. // See if we can achieve better ratio if we split the bigger side in half. boolean isRightLarger = rightSize >= leftSize; double newRatio = isRightLarger ? getMidStripeSplitRatio(leftSize, rightSize, lastRightSize) : getMidStripeSplitRatio(rightSize, leftSize, lastLeftSize); if (newRatio < 1) { newRatio = 1 / newRatio; } if (newRatio >= ratio) return state.stripeEndRows[leftIndex]; LOG.debug("Splitting the stripe - ratio w/o split " + ratio + ", ratio with split " + newRatio + " configured ratio " + config.getMaxSplitImbalance()); // Ok, we may get better ratio, get it. return StoreUtils.getLargestFile(state.stripeFiles.get( isRightLarger ? rightIndex : leftIndex)).getFileSplitPoint(this.cellComparator); } private byte[] getSplitPointFromAllFiles() throws IOException { ConcatenatedLists<StoreFile> sfs = new ConcatenatedLists<StoreFile>(); sfs.addSublist(state.level0Files); sfs.addAllSublists(state.stripeFiles); if (sfs.isEmpty()) return null; return StoreUtils.getLargestFile(sfs).getFileSplitPoint(this.cellComparator); } private double getMidStripeSplitRatio(long smallerSize, long largerSize, long lastLargerSize) { return (double)(largerSize - lastLargerSize / 2f) / (smallerSize + lastLargerSize / 2f); } @Override public Collection<StoreFile> getFilesForScanOrGet( boolean isGet, byte[] startRow, byte[] stopRow) { if (state.stripeFiles.isEmpty()) { return state.level0Files; // There's just L0. } int firstStripe = findStripeForRow(startRow, true); int lastStripe = findStripeForRow(stopRow, false); assert firstStripe <= lastStripe; if (firstStripe == lastStripe && state.level0Files.isEmpty()) { return state.stripeFiles.get(firstStripe); // There's just one stripe we need. } if (firstStripe == 0 && lastStripe == (state.stripeFiles.size() - 1)) { return state.allFilesCached; // We need to read all files. } ConcatenatedLists<StoreFile> result = new ConcatenatedLists<StoreFile>(); result.addAllSublists(state.stripeFiles.subList(firstStripe, lastStripe + 1)); result.addSublist(state.level0Files); return result; } @Override public void addCompactionResults( Collection<StoreFile> compactedFiles, Collection<StoreFile> results) throws IOException { // See class comment for the assumptions we make here. LOG.debug("Attempting to merge compaction results: " + compactedFiles.size() + " files replaced by " + results.size()); // In order to be able to fail in the middle of the operation, we'll operate on lazy // copies and apply the result at the end. CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(false); cmc.mergeResults(compactedFiles, results); debugDumpState("Merged compaction results"); } @Override public int getStoreCompactionPriority() { // If there's only L0, do what the default store does. // If we are in critical priority, do the same - we don't want to trump all stores all // the time due to how many files we have. int fc = getStorefileCount(); if (state.stripeFiles.isEmpty() || (this.blockingFileCount <= fc)) { return this.blockingFileCount - fc; } // If we are in good shape, we don't want to be trumped by all other stores due to how // many files we have, so do an approximate mapping to normal priority range; L0 counts // for all stripes. int l0 = state.level0Files.size(), sc = state.stripeFiles.size(); int priority = (int)Math.ceil(((double)(this.blockingFileCount - fc + l0) / sc) - l0); return (priority <= HStore.PRIORITY_USER) ? (HStore.PRIORITY_USER + 1) : priority; } /** * Gets the total size of all files in the stripe. * @param stripeIndex Stripe index. * @return Size. */ private long getStripeFilesSize(int stripeIndex) { long result = 0; for (StoreFile sf : state.stripeFiles.get(stripeIndex)) { result += sf.getReader().length(); } return result; } /** * Loads initial store files that were picked up from some physical location pertaining to * this store (presumably). Unlike adding files after compaction, assumes empty initial * sets, and is forgiving with regard to stripe constraints - at worst, many/all files will * go to level 0. * @param storeFiles Store files to add. */ private void loadUnclassifiedStoreFiles(List<StoreFile> storeFiles) { LOG.debug("Attempting to load " + storeFiles.size() + " store files."); TreeMap<byte[], ArrayList<StoreFile>> candidateStripes = new TreeMap<byte[], ArrayList<StoreFile>>(MAP_COMPARATOR); ArrayList<StoreFile> level0Files = new ArrayList<StoreFile>(); // Separate the files into tentative stripes; then validate. Currently, we rely on metadata. // If needed, we could dynamically determine the stripes in future. for (StoreFile sf : storeFiles) { byte[] startRow = startOf(sf), endRow = endOf(sf); // Validate the range and put the files into place. if (isInvalid(startRow) || isInvalid(endRow)) { insertFileIntoStripe(level0Files, sf); // No metadata - goes to L0. ensureLevel0Metadata(sf); } else if (!isOpen(startRow) && !isOpen(endRow) && nonOpenRowCompare(startRow, endRow) >= 0) { LOG.error("Unexpected metadata - start row [" + Bytes.toString(startRow) + "], end row [" + Bytes.toString(endRow) + "] in file [" + sf.getPath() + "], pushing to L0"); insertFileIntoStripe(level0Files, sf); // Bad metadata - goes to L0 also. ensureLevel0Metadata(sf); } else { ArrayList<StoreFile> stripe = candidateStripes.get(endRow); if (stripe == null) { stripe = new ArrayList<StoreFile>(); candidateStripes.put(endRow, stripe); } insertFileIntoStripe(stripe, sf); } } // Possible improvement - for variable-count stripes, if all the files are in L0, we can // instead create single, open-ended stripe with all files. boolean hasOverlaps = false; byte[] expectedStartRow = null; // first stripe can start wherever Iterator<Map.Entry<byte[], ArrayList<StoreFile>>> entryIter = candidateStripes.entrySet().iterator(); while (entryIter.hasNext()) { Map.Entry<byte[], ArrayList<StoreFile>> entry = entryIter.next(); ArrayList<StoreFile> files = entry.getValue(); // Validate the file start rows, and remove the bad ones to level 0. for (int i = 0; i < files.size(); ++i) { StoreFile sf = files.get(i); byte[] startRow = startOf(sf); if (expectedStartRow == null) { expectedStartRow = startRow; // ensure that first stripe is still consistent } else if (!rowEquals(expectedStartRow, startRow)) { hasOverlaps = true; LOG.warn("Store file doesn't fit into the tentative stripes - expected to start at [" + Bytes.toString(expectedStartRow) + "], but starts at [" + Bytes.toString(startRow) + "], to L0 it goes"); StoreFile badSf = files.remove(i); insertFileIntoStripe(level0Files, badSf); ensureLevel0Metadata(badSf); --i; } } // Check if any files from the candidate stripe are valid. If so, add a stripe. byte[] endRow = entry.getKey(); if (!files.isEmpty()) { expectedStartRow = endRow; // Next stripe must start exactly at that key. } else { entryIter.remove(); } } // In the end, there must be open ends on two sides. If not, and there were no errors i.e. // files are consistent, they might be coming from a split. We will treat the boundaries // as open keys anyway, and log the message. // If there were errors, we'll play it safe and dump everything into L0. if (!candidateStripes.isEmpty()) { StoreFile firstFile = candidateStripes.firstEntry().getValue().get(0); boolean isOpen = isOpen(startOf(firstFile)) && isOpen(candidateStripes.lastKey()); if (!isOpen) { LOG.warn("The range of the loaded files does not cover full key space: from [" + Bytes.toString(startOf(firstFile)) + "], to [" + Bytes.toString(candidateStripes.lastKey()) + "]"); if (!hasOverlaps) { ensureEdgeStripeMetadata(candidateStripes.firstEntry().getValue(), true); ensureEdgeStripeMetadata(candidateStripes.lastEntry().getValue(), false); } else { LOG.warn("Inconsistent files, everything goes to L0."); for (ArrayList<StoreFile> files : candidateStripes.values()) { for (StoreFile sf : files) { insertFileIntoStripe(level0Files, sf); ensureLevel0Metadata(sf); } } candidateStripes.clear(); } } } // Copy the results into the fields. State state = new State(); state.level0Files = ImmutableList.copyOf(level0Files); state.stripeFiles = new ArrayList<ImmutableList<StoreFile>>(candidateStripes.size()); state.stripeEndRows = new byte[Math.max(0, candidateStripes.size() - 1)][]; ArrayList<StoreFile> newAllFiles = new ArrayList<StoreFile>(level0Files); int i = candidateStripes.size() - 1; for (Map.Entry<byte[], ArrayList<StoreFile>> entry : candidateStripes.entrySet()) { state.stripeFiles.add(ImmutableList.copyOf(entry.getValue())); newAllFiles.addAll(entry.getValue()); if (i > 0) { state.stripeEndRows[state.stripeFiles.size() - 1] = entry.getKey(); } --i; } state.allFilesCached = ImmutableList.copyOf(newAllFiles); this.state = state; debugDumpState("Files loaded"); } private void ensureEdgeStripeMetadata(ArrayList<StoreFile> stripe, boolean isFirst) { HashMap<StoreFile, byte[]> targetMap = isFirst ? fileStarts : fileEnds; for (StoreFile sf : stripe) { targetMap.put(sf, OPEN_KEY); } } private void ensureLevel0Metadata(StoreFile sf) { if (!isInvalid(startOf(sf))) this.fileStarts.put(sf, INVALID_KEY_IN_MAP); if (!isInvalid(endOf(sf))) this.fileEnds.put(sf, INVALID_KEY_IN_MAP); } private void debugDumpState(String string) { if (!LOG.isDebugEnabled()) return; StringBuilder sb = new StringBuilder(); sb.append("\n" + string + "; current stripe state is as such:"); sb.append("\n level 0 with ") .append(state.level0Files.size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.level0Files), "", 1) + ";"); for (int i = 0; i < state.stripeFiles.size(); ++i) { String endRow = (i == state.stripeEndRows.length) ? "(end)" : "[" + Bytes.toString(state.stripeEndRows[i]) + "]"; sb.append("\n stripe ending in ") .append(endRow) .append(" with ") .append(state.stripeFiles.get(i).size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.stripeFiles.get(i)), "", 1) + ";"); } sb.append("\n").append(state.stripeFiles.size()).append(" stripes total."); sb.append("\n").append(getStorefileCount()).append(" files total."); LOG.debug(sb.toString()); } /** * Checks whether the key indicates an open interval boundary (i.e. infinity). */ private static final boolean isOpen(byte[] key) { return key != null && key.length == 0; } /** * Checks whether the key is invalid (e.g. from an L0 file, or non-stripe-compacted files). */ private static final boolean isInvalid(byte[] key) { // No need to use Arrays.equals because INVALID_KEY is null return key == INVALID_KEY; } /** * Compare two keys for equality. */ private final boolean rowEquals(byte[] k1, byte[] k2) { return Bytes.equals(k1, 0, k1.length, k2, 0, k2.length); } /** * Compare two keys. Keys must not be open (isOpen(row) == false). */ private final int nonOpenRowCompare(byte[] k1, byte[] k2) { assert !isOpen(k1) && !isOpen(k2); return cellComparator.compareRows(k1, 0, k1.length, k2, 0, k2.length); } /** * Finds the stripe index by end row. */ private final int findStripeIndexByEndRow(byte[] endRow) { assert !isInvalid(endRow); if (isOpen(endRow)) return state.stripeEndRows.length; return Arrays.binarySearch(state.stripeEndRows, endRow, Bytes.BYTES_COMPARATOR); } /** * Finds the stripe index for the stripe containing a row provided externally for get/scan. */ private final int findStripeForRow(byte[] row, boolean isStart) { if (isStart && Arrays.equals(row, HConstants.EMPTY_START_ROW)) return 0; if (!isStart && Arrays.equals(row, HConstants.EMPTY_END_ROW)) { return state.stripeFiles.size() - 1; } // If there's an exact match below, a stripe ends at "row". Stripe right boundary is // exclusive, so that means the row is in the next stripe; thus, we need to add one to index. // If there's no match, the return value of binarySearch is (-(insertion point) - 1), where // insertion point is the index of the next greater element, or list size if none. The // insertion point happens to be exactly what we need, so we need to add one to the result. return Math.abs(Arrays.binarySearch(state.stripeEndRows, row, Bytes.BYTES_COMPARATOR) + 1); } @Override public final byte[] getStartRow(int stripeIndex) { return (stripeIndex == 0 ? OPEN_KEY : state.stripeEndRows[stripeIndex - 1]); } @Override public final byte[] getEndRow(int stripeIndex) { return (stripeIndex == state.stripeEndRows.length ? OPEN_KEY : state.stripeEndRows[stripeIndex]); } private byte[] startOf(StoreFile sf) { byte[] result = fileStarts.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_START_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } private byte[] endOf(StoreFile sf) { byte[] result = fileEnds.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_END_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } /** * Inserts a file in the correct place (by seqnum) in a stripe copy. * @param stripe Stripe copy to insert into. * @param sf File to insert. */ private static void insertFileIntoStripe(ArrayList<StoreFile> stripe, StoreFile sf) { // The only operation for which sorting of the files matters is KeyBefore. Therefore, // we will store the file in reverse order by seqNum from the outset. for (int insertBefore = 0; ; ++insertBefore) { if (insertBefore == stripe.size() || (StoreFile.Comparators.SEQ_ID.compare(sf, stripe.get(insertBefore)) >= 0)) { stripe.add(insertBefore, sf); break; } } } /** * An extension of ConcatenatedLists that has several peculiar properties. * First, one can cut the tail of the logical list by removing last several sub-lists. * Second, items can be removed thru iterator. * Third, if the sub-lists are immutable, they are replaced with mutable copies when needed. * On average KeyBefore operation will contain half the stripes as potential candidates, * but will quickly cut down on them as it finds something in the more likely ones; thus, * the above allow us to avoid unnecessary copying of a bunch of lists. */ private static class KeyBeforeConcatenatedLists extends ConcatenatedLists<StoreFile> { @Override public java.util.Iterator<StoreFile> iterator() { return new Iterator(); } public class Iterator extends ConcatenatedLists<StoreFile>.Iterator { public ArrayList<List<StoreFile>> getComponents() { return components; } public void removeComponents(int startIndex) { List<List<StoreFile>> subList = components.subList(startIndex, components.size()); for (List<StoreFile> entry : subList) { size -= entry.size(); } assert size >= 0; subList.clear(); } @Override public void remove() { if (!this.nextWasCalled) { throw new IllegalStateException("No element to remove"); } this.nextWasCalled = false; List<StoreFile> src = components.get(currentComponent); if (src instanceof ImmutableList<?>) { src = new ArrayList<StoreFile>(src); components.set(currentComponent, src); } src.remove(indexWithinComponent); --size; --indexWithinComponent; if (src.isEmpty()) { components.remove(currentComponent); // indexWithinComponent is already -1 here. } } } } /** * Non-static helper class for merging compaction or flush results. * Since we want to merge them atomically (more or less), it operates on lazy copies, * then creates a new state object and puts it in place. */ private class CompactionOrFlushMergeCopy { private ArrayList<List<StoreFile>> stripeFiles = null; private ArrayList<StoreFile> level0Files = null; private ArrayList<byte[]> stripeEndRows = null; private Collection<StoreFile> compactedFiles = null; private Collection<StoreFile> results = null; private List<StoreFile> l0Results = new ArrayList<StoreFile>(); private final boolean isFlush; public CompactionOrFlushMergeCopy(boolean isFlush) { // Create a lazy mutable copy (other fields are so lazy they start out as nulls). this.stripeFiles = new ArrayList<List<StoreFile>>( StripeStoreFileManager.this.state.stripeFiles); this.isFlush = isFlush; } public void mergeResults(Collection<StoreFile> compactedFiles, Collection<StoreFile> results) throws IOException { assert this.compactedFiles == null && this.results == null; this.compactedFiles = compactedFiles; this.results = results; // Do logical processing. if (!isFlush) removeCompactedFiles(); TreeMap<byte[], StoreFile> newStripes = processResults(); if (newStripes != null) { processNewCandidateStripes(newStripes); } // Create new state and update parent. State state = createNewState(); StripeStoreFileManager.this.state = state; updateMetadataMaps(); } private State createNewState() { State oldState = StripeStoreFileManager.this.state; // Stripe count should be the same unless the end rows changed. assert oldState.stripeFiles.size() == this.stripeFiles.size() || this.stripeEndRows != null; State newState = new State(); newState.level0Files = (this.level0Files == null) ? oldState.level0Files : ImmutableList.copyOf(this.level0Files); newState.stripeEndRows = (this.stripeEndRows == null) ? oldState.stripeEndRows : this.stripeEndRows.toArray(new byte[this.stripeEndRows.size()][]); newState.stripeFiles = new ArrayList<ImmutableList<StoreFile>>(this.stripeFiles.size()); for (List<StoreFile> newStripe : this.stripeFiles) { newState.stripeFiles.add(newStripe instanceof ImmutableList<?> ? (ImmutableList<StoreFile>)newStripe : ImmutableList.copyOf(newStripe)); } List<StoreFile> newAllFiles = new ArrayList<StoreFile>(oldState.allFilesCached); if (!isFlush) newAllFiles.removeAll(compactedFiles); newAllFiles.addAll(results); newState.allFilesCached = ImmutableList.copyOf(newAllFiles); return newState; } private void updateMetadataMaps() { StripeStoreFileManager parent = StripeStoreFileManager.this; if (!isFlush) { for (StoreFile sf : this.compactedFiles) { parent.fileStarts.remove(sf); parent.fileEnds.remove(sf); } } if (this.l0Results != null) { for (StoreFile sf : this.l0Results) { parent.ensureLevel0Metadata(sf); } } } /** * @param index Index of the stripe we need. * @return A lazy stripe copy from current stripes. */ private final ArrayList<StoreFile> getStripeCopy(int index) { List<StoreFile> stripeCopy = this.stripeFiles.get(index); ArrayList<StoreFile> result = null; if (stripeCopy instanceof ImmutableList<?>) { result = new ArrayList<StoreFile>(stripeCopy); this.stripeFiles.set(index, result); } else { result = (ArrayList<StoreFile>)stripeCopy; } return result; } /** * @return A lazy L0 copy from current state. */ private final ArrayList<StoreFile> getLevel0Copy() { if (this.level0Files == null) { this.level0Files = new ArrayList<StoreFile>(StripeStoreFileManager.this.state.level0Files); } return this.level0Files; } /** * Process new files, and add them either to the structure of existing stripes, * or to the list of new candidate stripes. * @return New candidate stripes. */ private TreeMap<byte[], StoreFile> processResults() throws IOException { TreeMap<byte[], StoreFile> newStripes = null; for (StoreFile sf : this.results) { byte[] startRow = startOf(sf), endRow = endOf(sf); if (isInvalid(endRow) || isInvalid(startRow)) { if (!isFlush) { LOG.warn("The newly compacted file doesn't have stripes set: " + sf.getPath()); } insertFileIntoStripe(getLevel0Copy(), sf); this.l0Results.add(sf); continue; } if (!this.stripeFiles.isEmpty()) { int stripeIndex = findStripeIndexByEndRow(endRow); if ((stripeIndex >= 0) && rowEquals(getStartRow(stripeIndex), startRow)) { // Simple/common case - add file to an existing stripe. insertFileIntoStripe(getStripeCopy(stripeIndex), sf); continue; } } // Make a new candidate stripe. if (newStripes == null) { newStripes = new TreeMap<byte[], StoreFile>(MAP_COMPARATOR); } StoreFile oldSf = newStripes.put(endRow, sf); if (oldSf != null) { throw new IOException("Compactor has produced multiple files for the stripe ending in [" + Bytes.toString(endRow) + "], found " + sf.getPath() + " and " + oldSf.getPath()); } } return newStripes; } /** * Remove compacted files. * @param compactedFiles Compacted files. */ private void removeCompactedFiles() throws IOException { for (StoreFile oldFile : this.compactedFiles) { byte[] oldEndRow = endOf(oldFile); List<StoreFile> source = null; if (isInvalid(oldEndRow)) { source = getLevel0Copy(); } else { int stripeIndex = findStripeIndexByEndRow(oldEndRow); if (stripeIndex < 0) { throw new IOException("An allegedly compacted file [" + oldFile + "] does not belong" + " to a known stripe (end row - [" + Bytes.toString(oldEndRow) + "])"); } source = getStripeCopy(stripeIndex); } if (!source.remove(oldFile)) { throw new IOException("An allegedly compacted file [" + oldFile + "] was not found"); } } } /** * See {@link #addCompactionResults(Collection, Collection)} - updates the stripe list with * new candidate stripes/removes old stripes; produces new set of stripe end rows. * @param newStripes New stripes - files by end row. */ private void processNewCandidateStripes( TreeMap<byte[], StoreFile> newStripes) throws IOException { // Validate that the removed and added aggregate ranges still make for a full key space. boolean hasStripes = !this.stripeFiles.isEmpty(); this.stripeEndRows = new ArrayList<byte[]>( Arrays.asList(StripeStoreFileManager.this.state.stripeEndRows)); int removeFrom = 0; byte[] firstStartRow = startOf(newStripes.firstEntry().getValue()); byte[] lastEndRow = newStripes.lastKey(); if (!hasStripes && (!isOpen(firstStartRow) || !isOpen(lastEndRow))) { throw new IOException("Newly created stripes do not cover the entire key space."); } boolean canAddNewStripes = true; Collection<StoreFile> filesForL0 = null; if (hasStripes) { // Determine which stripes will need to be removed because they conflict with new stripes. // The new boundaries should match old stripe boundaries, so we should get exact matches. if (isOpen(firstStartRow)) { removeFrom = 0; } else { removeFrom = findStripeIndexByEndRow(firstStartRow); if (removeFrom < 0) throw new IOException("Compaction is trying to add a bad range."); ++removeFrom; } int removeTo = findStripeIndexByEndRow(lastEndRow); if (removeTo < 0) throw new IOException("Compaction is trying to add a bad range."); // See if there are files in the stripes we are trying to replace. ArrayList<StoreFile> conflictingFiles = new ArrayList<StoreFile>(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { conflictingFiles.addAll(this.stripeFiles.get(removeIndex)); } if (!conflictingFiles.isEmpty()) { // This can be caused by two things - concurrent flush into stripes, or a bug. // Unfortunately, we cannot tell them apart without looking at timing or something // like that. We will assume we are dealing with a flush and dump it into L0. if (isFlush) { long newSize = StripeCompactionPolicy.getTotalFileSize(newStripes.values()); LOG.warn("Stripes were created by a flush, but results of size " + newSize + " cannot be added because the stripes have changed"); canAddNewStripes = false; filesForL0 = newStripes.values(); } else { long oldSize = StripeCompactionPolicy.getTotalFileSize(conflictingFiles); LOG.info(conflictingFiles.size() + " conflicting files (likely created by a flush) " + " of size " + oldSize + " are moved to L0 due to concurrent stripe change"); filesForL0 = conflictingFiles; } if (filesForL0 != null) { for (StoreFile sf : filesForL0) { insertFileIntoStripe(getLevel0Copy(), sf); } l0Results.addAll(filesForL0); } } if (canAddNewStripes) { // Remove old empty stripes. int originalCount = this.stripeFiles.size(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { if (removeIndex != originalCount - 1) { this.stripeEndRows.remove(removeIndex); } this.stripeFiles.remove(removeIndex); } } } if (!canAddNewStripes) return; // Files were already put into L0. // Now, insert new stripes. The total ranges match, so we can insert where we removed. byte[] previousEndRow = null; int insertAt = removeFrom; for (Map.Entry<byte[], StoreFile> newStripe : newStripes.entrySet()) { if (previousEndRow != null) { // Validate that the ranges are contiguous. assert !isOpen(previousEndRow); byte[] startRow = startOf(newStripe.getValue()); if (!rowEquals(previousEndRow, startRow)) { throw new IOException("The new stripes produced by " + (isFlush ? "flush" : "compaction") + " are not contiguous"); } } // Add the new stripe. ArrayList<StoreFile> tmp = new ArrayList<StoreFile>(); tmp.add(newStripe.getValue()); stripeFiles.add(insertAt, tmp); previousEndRow = newStripe.getKey(); if (!isOpen(previousEndRow)) { stripeEndRows.add(insertAt, previousEndRow); } ++insertAt; } } } @Override public List<StoreFile> getLevel0Files() { return this.state.level0Files; } @Override public List<byte[]> getStripeBoundaries() { if (this.state.stripeFiles.isEmpty()) return new ArrayList<byte[]>(); ArrayList<byte[]> result = new ArrayList<byte[]>(this.state.stripeEndRows.length + 2); result.add(OPEN_KEY); Collections.addAll(result, this.state.stripeEndRows); result.add(OPEN_KEY); return result; } @Override public ArrayList<ImmutableList<StoreFile>> getStripes() { return this.state.stripeFiles; } @Override public int getStripeCount() { return this.state.stripeFiles.size(); } @Override public Collection<StoreFile> getUnneededFiles(long maxTs, List<StoreFile> filesCompacting) { // 1) We can never get rid of the last file which has the maximum seqid in a stripe. // 2) Files that are not the latest can't become one due to (1), so the rest are fair game. State state = this.state; Collection<StoreFile> expiredStoreFiles = null; for (ImmutableList<StoreFile> stripe : state.stripeFiles) { expiredStoreFiles = findExpiredFiles(stripe, maxTs, filesCompacting, expiredStoreFiles); } return findExpiredFiles(state.level0Files, maxTs, filesCompacting, expiredStoreFiles); } private Collection<StoreFile> findExpiredFiles(ImmutableList<StoreFile> stripe, long maxTs, List<StoreFile> filesCompacting, Collection<StoreFile> expiredStoreFiles) { // Order by seqnum is reversed. for (int i = 1; i < stripe.size(); ++i) { StoreFile sf = stripe.get(i); long fileTs = sf.getReader().getMaxTimestamp(); if (fileTs < maxTs && !filesCompacting.contains(sf)) { LOG.info("Found an expired store file: " + sf.getPath() + " whose maxTimeStamp is " + fileTs + ", which is below " + maxTs); if (expiredStoreFiles == null) { expiredStoreFiles = new ArrayList<StoreFile>(); } expiredStoreFiles.add(sf); } } return expiredStoreFiles; } @Override public double getCompactionPressure() { State stateLocal = this.state; if (stateLocal.allFilesCached.size() > blockingFileCount) { // just a hit to tell others that we have reached the blocking file count. return 2.0; } if (stateLocal.stripeFiles.isEmpty()) { return 0.0; } int blockingFilePerStripe = blockingFileCount / stateLocal.stripeFiles.size(); // do not calculate L0 separately because data will be moved to stripe quickly and in most cases // we flush data to stripe directly. int delta = stateLocal.level0Files.isEmpty() ? 0 : 1; double max = 0.0; for (ImmutableList<StoreFile> stripeFile : stateLocal.stripeFiles) { int stripeFileCount = stripeFile.size(); double normCount = (double) (stripeFileCount + delta - config.getStripeCompactMinFiles()) / (blockingFilePerStripe - config.getStripeCompactMinFiles()); if (normCount >= 1.0) { // This could happen if stripe is not split evenly. Do not return values that larger than // 1.0 because we have not reached the blocking file count actually. return 1.0; } if (normCount > max) { max = normCount; } } return max; } }
apache-2.0
agentmilindu/stratos
components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41.java
85517
/* * 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.stratos.rest.endpoint.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.autoscaler.stub.*; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidKubernetesClusterExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceKubernetesClusterAlreadyExistsExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceNetworkPartitionAlreadyExistsExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceNetworkPartitionNotExistsExceptionException; import org.apache.stratos.common.beans.*; import org.apache.stratos.common.beans.application.ApplicationBean; import org.apache.stratos.common.beans.application.ApplicationNetworkPartitionIdListBean; import org.apache.stratos.common.beans.application.GroupBean; import org.apache.stratos.common.beans.application.domain.mapping.ApplicationDomainMappingsBean; import org.apache.stratos.common.beans.application.domain.mapping.DomainMappingBean; import org.apache.stratos.common.beans.application.signup.ApplicationSignUpBean; import org.apache.stratos.common.beans.artifact.repository.GitNotificationPayloadBean; import org.apache.stratos.common.beans.cartridge.CartridgeBean; import org.apache.stratos.common.beans.kubernetes.KubernetesClusterBean; import org.apache.stratos.common.beans.kubernetes.KubernetesHostBean; import org.apache.stratos.common.beans.kubernetes.KubernetesMasterBean; import org.apache.stratos.common.beans.partition.NetworkPartitionBean; import org.apache.stratos.common.beans.policy.autoscale.AutoscalePolicyBean; import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean; import org.apache.stratos.common.beans.policy.deployment.DeploymentPolicyBean; import org.apache.stratos.common.beans.topology.ApplicationInfoBean; import org.apache.stratos.common.beans.topology.ClusterBean; import org.apache.stratos.common.exception.InvalidEmailException; import org.apache.stratos.manager.service.stub.StratosManagerServiceApplicationSignUpExceptionException; import org.apache.stratos.manager.service.stub.StratosManagerServiceDomainMappingExceptionException; import org.apache.stratos.rest.endpoint.Utils; import org.apache.stratos.rest.endpoint.annotation.AuthorizationAction; import org.apache.stratos.rest.endpoint.annotation.SuperTenantService; import org.apache.stratos.rest.endpoint.exception.*; import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Stratos API v4.1 for Stratos 4.1.0 release. */ @Path("/") public class StratosApiV41 extends AbstractApi { private static Log log = LogFactory.getLog(StratosApiV41.class); @Context HttpServletRequest httpServletRequest; @Context UriInfo uriInfo; /** * This method is used by clients such as the CLI to verify the Stratos manager URL. * * @return the response * @throws RestAPIException the rest api exception */ @GET @Path("/init") @AuthorizationAction("/permission/admin/restlogin") public Response initialize() throws RestAPIException { ApiResponseBean response = new ApiResponseBean(); response.setMessage("Successfully authenticated"); return Response.ok(response).build(); } /** * This method gets called by the client who are interested in using session mechanism to authenticate * themselves in subsequent calls. This method call get authenticated by the basic authenticator. * Once the authenticated call received, the method creates a session and returns the session id. * * @return The session id related with the session */ @GET @Path("/session") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/restlogin") public Response getSession() { HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); httpSession.setAttribute("userName", carbonContext.getUsername()); httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain()); httpSession.setAttribute("tenantId", carbonContext.getTenantId()); String sessionId = httpSession.getId(); return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON). entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build(); } /** * Creates the cartridge definition. * * @param cartridgeDefinitionBean the cartridge definition bean * @return 201 if cartridge is successfully created, 409 if cartridge already exists. * @throws RestAPIException the rest api exception */ @POST @Path("/cartridges") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addCartridge") public Response addCartridge( CartridgeBean cartridgeDefinitionBean) throws RestAPIException { String cartridgeType = cartridgeDefinitionBean.getType(); CartridgeBean cartridgeBean = StratosApiV41Utils.getCartridgeForValidate(cartridgeType); if (cartridgeBean != null) { String msg = String.format("Cartridge already exists: [cartridge-type] %s", cartridgeType); log.warn(msg); return Response.status(Response.Status.CONFLICT) .entity(new ErrorResponseBean(Response.Status.CONFLICT.getStatusCode(), msg)).build(); } StratosApiV41Utils.addCartridge(cartridgeDefinitionBean); URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeType).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Cartridge added successfully: [cartridge-type] %s", cartridgeType))).build(); } /** * Creates the Deployment Policy Definition. * * @param deploymentPolicyDefinitionBean the deployment policy bean * @return 201 if deployment policy is successfully added * @throws RestAPIException the rest api exception */ @POST @Path("/deploymentPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addDeploymentPolicy") public Response addDeploymentPolicy( DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException { String deploymentPolicyID = deploymentPolicyDefinitionBean.getId(); try { // TODO :: Deployment policy validation StratosApiV41Utils.addDeploymentPolicy(deploymentPolicyDefinitionBean); } catch (RestAPIException e) { throw e; } catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } catch (AutoscalerServiceDeploymentPolicyAlreadyExistsExceptionException e) { return Response.status(Response.Status.CONFLICT).build(); } URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Deployment policy added successfully: " + "[deployment-policy-id] %s", deploymentPolicyID))).build(); } /** * Get deployment policy by deployment policy id * * @return 200 if deployment policy is found, 404 if not * @throws RestAPIException */ @GET @Path("/deploymentPolicies/{deploymentPolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getDeploymentPolicy") public Response getDeploymentPolicy( @PathParam("deploymentPolicyId") String deploymentPolicyId) throws RestAPIException { DeploymentPolicyBean deploymentPolicyBean = StratosApiV41Utils.getDeployementPolicy(deploymentPolicyId); if (deploymentPolicyBean == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(deploymentPolicyBean).build(); } /** * Get deployment policies * * @return 200 with the list of deployment policies * @throws RestAPIException */ @GET @Path("/deploymentPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getDeploymentPolicy") public Response getDeploymentPolicies() throws RestAPIException { DeploymentPolicyBean[] deploymentPolicies = StratosApiV41Utils.getDeployementPolicies(); if (deploymentPolicies == null || deploymentPolicies.length == 0) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(deploymentPolicies).build(); } /** * Updates the Deployment Policy Definition. * * @param deploymentPolicyDefinitionBean the deployment policy bean * @return 200 if deployment policy is successfully updated * @throws RestAPIException the rest api exception */ @PUT @Path("/deploymentPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateDeploymentPolicy") public Response updateDeploymentPolicy( DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException { String deploymentPolicyID = deploymentPolicyDefinitionBean.getId(); // TODO :: Deployment policy validation try { StratosApiV41Utils.updateDeploymentPolicy(deploymentPolicyDefinitionBean); } catch (AutoscalerServiceInvalidPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) { return Response.status(Response.Status.NOT_FOUND).build(); } catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) { return Response.status(Response.Status.NOT_FOUND).build(); } URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build(); return Response.ok(url).entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Deployment policy updated successfully: " + "[deployment-policy-id] %s", deploymentPolicyID))).build(); } /** * Updates the Deployment Policy Definition. * * @param deploymentPolicyID the deployment policy id * @return 200 if deployment policy is successfully removed * @throws RestAPIException the rest api exception */ @DELETE @Path("/deploymentPolicies/{depolymentPolicyID}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeDeploymentPolicy") public Response removeDeploymentPolicy( @PathParam("depolymentPolicyID") String deploymentPolicyID) throws RestAPIException { try { StratosApiV41Utils.removeDeploymentPolicy(deploymentPolicyID); } catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) { return Response.status(Response.Status.NOT_FOUND).build(); } URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build(); return Response.ok(url).entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Deployment policy removed successfully: " + "[deployment-policy-id] %s", deploymentPolicyID))).build(); } /** * Updates the cartridge definition. * * @param cartridgeDefinitionBean the cartridge definition bean * @return 201 if cartridge successfully updated * @throws RestAPIException the rest api exception */ @PUT @Path("/cartridges") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateCartridge") public Response updateCartridge( CartridgeBean cartridgeDefinitionBean) throws RestAPIException { StratosApiV41Utils.updateCartridge(cartridgeDefinitionBean); URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeDefinitionBean.getType()).build(); return Response.ok(url) .entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), "Cartridge updated successfully")) .build(); } /** * Gets all available cartridges. * * @return 200 if cartridges exists, 404 if no cartridges found * @throws RestAPIException the rest api exception */ @GET @Path("/cartridges") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getCartridge") public Response getCartridges() throws RestAPIException { List<CartridgeBean> cartridges = StratosApiV41Utils.getAvailableCartridges(null, null, getConfigContext()); if (cartridges == null || cartridges.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).build(); } CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]); return Response.ok().entity(cartridgeArray).build(); } /** * Gets a single cartridge by type * * @param cartridgeType Cartridge type * @return 200 if specified cartridge exists, 404 if not * @throws RestAPIException */ @GET @Path("/cartridges/{cartridgeType}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getCartridge") public Response getCartridge( @PathParam("cartridgeType") String cartridgeType) throws RestAPIException { CartridgeBean cartridge; try { cartridge = StratosApiV41Utils.getCartridge(cartridgeType); return Response.ok().entity(cartridge).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).build(); } } /** * Returns cartridges by category. * * @param filter Filter * @param criteria Criteria * @return 200 if cartridges are found for specified filter, 404 if none found * @throws RestAPIException */ @GET @Path("/cartridges/filter/{filter}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getCartridgesByFilter") public Response getCartridgesByFilter( @DefaultValue("") @PathParam("filter") String filter, @QueryParam("criteria") String criteria) throws RestAPIException { List<CartridgeBean> cartridges = StratosApiV41Utils. getCartridgesByFilter(filter, criteria, getConfigContext()); if (cartridges == null || cartridges.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).build(); } CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]); return Response.ok().entity(cartridgeArray).build(); } /** * Returns a specific cartridge by category. * * @param filter Filter * @param cartridgeType Cartridge Type * @return 200 if a cartridge is found for specified filter, 404 if none found * @throws RestAPIException */ @GET @Path("/cartridges/{cartridgeType}/filter/{filter}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getCartridgesByFilter") public Response getCartridgeByFilter( @PathParam("cartridgeType") String cartridgeType, @DefaultValue("") @PathParam("filter") String filter) throws RestAPIException { CartridgeBean cartridge; try { cartridge = StratosApiV41Utils.getCartridgeByFilter(filter, cartridgeType, getConfigContext()); return Response.ok().entity(cartridge).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).build(); } } /** * Deletes a cartridge definition. * * @param cartridgeType the cartridge type * @return 200 if cartridge is successfully removed * @throws RestAPIException the rest api exception */ @DELETE @Path("/cartridges/{cartridgeType}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeCartridge") public Response removeCartridge( @PathParam("cartridgeType") String cartridgeType) throws RestAPIException { StratosApiV41Utils.removeCartridge(cartridgeType); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Cartridge deleted successfully: [cartridge-type] %s", cartridgeType))).build(); } // API methods for cartridge groups /** * Creates the cartridge group definition. * * @param serviceGroupDefinition the cartridge group definition * @return 201 if group added successfully * @throws RestAPIException the rest api exception */ @POST @Path("/cartridgeGroups") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addServiceGroup") @SuperTenantService(true) public Response addServiceGroup( GroupBean serviceGroupDefinition) throws RestAPIException { try { StratosApiV41Utils.addServiceGroup(serviceGroupDefinition); URI url = uriInfo.getAbsolutePathBuilder().path(serviceGroupDefinition.getName()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Service Group added successfully: [service-group] %s", serviceGroupDefinition.getName()))).build(); } catch (RestAPIException e) { if (e.getCause().getMessage().contains("already exists")) { return Response.status(Response.Status.CONFLICT).build(); } else { throw e; } } } /** * Gets the cartridge group definition. * * @param groupDefinitionName the group definition name * @return 200 if cartridge group found for group definition, 404 if none is found * @throws RestAPIException the rest api exception */ @GET @Path("/cartridgeGroups/{groupDefinitionName}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition") public Response getServiceGroupDefinition( @PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException { GroupBean serviceGroupDefinition = StratosApiV41Utils.getServiceGroupDefinition(groupDefinitionName); Response.ResponseBuilder rb; if (serviceGroupDefinition != null) { rb = Response.ok().entity(serviceGroupDefinition); } else { rb = Response.status(Response.Status.NOT_FOUND); } return rb.build(); } /** * Gets all cartridge groups created. * * @return 200 if cartridge groups are found, 404 if none found * @throws RestAPIException the rest api exception */ @GET @Path("/cartridgeGroups") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition") public Response getServiceGroups() throws RestAPIException { GroupBean[] serviceGroups = StratosApiV41Utils.getServiceGroupDefinitions(); Response.ResponseBuilder rb; if (serviceGroups != null) { rb = Response.ok().entity(serviceGroups); } else { rb = Response.status(Response.Status.NOT_FOUND); } return rb.build(); } /** * Delete cartridge group definition. * * @param groupDefinitionName the group definition name * @return 200 if cartridge group is successfully removed * @throws RestAPIException the rest api exception */ @DELETE @Path("/cartridgeGroups/{groupDefinitionName}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/removeServiceGroup") @SuperTenantService(true) public Response removeServiceGroup( @PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException { StratosApiV41Utils.removeServiceGroup(groupDefinitionName); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Service Group deleted successfully: [service-group] %s", groupDefinitionName))) .build(); } // API methods for network partitions /** * Add network partition * * @param networkPartitionBean Network Partition * @return 201 if network partition successfully added, 409 if network partition already exists * @throws RestAPIException */ @POST @Path("/networkPartitions") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addNetworkPartition") public Response addNetworkPartition( NetworkPartitionBean networkPartitionBean) throws RestAPIException { String networkPartitionId = networkPartitionBean.getId(); try { StratosApiV41Utils.addNetworkPartition(networkPartitionBean); } catch (CloudControllerServiceNetworkPartitionAlreadyExistsExceptionException e) { return Response.status(Response.Status.CONFLICT) .entity(new ErrorResponseBean(Response.Status.CONFLICT.getStatusCode(), e.getLocalizedMessage())) .build(); } URI url = uriInfo.getAbsolutePathBuilder().path(networkPartitionId).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Network partition added successfully: [network-partition] %s", networkPartitionId))) .build(); } /** * Get network partitions * * @return 200 if network partitions are found * @throws RestAPIException */ @GET @Path("/networkPartitions") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getNetworkPartitions") public Response getNetworkPartitions() throws RestAPIException { NetworkPartitionBean[] networkPartitions = StratosApiV41Utils.getNetworkPartitions(); if (networkPartitions == null || networkPartitions.length == 0) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(networkPartitions).build(); } /** * Get network partition by network partition id * * @return 200 if specified network partition is found * @throws RestAPIException */ @GET @Path("/networkPartitions/{networkPartitionId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getNetworkPartitions") public Response getNetworkPartition( @PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException { NetworkPartitionBean networkPartition = StratosApiV41Utils.getNetworkPartition(networkPartitionId); if (networkPartition == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(networkPartition).build(); } /** * Remove network partition by network partition id * * @return 200 if specified network partition is successfully deleted, 404 if specified network partition is not * found * @throws RestAPIException */ @DELETE @Path("/networkPartitions/{networkPartitionId}") @AuthorizationAction("/permission/protected/manage/removeNetworkPartition") public Response removeNetworkPartition( @PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException { try { StratosApiV41Utils.removeNetworkPartition(networkPartitionId); } catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Network Partition deleted successfully: [network-partition] %s", networkPartitionId))).build(); } // API methods for applications /** * Add application * * @param applicationDefinition Application Definition * @return 201 if application is successfully added * @throws RestAPIException */ @POST @Path("/applications") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addApplication") public Response addApplication(ApplicationBean applicationDefinition) throws RestAPIException { try { StratosApiV41Utils.addApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain()); URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Application added successfully: [application] %s", applicationDefinition.getApplicationId()))).build(); } catch (ApplicationAlreadyExistException e) { return Response.status(Response.Status.CONFLICT).build(); } catch (RestAPIException e) { throw e; } } /** * Add application * * @param applicationDefinition Application Definition * @return 201 if application is successfully added * @throws RestAPIException */ @PUT @Path("/applications") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addApplication") public Response updateApplication(ApplicationBean applicationDefinition) throws RestAPIException { try { StratosApiV41Utils.updateApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain()); URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Application added successfully: [application] %s", applicationDefinition.getApplicationId()))).build(); } catch (RestAPIException e) { throw e; } } /** * Return applications * * @return 200 if applications are found * @throws RestAPIException */ @GET @Path("/applications") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplications") public Response getApplications() throws RestAPIException { List<ApplicationBean> applicationDefinitions = StratosApiV41Utils.getApplications(); if (applicationDefinitions == null || applicationDefinitions.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "No applications found")).build(); } ApplicationBean[] applicationDefinitionsArray = applicationDefinitions .toArray(new ApplicationBean[applicationDefinitions.size()]); return Response.ok(applicationDefinitionsArray).build(); } /** * Gets the application. * * @param applicationId the application id * @return 200 if specified application is found, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/applications/{applicationId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplications") public Response getApplication( @PathParam("applicationId") String applicationId) throws RestAPIException { ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId); if (applicationDefinition == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Application not found")).build(); } return Response.ok(applicationDefinition).build(); } /** * Deploy application. * * @param applicationId Application Id * @param applicationPolicyId the application policy id * @return 202 after deployment process is started. Deployment is asynchronous * @throws RestAPIException the rest api exception */ @POST @Path("/applications/{applicationId}/deploy/{applicationPolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/deployApplication") public Response deployApplication( @PathParam("applicationId") String applicationId, @PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException { try { StratosApiV41Utils.deployApplication(applicationId, applicationPolicyId); return Response.accepted().entity(new SuccessResponseBean(Response.Status.ACCEPTED.getStatusCode(), String.format("Application deployed successfully: [application] %s", applicationId))).build(); } catch (ApplicationAlreadyDeployedException e) { return Response.status(Response.Status.CONFLICT).entity(new ErrorResponseBean( Response.Status.CONFLICT.getStatusCode(), "Application policy already deployed")).build(); } catch (RestAPIException e) { throw e; } } /** * Adds an application policy * * @param applicationPolicy Application Policy * @return 201 if the application policy is successfully added * @throws RestAPIException */ @POST @Path("/applicationPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addApplicationPolicy") public Response addApplicationPolicy( ApplicationPolicyBean applicationPolicy) throws RestAPIException { try { StratosApiV41Utils.addApplicationPolicy(applicationPolicy); URI url = uriInfo.getAbsolutePathBuilder().path(applicationPolicy.getId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Application policy added successfully: [application-policy] %s", applicationPolicy.getId()))).build(); } catch (RestAPIException e) { throw e; } catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Invalid application policy")).build(); } } /** * Retrieve specified application policy * * @param applicationPolicyId Application Policy Id * @return 200 if application policy is found * @throws RestAPIException */ @GET @Path("/applicationPolicies/{applicationPolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplicationPolicy") public Response getApplicationPolicy( @PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException { try { ApplicationPolicyBean applicationPolicyBean = StratosApiV41Utils.getApplicationPolicy(applicationPolicyId); if (applicationPolicyBean == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(applicationPolicyBean).build(); } catch (ApplicationPolicyIdIsEmptyException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } } /** * Retrieve all application policies * * @return 200 * @throws RestAPIException */ @GET @Path("/applicationPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getApplicationPolicies") public Response getApplicationPolicies() throws RestAPIException { ApplicationPolicyBean[] applicationPolicies = StratosApiV41Utils.getApplicationPolicies(); if (applicationPolicies == null || applicationPolicies.length == 0) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok().entity(applicationPolicies).build(); } /** * Remove specified application policy * * @param applicationPolicyId Application Policy Id * @return 200 if application policy is successfully removed * @throws RestAPIException */ @DELETE @Path("/applicationPolicies/{applicationPolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeApplicationPolicy") public Response removeApplicationPolicy( @PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException { try { StratosApiV41Utils.removeApplicationPolicy(applicationPolicyId); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Application policy deleted successfully: [application-policy] %s", applicationPolicyId))).build(); } catch (ApplicationPolicyIdIsEmptyException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Autoscaling policy id is empty")) .build(); } catch (AutoscalerServiceInvalidPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Autoscaling policy is invalid")) .build(); } } /** * Update application policy * * @param applicationPolicy Application Policy * @return 200 if application policies successfully updated * @throws RestAPIException */ @PUT @Path("/applicationPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateApplicationPolicy") public Response updateApplicationPolicy( ApplicationPolicyBean applicationPolicy) throws RestAPIException { try { StratosApiV41Utils.updateApplicationPolicy(applicationPolicy); } catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Invalid application policy")) .build(); } catch (AutoscalerServiceApplicatioinPolicyNotExistsExceptionException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Application policy does not exist")) .build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Application policy updated successfully: [application-policy] %s", applicationPolicy.getId()))).build(); } /** * Get network partition ids used in an application * * @return 200 * @throws RestAPIException */ @GET @Path("/applications/{applicationId}/networkPartitions") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplicationNetworkPartitions") public Response getApplicationNetworkPartitions( @PathParam("applicationId") String applicationId) throws RestAPIException { ApplicationNetworkPartitionIdListBean appNetworkPartitionsBean = StratosApiV41Utils .getApplicationNetworkPartitions(applicationId); if (appNetworkPartitionsBean == null || (appNetworkPartitionsBean.getNetworkPartitionIds().size() == 1 && appNetworkPartitionsBean.getNetworkPartitionIds().get(0) == null)) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "No network partitions used in the application")) .build(); } return Response.ok(appNetworkPartitionsBean).build(); } /** * Signs up for an application. * * @param applicationId the application id * @param applicationSignUpBean the application sign up bean * @return 200 if application sign up was successfull * @throws RestAPIException the rest api exception */ @POST @Path("/applications/{applicationId}/signup") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addApplicationSignUp") public Response addApplicationSignUp( @PathParam("applicationId") String applicationId, ApplicationSignUpBean applicationSignUpBean) throws RestAPIException { StratosApiV41Utils.addApplicationSignUp(applicationId, applicationSignUpBean); URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Successfully signed up for: [application] %s", applicationId))).build(); } /** * Gets the application sign up. * * @param applicationId the application id * @return 200 if specified application signup is found, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/applications/{applicationId}/signup") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplicationSignUp") public Response getApplicationSignUp( @PathParam("applicationId") String applicationId) throws RestAPIException, StratosManagerServiceApplicationSignUpExceptionException { ApplicationSignUpBean applicationSignUpBean; try { applicationSignUpBean = StratosApiV41Utils.getApplicationSignUp(applicationId); if (applicationSignUpBean == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "No Application sign ups found for application")) .build(); } return Response.ok(applicationSignUpBean).build(); } catch (ApplicationSignUpRestAPIException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Incorrect request to get application sign ups")) .build(); } } /** * Removes the application sign up. * * @param applicationId the application id * @return 200 if specified application sign up is removed * @throws RestAPIException the rest api exception */ @DELETE @Path("/applications/{applicationId}/signup") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/removeApplicationSignUp") public Response removeApplicationSignUp( @PathParam("applicationId") String applicationId) throws RestAPIException { StratosApiV41Utils.removeApplicationSignUp(applicationId); return Response.ok().build(); } /** * Adds the domain mappings for an application. * * @param applicationId the application id * @param domainMappingsBean the domain mappings bean * @return 200 * @throws RestAPIException the rest api exception */ @POST @Path("/applications/{applicationId}/domainMappings") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/addDomainMappings") public Response addDomainMappings( @PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMappingsBean) throws RestAPIException { try { StratosApiV41Utils.addApplicationDomainMappings(applicationId, domainMappingsBean); } catch (StratosManagerServiceDomainMappingExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Incorrect request to add domain mapping for " + "application")).build(); } List<DomainMappingBean> mappings = domainMappingsBean.getDomainMappings(); List<String> domainMappingList = new ArrayList<String>(); for (DomainMappingBean domainMappingBean : mappings) { domainMappingList.add(domainMappingBean.getDomainName()); } URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Domain Mappings added successfully: [domain-mappings] %s", domainMappingList))) .build(); } /** * Removes the domain mappings for an application. * * @param applicationId the application id * @param domainMapppingsBean the domain mapppings bean * @return 200 * @throws RestAPIException the rest api exception */ @DELETE @Path("/applications/{applicationId}/domainMappings") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/removeDomainMappings") public Response removeDomainMappings( @PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMapppingsBean) throws RestAPIException { try { StratosApiV41Utils.removeApplicationDomainMappings(applicationId, domainMapppingsBean); } catch (StratosManagerServiceDomainMappingExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Incorrect request to delete domain mapping of " + "application")).build(); } List<DomainMappingBean> mappings = domainMapppingsBean.getDomainMappings(); List<String> domainMappingList = new ArrayList<String>(); for (DomainMappingBean domainMappingBean : mappings) { domainMappingList.add(domainMappingBean.getDomainName()); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Domain Mappings deleted successfully: [domain-mappings] %s", domainMappingList))) .build(); } /** * Gets the domain mappings for an application. * * @param applicationId the application id * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/applications/{applicationId}/domainMappings") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getDomainMappings") public Response getDomainMappings( @PathParam("applicationId") String applicationId) throws RestAPIException { List<DomainMappingBean> domainMappingsBeanList = null; try { domainMappingsBeanList = StratosApiV41Utils.getApplicationDomainMappings(applicationId); if (domainMappingsBeanList == null || domainMappingsBeanList.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "No domain mappings found for the application")) .build(); } } catch (StratosManagerServiceDomainMappingExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Incorrect request to get domain mapping of application")) .build(); } DomainMappingBean[] domainMappingsBeans = domainMappingsBeanList .toArray(new DomainMappingBean[domainMappingsBeanList.size()]); return Response.ok(domainMappingsBeans).build(); } /** * Undeploy an application. * * @param applicationId the application id * @return 202 if undeployment process started, 404 if specified application is not found, 409 if application * status is not in DEPLOYED state * @throws RestAPIException the rest api exception */ @POST @Path("/applications/{applicationId}/undeploy") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/undeployApplication") public Response undeployApplication( @PathParam("applicationId") String applicationId, @QueryParam("force") @DefaultValue("false") boolean force) throws RestAPIException { ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId); if (applicationDefinition == null) { String msg = String.format("Application does not exist [application-id] %s", applicationId); log.info(msg); return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), msg)).build(); } if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_DEPLOYED)) { String message = String.format("Could not undeploy since application is not in DEPLOYED status " + "[application-id] %s [current status] %S", applicationId, applicationDefinition.getStatus()); log.info(message); return Response.status(Response.Status.CONFLICT).entity(new ErrorResponseBean( Response.Status.CONFLICT.getStatusCode(), message)).build(); } StratosApiV41Utils.undeployApplication(applicationId, force); return Response.accepted().entity(new SuccessResponseBean(Response.Status.ACCEPTED.getStatusCode(), String.format("Application undeployed successfully: [application] %s", applicationId))).build(); } /** * This API resource provides information about the application denoted by the given appId. Details includes, * Application details, top level cluster details, details of the group and sub groups. * * @param applicationId Id of the application. * @return Json representing the application details with 200 as HTTP status. HTTP 404 is returned when there is * no application with given Id. * @throws RestAPIException is thrown in case of failure occurs. */ @GET @Path("/applications/{applicationId}/runtime") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/getApplicationRuntime") public Response getApplicationRuntime( @PathParam("applicationId") String applicationId) throws RestAPIException { ApplicationInfoBean applicationRuntime = StratosApiV41Utils.getApplicationRuntime(applicationId); if (applicationRuntime == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Application runtime not found")).build(); } else { return Response.ok().entity(applicationRuntime).build(); } } /** * Delete an application. * * @param applicationId the application id * @return 200 if application is successfully removed, 404 if specified application is not found, 409 if * application is not in CREATED state * @throws RestAPIException the rest api exception */ @DELETE @Path("/applications/{applicationId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/removeApplication") @SuperTenantService(true) public Response removeApplication( @PathParam("applicationId") String applicationId) throws RestAPIException { ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId); if (applicationDefinition == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Application not found")).build(); } if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_CREATED)) { return Response.status(Response.Status.CONFLICT).entity(new SuccessResponseBean(Response.Status.CONFLICT. getStatusCode(), String.format("Could not delete since application is not in CREATED state :" + " [application] %s [current-status] %S", applicationId, applicationDefinition.getStatus()))).build(); } StratosApiV41Utils.removeApplication(applicationId); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Application deleted successfully: [application] %s", applicationId))).build(); } // API methods for autoscaling policies /** * Gets the autoscaling policies. * * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/autoscalingPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies") public Response getAutoscalingPolicies() throws RestAPIException { AutoscalePolicyBean[] autoScalePolicies = StratosApiV41Utils.getAutoScalePolicies(); if (autoScalePolicies == null || autoScalePolicies.length == 0) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "No Autoscaling policies found")).build(); } return Response.ok().entity(autoScalePolicies).build(); } /** * Gets the autoscaling policy. * * @param autoscalePolicyId the autoscale policy id * @return 200 if specified autoscaling policy is found, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/autoscalingPolicies/{autoscalePolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies") public Response getAutoscalingPolicy( @PathParam("autoscalePolicyId") String autoscalePolicyId) throws RestAPIException { AutoscalePolicyBean autoScalePolicy = StratosApiV41Utils.getAutoScalePolicy(autoscalePolicyId); if (autoScalePolicy == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Autoscaling policy not found")).build(); } return Response.ok().entity(autoScalePolicy).build(); } /** * Creates the autoscaling policy defintion. * * @param autoscalePolicy the autoscale policy * @return 201 if autoscale policy is successfully added * @throws RestAPIException the rest api exception */ @POST @Path("/autoscalingPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addAutoscalingPolicy") public Response addAutoscalingPolicy( AutoscalePolicyBean autoscalePolicy) throws RestAPIException { try { StratosApiV41Utils.addAutoscalingPolicy(autoscalePolicy); URI url = uriInfo.getAbsolutePathBuilder().path(autoscalePolicy.getId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Autoscaling policy added successfully: [autoscale-policy] %s", autoscalePolicy.getId()))).build(); } catch (AutoscalerServiceInvalidPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Provided Autoscaling policy is invalid")).build(); } catch (AutoscalerServiceAutoScalingPolicyAlreadyExistExceptionException e) { return Response.status(Response.Status.CONFLICT).entity(new ErrorResponseBean( Response.Status.CONFLICT.getStatusCode(), "Autoscaling policy already exists")).build(); } catch (RestAPIException e) { throw e; } } /** * Update autoscaling policy. * * @param autoscalePolicy the autoscale policy * @return 200 if autoscale policy is successfully updated * @throws RestAPIException the rest api exception */ @PUT @Path("/autoscalingPolicies") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateAutoscalingPolicy") public Response updateAutoscalingPolicy( AutoscalePolicyBean autoscalePolicy) throws RestAPIException { try { StratosApiV41Utils.updateAutoscalingPolicy(autoscalePolicy); } catch (AutoscalerServiceInvalidPolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Autoscaling policy is invalid")).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Autoscaling policy updated successfully: [autoscale-policy] %s", autoscalePolicy.getId()))).build(); } /** * Updates a network partition * * @param networkPartition Network Partition * @return 200 if network partition is successfully updated * @throws RestAPIException */ @PUT @Path("/networkPartitions") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/updateNetworkPartition") public Response updateNetworkPartition( NetworkPartitionBean networkPartition) throws RestAPIException { try { StratosApiV41Utils.updateNetworkPartition(networkPartition); } catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Network partition not found")).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Network Partition updated successfully: [network-partition] %s", networkPartition.getId()))).build(); } /** * Remove autoscaling policy. * * @param autoscalingPolicyId the autoscale policy * @return 200 * @throws RestAPIException the rest api exception */ @DELETE @Path("/autoscalingPolicies/{autoscalingPolicyId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeAutoscalingPolicy") public Response removeAutoscalingPolicy( @PathParam("autoscalingPolicyId") String autoscalingPolicyId) throws RestAPIException { try { StratosApiV41Utils.removeAutoscalingPolicy(autoscalingPolicyId); } catch (AutoscalerServiceUnremovablePolicyExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Autoscaling policy is in use")).build(); } catch (AutoscalerServicePolicyDoesNotExistExceptionException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Autoscaling policy not found")).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Autoscaling policy deleted successfully: [autoscale-policy] %s", autoscalingPolicyId))).build(); } /** * Get cluster for a given cluster id * * @param clusterId id of the cluster * @return 200 if specified cluster is found, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/cluster/{clusterId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/cluster") public Response getCluster( @PathParam("clusterId") String clusterId) throws RestAPIException { try { ClusterBean clusterBean = StratosApiV41Utils.getClusterInfo(clusterId); if (clusterBean == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Cluster not found")).build(); } else { return Response.ok().entity(clusterBean).build(); } } catch (ClusterIdIsEmptyException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } } // API methods for tenants /** * Adds the tenant. * * @param tenantInfoBean the tenant info bean * @return 201 if the tenant is successfully added * @throws RestAPIException the rest api exception */ @POST @Path("/tenants") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/addTenant") @SuperTenantService(true) public Response addTenant( org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException { try { StratosApiV41Utils.addTenant(tenantInfoBean); } catch (InvalidEmailException e) { Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Invalid email")).build(); } catch (InvalidDomainException e) { Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Invalid domain")).build(); } URI url = uriInfo.getAbsolutePathBuilder().path(tenantInfoBean.getTenantDomain()).build(); return Response.created(url).entity( new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format( "Tenant added successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))).build(); } /** * Update tenant. * * @param tenantInfoBean the tenant info bean * @return 200 if tenant is successfully updated, 404 if specified tenant not found * @throws RestAPIException the rest api exception */ @PUT @Path("/tenants") @Consumes("application/json") @AuthorizationAction("/permission/protected/manage/updateTenant") @SuperTenantService(true) public Response updateTenant( org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException { try { StratosApiV41Utils.updateExistingTenant(tenantInfoBean); } catch (TenantNotFoundException ex) { Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Tenant not found")).build(); } catch (InvalidEmailException e) { Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Invalid email")).build(); } catch (Exception e) { String msg = "Error in updating tenant " + tenantInfoBean.getTenantDomain(); log.error(msg, e); throw new RestAPIException(msg); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Tenant updated successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))) .build(); } /** * Gets the tenant by domain. * * @param tenantDomain the tenant domain * @return 200 if tenant for specified tenant domain found * @throws RestAPIException the rest api exception */ @GET @Path("/tenants/{tenantDomain}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/getTenantForDomain") @SuperTenantService(true) public Response getTenantForDomain( @PathParam("tenantDomain") String tenantDomain) throws RestAPIException { try { TenantInfoBean tenantInfo = StratosApiV41Utils.getTenantByDomain(tenantDomain); if (tenantInfo == null) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Tenant information not found")).build(); } return Response.ok().entity(tenantInfo).build(); } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).build(); } } /** * Delete tenant. * * @param tenantDomain the tenant domain * @return 406 - Use tenantDeactivate method * @throws RestAPIException the rest api exception */ @DELETE @Path("/tenants/{tenantDomain}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/removeTenant") @SuperTenantService(true) public Response removeTenant( @PathParam("tenantDomain") String tenantDomain) throws RestAPIException { return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new ErrorResponseBean(Response.Status.NOT_ACCEPTABLE.getStatusCode(), "Please use the tenant deactivate method")).build(); } /** * Gets the tenants. * * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/tenants") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/getTenants") @SuperTenantService(true) public Response getTenants() throws RestAPIException { try { List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.getAllTenants(); if (tenantList == null || tenantList.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok().entity(tenantList.toArray( new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build(); } catch (Exception e) { String msg = "Error in retrieving tenants"; log.error(msg, e); throw new RestAPIException(msg); } } /** * Gets the partial search tenants. * * @param tenantDomain the tenant domain * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/tenants/search/{tenantDomain}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/getTenants") @SuperTenantService(true) public Response getPartialSearchTenants( @PathParam("tenantDomain") String tenantDomain) throws RestAPIException { try { List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.searchPartialTenantsDomains(tenantDomain); if (tenantList == null || tenantList.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok().entity(tenantList.toArray(new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build(); } catch (Exception e) { String msg = "Error in getting information for tenant " + tenantDomain; log.error(msg, e); throw new RestAPIException(msg); } } /** * Activate tenant. * * @param tenantDomain the tenant domain * @return 200 if tenant activated successfully * @throws RestAPIException the rest api exception */ @PUT @Path("/tenants/activate/{tenantDomain}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/activateTenant") @SuperTenantService(true) public Response activateTenant( @PathParam("tenantDomain") String tenantDomain) throws RestAPIException { StratosApiV41Utils.activateTenant(tenantDomain); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Tenant activated successfully: [tenant] %s", tenantDomain))).build(); } /** * Deactivate tenant. * * @param tenantDomain the tenant domain * @return 200 if tenant deactivated successfully * @throws RestAPIException the rest api exception */ @PUT @Path("/tenants/deactivate/{tenantDomain}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/protected/manage/deactivateTenant") @SuperTenantService(true) public Response deactivateTenant( @PathParam("tenantDomain") String tenantDomain) throws RestAPIException { StratosApiV41Utils.deactivateTenant(tenantDomain); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Tenant deactivated successfully: [tenant] %s", tenantDomain))).build(); } // API methods for repositories /** * Notify artifact update event for specified repository * * @param payload Git notification Payload * @return 204 * @throws RestAPIException */ @POST @Path("/repo/notify") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/notifyRepository") public Response notifyRepository( GitNotificationPayloadBean payload) throws RestAPIException { if (log.isInfoEnabled()) { log.info(String.format("Git update notification received.")); } StratosApiV41Utils.notifyArtifactUpdatedEvent(payload); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Repository notificaton sent successfully"))).build(); } // API methods for users /** * Adds the user. * * @param userInfoBean the user info bean * @return 201 if the user is successfully created * @throws RestAPIException the rest api exception */ @POST @Path("/users") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/admin/manage/addUser") public Response addUser( UserInfoBean userInfoBean) throws RestAPIException { StratosApiV41Utils.addUser(userInfoBean); log.info("Successfully added an user with Username " + userInfoBean.getUserName()); URI url = uriInfo.getAbsolutePathBuilder().path(userInfoBean.getUserName()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("User added successfully: [user] %s", userInfoBean.getUserName()))).build(); } /** * Delete user. * * @param userName the user name * @return 200 if the user is successfully deleted * @throws RestAPIException the rest api exception */ @DELETE @Path("/users/{userName}") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/admin/manage/removeUser") public Response removeUser( @PathParam("userName") String userName) throws RestAPIException { StratosApiV41Utils.removeUser(userName); log.info("Successfully removed user: [username] " + userName); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("User deleted successfully: [user] %s", userName))).build(); } /** * Update user. * * @param userInfoBean the user info bean * @return 200 if the user is successfully updated * @throws RestAPIException the rest api exception */ @PUT @Path("/users") @Consumes("application/json") @Produces("application/json") @AuthorizationAction("/permission/admin/manage/updateUser") public Response updateUser( UserInfoBean userInfoBean) throws RestAPIException { StratosApiV41Utils.updateUser(userInfoBean); log.info("Successfully updated an user with Username " + userInfoBean.getUserName()); return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("User updated successfully: [user] %s", userInfoBean.getUserName()))).build(); } /** * Gets the users. * * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/users") @Produces("application/json") @AuthorizationAction("/permission/admin/manage/getUsers") public Response getUsers() throws RestAPIException { List<UserInfoBean> userList = StratosApiV41Utils.getUsers(); return Response.ok().entity(userList.toArray(new UserInfoBean[userList.size()])).build(); } // API methods for Kubernetes clusters /** * Deploy kubernetes host cluster. * * @param kubernetesCluster the kubernetes cluster * @return 201 if the kubernetes cluster is successfully created * @throws RestAPIException the rest api exception */ @POST @Path("/kubernetesClusters") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addKubernetesHostCluster") public Response addKubernetesHostCluster( KubernetesClusterBean kubernetesCluster) throws RestAPIException { try { StratosApiV41Utils.addKubernetesCluster(kubernetesCluster); URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesCluster.getClusterId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Kubernetes Host Cluster added successfully: [kub-host-cluster] %s", kubernetesCluster.getClusterId()))).build(); } catch (RestAPIException e) { throw e; } catch (CloudControllerServiceKubernetesClusterAlreadyExistsExceptionException e) { return Response.status(Response.Status.CONFLICT).entity(new ErrorResponseBean( Response.Status.CONFLICT.getStatusCode(), "Kubernetes cluster already exists")).build(); } catch (CloudControllerServiceInvalidKubernetesClusterExceptionException e) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponseBean( Response.Status.BAD_REQUEST.getStatusCode(), "Kubernetes cluster is invalid")).build(); } } /** * Deploy kubernetes host. * * @param kubernetesClusterId the kubernetes cluster id * @param kubernetesHost the kubernetes host * @return 201 if the kubernetes host is successfully added * @throws RestAPIException the rest api exception */ @POST @Path("/kubernetesClusters/{kubernetesClusterId}/minion") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/addKubernetesHost") public Response addKubernetesHost( @PathParam("kubernetesClusterId") String kubernetesClusterId, KubernetesHostBean kubernetesHost) throws RestAPIException { StratosApiV41Utils.addKubernetesHost(kubernetesClusterId, kubernetesHost); URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build(); return Response.created(url).entity(new SuccessResponseBean(Response.Status.CREATED.getStatusCode(), String.format("Kubernetes Host added successfully: [kub-host] %s", kubernetesHost.getHostId()))) .build(); } /** * Update kubernetes master. * * @param kubernetesMaster the kubernetes master * @return 200 if the kubernetes master is updated successfully, 404 if the kubernetes master is not found * @throws RestAPIException the rest api exception */ @PUT @Path("/kubernetesClusters/{kubernetesClusterId}/master") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateKubernetesMaster") public Response updateKubernetesMaster( KubernetesMasterBean kubernetesMaster) throws RestAPIException { try { StratosApiV41Utils.updateKubernetesMaster(kubernetesMaster); URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesMaster.getHostId()).build(); return Response.ok(url).entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Kubernetes Master updated successfully: [kub-master] %s", kubernetesMaster.getHostId()))).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes cluster not found")).build(); } } //TODO: Check need for this method @PUT @Path("/kubernetes/update/host") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/updateKubernetesHost") public Response updateKubernetesHost( KubernetesHostBean kubernetesHost) throws RestAPIException { try { StratosApiV41Utils.updateKubernetesHost(kubernetesHost); URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build(); return Response.ok(url).entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Kubernetes Host updated successfully: [kub-host] %s", kubernetesHost.getHostId()))).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes host not found")).build(); } } /** * Gets the kubernetes host clusters. * * @return 200 * @throws RestAPIException the rest api exception */ @GET @Path("/kubernetesClusters") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters") public Response getKubernetesHostClusters() throws RestAPIException { KubernetesClusterBean[] availableKubernetesClusters = StratosApiV41Utils.getAvailableKubernetesClusters(); if (availableKubernetesClusters == null || availableKubernetesClusters.length == 0) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes cluster not found")).build(); } return Response.ok().entity(availableKubernetesClusters).build(); } /** * Gets the kubernetes host cluster. * * @param kubernetesClusterId the kubernetes cluster id * @return 200 if specified kubernetes host cluster is found, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/kubernetesClusters/{kubernetesClusterId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters") public Response getKubernetesHostCluster( @PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException { try { return Response.ok().entity(StratosApiV41Utils.getKubernetesCluster(kubernetesClusterId)).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes cluster not found")).build(); } } /** * Gets the kubernetes hosts of kubernetes cluster. * * @param kubernetesClusterId the kubernetes cluster id * @return 200 if hosts are found in the specified kubernetes host cluster, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/kubernetesClusters/{kubernetesClusterId}/hosts") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters") public Response getKubernetesHostsOfKubernetesCluster( @PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException { try { return Response.ok().entity(StratosApiV41Utils.getKubernetesHosts(kubernetesClusterId)).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes hosts not found")).build(); } } /** * Gets the kubernetes master of kubernetes cluster. * * @param kubernetesClusterId the kubernetes cluster id * @return 200 if master is found for specified kubernetes cluster, 404 if not * @throws RestAPIException the rest api exception */ @GET @Path("/kubernetesClusters/{kubernetesClusterId}/master") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters") public Response getKubernetesMasterOfKubernetesCluster( @PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException { try { return Response.ok().entity(StratosApiV41Utils.getKubernetesMaster(kubernetesClusterId)).build(); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes cluster not found")).build(); } } /** * Un deploy kubernetes host cluster. * * @param kubernetesClusterId the kubernetes cluster id * @return 204 if Kubernetes cluster is successfully removed, 404 if the specified Kubernetes cluster is not found * @throws RestAPIException the rest api exception */ @DELETE @Path("/kubernetesClusters/{kubernetesClusterId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster") public Response removeKubernetesHostCluster( @PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException { try { StratosApiV41Utils.removeKubernetesCluster(kubernetesClusterId); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND) .entity(new SuccessResponseBean(Response.Status.NOT_FOUND.getStatusCode(), String.format("Could not find specified Kubernetes cluster: [kub-cluster] %s", kubernetesClusterId))).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Kubernetes Cluster removed successfully: [kub-cluster] %s", kubernetesClusterId))) .build(); } /** * Undeploy kubernetes host of kubernetes cluster. * * @param kubernetesHostId the kubernetes host id * @return 200 if hosts are successfully removed from the specified Kubernetes cluster, 404 if specified Kubernetes * cluster is not found. * @throws RestAPIException the rest api exception */ @DELETE @Path("/kubernetesClusters/{kubernetesClusterId}/hosts/{hostId}") @Produces("application/json") @Consumes("application/json") @AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster") public Response removeKubernetesHostOfKubernetesCluster( @PathParam("hostId") String kubernetesHostId) throws RestAPIException { try { StratosApiV41Utils.removeKubernetesHost(kubernetesHostId); } catch (RestAPIException e) { return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponseBean( Response.Status.NOT_FOUND.getStatusCode(), "Kubernetes cluster not found")).build(); } return Response.ok().entity(new SuccessResponseBean(Response.Status.OK.getStatusCode(), String.format("Kubernetes Host removed successfully: [kub-host] %s", kubernetesHostId))) .build(); } }
apache-2.0
jjhaggar/ludum30_a_hole_new_world
android/src/com/blogspot/ludumdaresforfun/android/AndroidLauncher.java
533
package com.blogspot.ludumdaresforfun.android; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.blogspot.ludumdaresforfun.LD; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); initialize(new LD(), config); } }
apache-2.0
jalaziz/cens-whatsinvasive
src/edu/ucla/cens/whatsinvasive/ViewTag.java
1968
package edu.ucla.cens.whatsinvasive; import java.io.File; import android.app.Activity; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase.PhotoDatabaseRow; public class ViewTag extends Activity { private PhotoDatabaseRow data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_tag); PhotoDatabase pdb = new PhotoDatabase(this); long id = this.getIntent().getIntExtra("id", -1); pdb.open(); data = pdb.fetchPhoto(id); pdb.close(); if(data!=null) populate(); } private void populate(){ TextView tag = (TextView) this.findViewById(R.id.tag_name); TextView tagged = (TextView) this.findViewById(R.id.tag_time); TextView uploaded = (TextView) this.findViewById(R.id.tag_time); TextView location = (TextView) this.findViewById(R.id.tag_location); TextView notes = (TextView)this.findViewById(R.id.tag_note); ImageView thumbnail = (ImageView) this.findViewById(R.id.tag_image); tag.setText(data.tagsValue); tagged.setText(getString(R.string.tag_tagged_at) + " " + data.timeValue); if(data.uploadValue!=null) uploaded.setText(getString(R.string.tag_uploaded_on) + " " + data.uploadValue); if(data.latValue != 0) location.setText(String.format("%s %.4f, %.4f ± %.2f m", getString(R.string.tag_location), data.latValue, data.lonValue, data.accuracyValue)); if(data.noteValue != null) notes.setText(getString(R.string.tag_note) + " " + data.noteValue); if(data.filenameValue != null && new File(data.filenameValue).exists()){ thumbnail.setVisibility(ImageView.VISIBLE); thumbnail.setImageBitmap(BitmapFactory.decodeFile(data.filenameValue)); }else{ thumbnail.setVisibility(ImageView.GONE); } } }
apache-2.0
yzuzhang/zhang
src/main/java/com/feicent/zhang/io/DownloadUtils.java
1719
package com.feicent.zhang.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feicent.zhang.util.CloseUtil; public class DownloadUtils { private static Logger logger = LoggerFactory.getLogger(DownloadUtils.class); public static void download(HttpServletRequest request, HttpServletResponse response, String filepath, String fileName) throws Exception { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; String ctxPath = request.getSession().getServletContext().getRealPath("/") +filepath; try { File file = new File(ctxPath); if(!file.exists()) throw new RuntimeException("download agent is error: "+ ctxPath +" is not exists !"); response.setContentType("application/x-msdownload;"); response.setHeader("Content-Length", String.valueOf(file.length())); response.setHeader("Content-disposition","attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); bis = new BufferedInputStream(new FileInputStream(ctxPath)); bos = new BufferedOutputStream(response.getOutputStream()); int bytesRead = 0; byte[] buff = new byte[2048]; while (-1 != (bytesRead = bis.read(buff))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { logger.error("download agent is error ! messages --->> "+e.fillInStackTrace()); } finally { CloseUtil.close(bos, bis); } } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/MutateAdGroupCriterionLabelsRequestOrBuilder.java
3483
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/ad_group_criterion_label_service.proto package com.google.ads.googleads.v8.services; public interface MutateAdGroupCriterionLabelsRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.services.MutateAdGroupCriterionLabelsRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. ID of the customer whose ad group criterion labels are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ java.lang.String getCustomerId(); /** * <pre> * Required. ID of the customer whose ad group criterion labels are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ com.google.protobuf.ByteString getCustomerIdBytes(); /** * <pre> * Required. The list of operations to perform on ad group criterion labels. * </pre> * * <code>repeated .google.ads.googleads.v8.services.AdGroupCriterionLabelOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ java.util.List<com.google.ads.googleads.v8.services.AdGroupCriterionLabelOperation> getOperationsList(); /** * <pre> * Required. The list of operations to perform on ad group criterion labels. * </pre> * * <code>repeated .google.ads.googleads.v8.services.AdGroupCriterionLabelOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.ads.googleads.v8.services.AdGroupCriterionLabelOperation getOperations(int index); /** * <pre> * Required. The list of operations to perform on ad group criterion labels. * </pre> * * <code>repeated .google.ads.googleads.v8.services.AdGroupCriterionLabelOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ int getOperationsCount(); /** * <pre> * Required. The list of operations to perform on ad group criterion labels. * </pre> * * <code>repeated .google.ads.googleads.v8.services.AdGroupCriterionLabelOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ java.util.List<? extends com.google.ads.googleads.v8.services.AdGroupCriterionLabelOperationOrBuilder> getOperationsOrBuilderList(); /** * <pre> * Required. The list of operations to perform on ad group criterion labels. * </pre> * * <code>repeated .google.ads.googleads.v8.services.AdGroupCriterionLabelOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.ads.googleads.v8.services.AdGroupCriterionLabelOperationOrBuilder getOperationsOrBuilder( int index); /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 3;</code> * @return The partialFailure. */ boolean getPartialFailure(); /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ boolean getValidateOnly(); }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/transform/NoSuchChangeExceptionUnmarshaller.java
1528
/* * Copyright 2010-2016 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.route53.model.transform; import org.w3c.dom.Node; import com.amazonaws.AmazonServiceException; import com.amazonaws.util.XpathUtils; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.route53.model.NoSuchChangeException; public class NoSuchChangeExceptionUnmarshaller extends StandardErrorUnmarshaller { public NoSuchChangeExceptionUnmarshaller() { super(NoSuchChangeException.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("NoSuchChange")) return null; NoSuchChangeException e = (NoSuchChangeException) super .unmarshall(node); return e; } }
apache-2.0
mrniko/redisson
redisson/src/main/java/org/redisson/api/mapreduce/RCollector.java
1045
/** * Copyright (c) 2013-2020 Nikita Koksharov * * 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.redisson.api.mapreduce; /** * Stores each key/value mapping during map phase of MapReduce process. * Later used in reduce phase. * * * @author Nikita Koksharov * * @param <K> key type * @param <V> value type */ public interface RCollector<K, V> { /** * Store key/value * * @param key available to reduce * @param value available to reduce */ void emit(K key, V value); }
apache-2.0
Lewis-Liu-001/ansj_segx
src/main/java/org/ansj/library/dao/impl/package-info.java
81
/** * */ /** * @author Lewis * */ package org.ansj.library.dao.impl;
apache-2.0
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/enums/FeedMappingCriterionTypeProto.java
2783
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/enums/feed_mapping_criterion_type.proto package com.google.ads.googleads.v8.enums; public final class FeedMappingCriterionTypeProto { private FeedMappingCriterionTypeProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_enums_FeedMappingCriterionTypeEnum_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_enums_FeedMappingCriterionTypeEnum_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n?google/ads/googleads/v8/enums/feed_map" + "ping_criterion_type.proto\022\035google.ads.go" + "ogleads.v8.enums\032\034google/api/annotations" + ".proto\"\215\001\n\034FeedMappingCriterionTypeEnum\"" + "m\n\030FeedMappingCriterionType\022\017\n\013UNSPECIFI" + "ED\020\000\022\013\n\007UNKNOWN\020\001\022 \n\034LOCATION_EXTENSION_" + "TARGETING\020\004\022\021\n\rDSA_PAGE_FEED\020\003B\362\001\n!com.g" + "oogle.ads.googleads.v8.enumsB\035FeedMappin" + "gCriterionTypeProtoP\001ZBgoogle.golang.org" + "/genproto/googleapis/ads/googleads/v8/en" + "ums;enums\242\002\003GAA\252\002\035Google.Ads.GoogleAds.V" + "8.Enums\312\002\035Google\\Ads\\GoogleAds\\V8\\Enums\352" + "\002!Google::Ads::GoogleAds::V8::Enumsb\006pro" + "to3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v8_enums_FeedMappingCriterionTypeEnum_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v8_enums_FeedMappingCriterionTypeEnum_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_enums_FeedMappingCriterionTypeEnum_descriptor, new java.lang.String[] { }); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
consulo/consulo-android
tools-base/build-system/profile/src/test/java/com/android/builder/profile/ThreadRecorderTest.java
10618
/* * Copyright (C) 2015 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.android.builder.profile; import com.android.annotations.NonNull; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.concurrent.atomic.AtomicBoolean; /** * Tests for the {@link ThreadRecorder} class. */ public class ThreadRecorderTest { @Before public void setUp() { // reset for each test. ProcessRecorderFactory.sINSTANCE = new ProcessRecorderFactory(); ProcessRecorderFactory.sINSTANCE.setRecordWriter( Mockito.mock(ProcessRecorder.ExecutionRecordWriter.class)); } @Test public void testBasicTracing() { Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception{ return 10; } }); Assert.assertNotNull(value); Assert.assertEquals(10, value.intValue()); } @Test public void testBasicNoExceptionHandling() { final AtomicBoolean handlerCalled = new AtomicBoolean(false); Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception{ return 10; } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); } }); Assert.assertNotNull(value); Assert.assertEquals(10, value.intValue()); // exception handler shouldn't have been called. Assert.assertFalse(handlerCalled.get()); } @Test public void testBasicExceptionHandling() { final Exception toBeThrown = new Exception("random"); final AtomicBoolean handlerCalled = new AtomicBoolean(false); Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { throw toBeThrown; } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); Assert.assertEquals(toBeThrown, e); } }); Assert.assertTrue(handlerCalled.get()); Assert.assertNull(value); } @Test public void testBlocks() { Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return 10; } }); } }); Assert.assertNotNull(value); Assert.assertEquals(10, value.intValue()); } @Test public void testBlocksWithInnerException() { final Exception toBeThrown = new Exception("random"); final AtomicBoolean handlerCalled = new AtomicBoolean(false); Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { throw toBeThrown; } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); Assert.assertEquals(toBeThrown, e); } }); } }); Assert.assertTrue(handlerCalled.get()); Assert.assertNull(value); } @Test public void testBlocksWithOuterException() { final Exception toBeThrown = new Exception("random"); final AtomicBoolean handlerCalled = new AtomicBoolean(false); Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return 10; } }); throw toBeThrown; } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); Assert.assertEquals(toBeThrown, e); } }); Assert.assertTrue(handlerCalled.get()); Assert.assertNull(value); } @Test public void testBlocksWithInnerExceptionRepackaged() { final Exception toBeThrown = new Exception("random"); final AtomicBoolean handlerCalled = new AtomicBoolean(false); Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { throw toBeThrown; } }); } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); Assert.assertTrue(e instanceof RuntimeException); Assert.assertEquals(toBeThrown, e.getCause()); } }); Assert.assertTrue(handlerCalled.get()); Assert.assertNull(value); } @Test public void testWithMulipleInnerBlocksWithExceptionRepackaged() { final Exception toBeThrown = new Exception("random"); final AtomicBoolean handlerCalled = new AtomicBoolean(false); // make three layers and throw an exception from the bottom layer, ensure the exception // is not repackaged in a RuntimeException several time as it makes its way back up // to the handler. Integer value = ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { return ThreadRecorder.get().record( ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { throw toBeThrown; } }); } }); } @Override public void handleException(@NonNull Exception e) { handlerCalled.set(true); Assert.assertTrue(e instanceof RuntimeException); Assert.assertEquals(toBeThrown, e.getCause()); } }); Assert.assertTrue(handlerCalled.get()); Assert.assertNull(value); } @Test public void testExceptionPropagation() { final Exception toBeThrown = new Exception("random"); try { ThreadRecorder.get().record(ExecutionType.SOME_RANDOM_PROCESSING, new Recorder.Block<Integer>() { @Override public Integer call() throws Exception { throw toBeThrown; } }); } catch (Exception e) { Assert.assertEquals(toBeThrown, e.getCause()); return; } Assert.fail("Exception not propagated."); } }
apache-2.0
adleritech/flexibee
flexibee-core/src/test/java/com/adleritech/flexibee/core/api/domain/IssuedInvoiceTest.java
13130
package com.adleritech.flexibee.core.api.domain; import com.adleritech.flexibee.core.api.transformers.Factory; import org.junit.Test; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; import static java.math.BigDecimal.ONE; import static org.assertj.core.api.Assertions.assertThat; public class IssuedInvoiceTest { @Test public void parseFromXmlToObject() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<winstrom version=\"1.0\">\n" + " <adresar>\n" + " <kod>PBENDA</kod>\n" + " <id>ext:33866089</id>\n" + " <id>ext:1976780508</id>\n" + " <nazev>Papírnictví Benda</nazev>\n" + " <ulice>Plzeňská 65</ulice>\n" + " <mesto>Praha 5</mesto>\n" + " <psc>150 00</psc>\n" + " <ic>12345678</ic>\n" + " <dic>CZ7002051235</dic>\n" + " </adresar>\n" + " <faktura-vydana>\n" + " <firma>code:PBENDA</firma>\n" + " <typDokl>code:FAKTURA</typDokl>\n" + " </faktura-vydana>\n" + "</winstrom>"; Serializer serializer = new Persister(Factory.matchers()); WinstromRequest example = serializer.read(WinstromRequest.class, xml); assertThat(example.getAddressBooks().get(0)).isNotNull(); assertThat(example.getAddressBooks().get(0).getCode()).isEqualTo("PBENDA"); assertThat(example.getAddressBooks().get(0).getId()).isEqualTo(Arrays.asList("ext:33866089", "ext:1976780508")); assertThat(example.getAddressBooks().get(0).getName()).isEqualTo("Papírnictví Benda"); assertThat(example.getAddressBooks().get(0).getStreet()).isEqualTo("Plzeňská 65"); assertThat(example.getAddressBooks().get(0).getCity()).isEqualTo("Praha 5"); assertThat(example.getAddressBooks().get(0).getRegNo()).isEqualTo("12345678"); assertThat(example.getAddressBooks().get(0).getPostCode()).isEqualTo("150 00"); assertThat(example.getAddressBooks().get(0).getVatId()).isEqualTo("CZ7002051235"); assertThat(example.getIssuedInvoices().get(0)).isNotNull(); assertThat(example.getIssuedInvoices().get(0).getCompany()).isEqualTo("code:PBENDA"); assertThat(example.getIssuedInvoices().get(0).getDocumentType()).isEqualTo("code:FAKTURA"); } @Test public void parseFromObjectToXml() throws Exception { String xml = "<winstrom version=\"1.0\">\n" + " <adresar>\n" + " <id>123</id>\n" + " <ic>12345678</ic>\n" + " <psc>150 </psc>\n" + " <nazev>Papírnictví</nazev>\n" + " <mesto>Praha </mesto>\n" + " <dic>CZ7002051235</dic>\n" + " <ulice>Plzeňská</ulice>\n" + " <kod>PBENDA</kod>\n" + " </adresar>\n" + " <faktura-vydana>\n" + " <id>456</id>\n" + " <typDokl>code:FAKTURA</typDokl>\n" + " <firma>code:PBENDA</firma>\n" + " </faktura-vydana>\n" + "</winstrom>"; WinstromRequest envelope = WinstromRequest.builder() .issuedInvoice( IssuedInvoice.builder() .id(Collections.singletonList("456")) .company("code:PBENDA") .documentType("code:FAKTURA") .build()) .addressBook( AddressBook.builder() .code("PBENDA") .id(Collections.singletonList("123")) .name("Papírnictví") .street("Plzeňská") .city("Praha ") .postCode("150 ") .regNo("12345678") .vatId("CZ7002051235") .build()) .build(); ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = new Persister(Factory.matchers()); serializer.write(envelope, result); assertThat(result.toString()).isXmlEqualTo(xml); } @Test public void createInvoiceWithItems() throws Exception { WinstromRequest envelope = WinstromRequest.builder() .issuedInvoice(IssuedInvoice.builder() .company("code:ABCFIRM1#") .documentType("code:FAKTURA") .issued(LocalDate.of(2017, 4, 2)) .orderNumber("123456789") .items(new IssuedInvoiceItems( IssuedInvoiceItem.builder() .name("Bla bla jizdne") .amount(ONE) .sumVat(BigDecimal.valueOf(1500)) .unitPrice(BigDecimal.valueOf(7500)) .sumTotal(BigDecimal.valueOf(9000)) .priceKind(PriceKind.withVat) .vatRate(BigDecimal.valueOf(21)).build() )) .build()).build(); // Maybe you have to correct this or use another / no Locale ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = Factory.persister(); serializer.write(envelope, result); String xml = "<winstrom version=\"1.0\">\n" + " <faktura-vydana>\n" + " <typDokl>code:FAKTURA</typDokl>\n" + " <firma>code:ABCFIRM1#</firma>\n" + " <datVyst>2017-04-02</datVyst>\n" + " <polozkyFaktury removeAll=\"false\">\n" + " <faktura-vydana-polozka>\n" + " <nazev>Bla bla jizdne</nazev>\n" + " <mnozBaleni>1</mnozBaleni>\n" + " <szbDph>21</szbDph>\n" + " <sumDph>1500</sumDph>\n" + " <sumCelkem>9000</sumCelkem>\n" + " <cenaMj>7500</cenaMj>\n" + " <typCenyDphK>typCeny.sDphKoef</typCenyDphK>\n" + " </faktura-vydana-polozka>\n" + " </polozkyFaktury>\n" + " <cisObj>123456789</cisObj>" + " </faktura-vydana>\n" + "</winstrom>"; assertThat(result.toString()).isXmlEqualTo(xml); } @Test public void LocalDateIsParsed() throws Exception { WinstromRequest envelope = WinstromRequest.builder() .issuedInvoice(IssuedInvoice.builder() .issued(LocalDate.of(2017, 4, 2)) .build()).build(); ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = Factory.persister(); serializer.write(envelope, result); String xml = "<winstrom version=\"1.0\">\n" + " <faktura-vydana>\n" + " <datVyst>2017-04-02</datVyst>\n" + " </faktura-vydana>\n" + "</winstrom>"; assertThat(result.toString()).isXmlEqualTo(xml); } @Test public void invoiceWithAddressBook() throws Exception { WinstromRequest envelope = WinstromRequest.builder() .addressBook(AddressBook.builder() .name("Československá obchodní banka, a. s.") .vatId("CZ00001350") .regNo("00001350") .city("Praha 5") .street("Radlická 333/150") .postCode("15057") .build()) .issuedInvoice(IssuedInvoice.builder() .company("code:ČESKOSLOVENSKÁ0") .documentType("code:FAKTURA") .items(new IssuedInvoiceItems( IssuedInvoiceItem.builder() .name("Bla bla jizdne") .amount(ONE) .sumVat(BigDecimal.valueOf(1500)) .unitPrice(BigDecimal.valueOf(7500)) .sumTotal(BigDecimal.valueOf(9000)) .vatRate(BigDecimal.valueOf(21)).build() )) .build()).build(); ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = Factory.persister(); serializer.write(envelope, result); String xml = "<winstrom version=\"1.0\">\n" + " <adresar>\n" + " <ic>00001350</ic>\n" + " <psc>15057</psc>\n" + " <nazev>Československá obchodní banka, a. s.</nazev>\n" + " <mesto>Praha 5</mesto>\n" + " <dic>CZ00001350</dic>\n" + " <ulice>Radlická 333/150</ulice>\n" + " </adresar>\n" + " <faktura-vydana>\n" + " <typDokl>code:FAKTURA</typDokl>\n" + " <firma>code:ČESKOSLOVENSKÁ0</firma>\n" + " <polozkyFaktury removeAll=\"false\">\n" + " <faktura-vydana-polozka>\n" + " <nazev>Bla bla jizdne</nazev>\n" + " <mnozBaleni>1</mnozBaleni>\n" + " <szbDph>21</szbDph>\n" + " <sumDph>1500</sumDph>\n" + " <sumCelkem>9000</sumCelkem>\n" + " <cenaMj>7500</cenaMj>\n" + " </faktura-vydana-polozka>\n" + " </polozkyFaktury>\n" + " </faktura-vydana>\n" + "</winstrom>"; assertThat(result.toString()).isXmlEqualTo(xml); } @Test public void invoiceWithDeposits() throws Exception { String xml = "<winstrom version=\"1.0\">\n" + " <faktura-vydana>\n" + " <odpocty-zaloh class=\"java.util.Collections$SingletonList\">\n" + " <odpocet>\n" + " <id>ext:deposit</id>\n" + " <castkaMen>100</castkaMen>\n" + " <doklad>41</doklad>\n" + " </odpocet>\n" + " </odpocty-zaloh>\n" + " </faktura-vydana>\n" + "</winstrom>\n"; WinstromRequest envelope = WinstromRequest.builder() .issuedInvoice( IssuedInvoice.builder() .deposits(Collections.singletonList( Deposit.builder() .id("ext:deposit") .amount(BigDecimal.valueOf(100)) .deposit("41").build() )) .build() ).build(); ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = Factory.persister(); serializer.write(envelope, result); assertThat(result.toString()).isXmlEqualTo(xml); } @Test public void paymentStatusIsParsedCorrectly() throws Exception { String xml = "<winstrom version=\"1.0\">\n" + " <faktura-vydana>\n" + " <stavUhrK>stavUhr.uhrazenoRucne</stavUhrK>\n" + " </faktura-vydana>\n" + "</winstrom>\n"; WinstromRequest envelope = WinstromRequest.builder() .issuedInvoice( IssuedInvoice.builder() .paymentStatus(PaymentStatus.MANUALLY) .build() ).build(); ByteArrayOutputStream result = new ByteArrayOutputStream(); Serializer serializer = Factory.persister(); serializer.write(envelope, result); assertThat(result.toString()).isXmlEqualTo(xml); } }
apache-2.0
dkpro/dkpro-lab
dkpro-lab-uima/src/main/java/org/dkpro/lab/uima/task/package-info.java
916
/******************************************************************************* * Copyright 2013 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * 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. ******************************************************************************/ /** * UIMA tasks and access to the task context from UIMA. */ package org.dkpro.lab.uima.task;
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/modules/rmi2/src/ar/org/fitc/test/rmi/TestRMISecurityManager.java
2411
/* * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Hugo Beilis * @author Osvaldo Demo * @author Jorge Rafael * @version 1.0 */ package ar.org.fitc.test.rmi; import java.rmi.RMISecurityManager; import java.security.Permission; import junit.framework.TestCase; public class TestRMISecurityManager extends TestCase { public static void main(String[] args) { } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } /* * Test method for 'java.rmi.RMISecurityManager.RMISecurityManager()' */ public void testRMISecurityManager001() { try { assertTrue(new RMISecurityManager() instanceof RMISecurityManager); } catch (Throwable e) { fail("Failed with:" + e); } } public void testRMISecurityManager002() { SecurityManager smOld = System.getSecurityManager(); try { SecurityManager sm = new SecurityManager() { boolean allow = false; public void checkPermission(Permission perm) { if (!allow) { allow = true; throw new SecurityException( "No, No, No, you can't do that."); } } }; System.setSecurityManager(sm); new RMISecurityManager(); fail("SecurityMAnager not allow the first use"); } catch (SecurityException e) { } catch (Throwable e) { fail("Failed with:" + e); } finally { System.setSecurityManager(smOld); } } }
apache-2.0
madhur/GAnalytics
src/in/co/madhur/ganalyticsdashclock/API/GMetric.java
470
package in.co.madhur.ganalyticsdashclock.API; import android.util.Log; import in.co.madhur.ganalyticsdashclock.Consts; import in.co.madhur.ganalyticsdashclock.Consts.ANALYTICS_METRICS; public class GMetric extends GType { public GMetric() { } public GMetric(String Id, String Name) { super(Id, Name); } public GMetric(ANALYTICS_METRICS Id, String Name) { super(Id.toString(), Name); } @Override public String toString() { return Name; } }
apache-2.0
IHTSDO/snow-owl
snomed/com.b2international.snowowl.snomed.importer.rf2/src/com/b2international/snowowl/snomed/importer/rf2/model/ComponentImportUnit.java
2474
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.importer.rf2.model; import static com.google.common.base.Preconditions.checkNotNull; import java.io.File; import com.b2international.snowowl.snomed.importer.AbstractImportUnit; import com.b2international.snowowl.snomed.importer.Importer; import com.google.common.collect.Ordering; /** * An {@link AbstractImportUnit} for SNOMED CT components. Carries the effective time, * the component type, the location of the release slice and the number of * records. */ public class ComponentImportUnit extends AbstractImportUnit { public static final Ordering<AbstractImportUnit> ORDERING = EffectiveTimeUnitOrdering.INSTANCE.compound(TypeUnitOrdering.INSTANCE); private String effectiveTimeKey; private final ComponentImportType type; private final File unitFile; private final int recordCount; public ComponentImportUnit(final Importer parent, final String effectiveTimeKey, final ComponentImportType type, final File unitFile, final int recordCount) { super(parent); this.effectiveTimeKey = checkNotNull(effectiveTimeKey, "effectiveTimeKey"); this.type = checkNotNull(type, "type"); this.unitFile = checkNotNull(unitFile, "unitFile"); this.recordCount = recordCount; } public String getEffectiveTimeKey() { return effectiveTimeKey; } public void setEffectiveTimeKey(String effectiveTimeKey) { this.effectiveTimeKey = effectiveTimeKey; } public ComponentImportType getType() { return type; } public File getUnitFile() { return unitFile; } public int getRecordCount() { return recordCount; } @Override public String toString() { return String.format("ComponentImportUnit [importer=%s, effectiveTimeKey=%s, type=%s, unitFile=%s, recordCount=%d]", getImporter(), getEffectiveTimeKey(), getType(), getUnitFile(), getRecordCount()); } }
apache-2.0
ldp4j/ldp4j
framework/application/api/src/main/java/org/ldp4j/application/data/ImmutableDurationLiteral.java
2914
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the LDP4j Project: * http://www.ldp4j.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2014-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.ldp4j.framework:ldp4j-application-api:0.2.2 * Bundle : ldp4j-application-api-0.2.2.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.ldp4j.application.data; import java.net.URI; import java.util.Objects; import org.joda.time.Duration; import com.google.common.base.MoreObjects; final class ImmutableDurationLiteral implements DurationLiteral { private static final long serialVersionUID = -7312919003663624256L; private final Duration duration; private final URI dataType; ImmutableDurationLiteral(Duration duration, URI dataType) { this.duration = duration; this.dataType = dataType; } /** * {@inheritDoc} */ @Override public void accept(ValueVisitor visitor) { visitor.visitLiteral(this); } /** * {@inheritDoc} */ @Override public Duration get() { return this.duration; } /** * {@inheritDoc} */ @Override public void accept(LiteralVisitor visitor) { visitor.visitTypedLiteral(this); } /** * {@inheritDoc} */ @Override public URI type() { return this.dataType; } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.duration,this.dataType); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { boolean result=false; if(obj instanceof TypedLiteral) { TypedLiteral<?> that=(TypedLiteral<?>)obj; result= Objects.equals(this.duration, that.get()) && Objects.equals(this.dataType, that.type()) && !(obj instanceof LanguageLiteral); } return result; } /** * {@inheritDoc} */ @Override public String toString() { return MoreObjects. toStringHelper(getClass()). add("duration",this.duration). add("dataType", this.dataType). toString(); } }
apache-2.0
SUPERCILEX/FirebaseUI-Android
auth/src/main/java/com/firebase/ui/auth/util/data/PhoneNumberUtils.java
19276
/* * Copyright (C) 2015 Twitter, 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. * * Modifications copyright (C) 2017 Google Inc */ package com.firebase.ui.auth.util.data; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.SparseArray; import com.firebase.ui.auth.data.model.CountryInfo; import com.firebase.ui.auth.data.model.PhoneNumber; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class PhoneNumberUtils { private static final int DEFAULT_COUNTRY_CODE_INT = 1; private static final String DEFAULT_COUNTRY_CODE = String.valueOf(DEFAULT_COUNTRY_CODE_INT); private static final Locale DEFAULT_LOCALE = Locale.US; private static final CountryInfo DEFAULT_COUNTRY = new CountryInfo(DEFAULT_LOCALE, DEFAULT_COUNTRY_CODE_INT); private static final int MAX_COUNTRY_CODES = 215; private static final int MAX_COUNTRIES = 248; private static final int MAX_LENGTH_COUNTRY_CODE = 3; private static final SparseArray<List<String>> COUNTRY_TO_REGION_CODES = createCountryCodeToRegionCodeMap(); private static Map<String, Integer> COUNTRY_TO_ISO_CODES; /** * This method works as follow: <ol><li>When the android version is LOLLIPOP or greater, the * reliable {{@link android.telephony.PhoneNumberUtils#formatNumberToE164}} is used to * format.</li> <li>For lower versions, we construct a value with the input phone number * stripped of non numeric characters and prefix it with a "+" and country code</li> </ol> * * @param phoneNumber that may or may not itself have country code * @param countryInfo must have locale with ISO 3166 2-letter code for country */ public static String format(@NonNull String phoneNumber, @NonNull CountryInfo countryInfo) { if (phoneNumber.startsWith("+")) { return phoneNumber; } else { return "+" + String.valueOf(countryInfo.getCountryCode()) + phoneNumber.replaceAll("[^\\d.]", ""); } } /** * This method uses the country returned by {@link #getCurrentCountryInfo(Context)} to format * the phone number. Internally invokes {@link #format(String, CountryInfo)} * * @param phoneNumber that may or may not itself have country code */ @Nullable public static String formatUsingCurrentCountry(@NonNull String phoneNumber, Context context) { return format(phoneNumber, getCurrentCountryInfo(context)); } @NonNull public static CountryInfo getCurrentCountryInfo(@NonNull Context context) { Locale locale = getSimBasedLocale(context); if (locale == null) { locale = getOSLocale(); } if (locale == null) { return DEFAULT_COUNTRY; } Integer countryCode = getCountryCode(locale.getCountry()); return countryCode == null ? DEFAULT_COUNTRY : new CountryInfo(locale, countryCode); } /** * This method should not be called on UI thread. Potentially creates a country code by iso map * which can take long in some devices * * @param providedPhoneNumber works best when formatted as e164 * @return an instance of the PhoneNumber using the SIM information */ public static PhoneNumber getPhoneNumber(@NonNull String providedPhoneNumber) { String countryCode = DEFAULT_COUNTRY_CODE; String countryIso = DEFAULT_LOCALE.getCountry(); String phoneNumber = providedPhoneNumber; if (providedPhoneNumber.startsWith("+")) { countryCode = getCountryCodeForPhoneNumberOrDefault(providedPhoneNumber); countryIso = getCountryIsoForCountryCode(countryCode); phoneNumber = stripCountryCode(providedPhoneNumber, countryCode); } return new PhoneNumber(phoneNumber, countryIso, countryCode); } public static boolean isValid(@NonNull String number) { return number.startsWith("+") && getCountryCodeForPhoneNumber(number) != null; } public static boolean isValidIso(@Nullable String iso) { return getCountryCode(iso) != null; } /** * @see #getPhoneNumber(String) */ public static PhoneNumber getPhoneNumber( @NonNull String providedCountryIso, @NonNull String providedNationalNumber) { Integer countryCode = getCountryCode(providedCountryIso); if (countryCode == null) { // Invalid ISO supplied: countryCode = DEFAULT_COUNTRY_CODE_INT; providedCountryIso = DEFAULT_COUNTRY_CODE; } // National number shouldn't include '+', but just in case: providedNationalNumber = stripPlusSign(providedNationalNumber); return new PhoneNumber( providedNationalNumber, providedCountryIso, String.valueOf(countryCode)); } @Nullable public static Integer getCountryCode(String countryIso) { if (COUNTRY_TO_ISO_CODES == null) { initCountryCodeByIsoMap(); } return countryIso == null ? null : COUNTRY_TO_ISO_CODES.get(countryIso.toUpperCase(Locale.getDefault())); } public static Map<String, Integer> getImmutableCountryIsoMap() { if (COUNTRY_TO_ISO_CODES == null) { initCountryCodeByIsoMap(); } return COUNTRY_TO_ISO_CODES; } private static String getCountryIsoForCountryCode(String countryCode) { List<String> countries = COUNTRY_TO_REGION_CODES.get(Integer.parseInt(countryCode)); if (countries != null) { return countries.get(0); } return DEFAULT_LOCALE.getCountry(); } @Nullable public static List<String> getCountryIsosFromCountryCode(String countryCode) { return !isValid(countryCode) ? null : COUNTRY_TO_REGION_CODES.get(Integer.parseInt(countryCode.substring(1))); } /** * Country code extracted using shortest matching prefix like libPhoneNumber. See: * https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/src/com * /google/i18n/phonenumbers/PhoneNumberUtil.java#L2395 */ @Nullable private static String getCountryCodeForPhoneNumber(String normalizedPhoneNumber) { String phoneWithoutPlusPrefix = normalizedPhoneNumber.replaceFirst("^\\+", ""); int numberLength = phoneWithoutPlusPrefix.length(); for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) { String potentialCountryCode = phoneWithoutPlusPrefix.substring(0, i); Integer countryCodeKey = Integer.valueOf(potentialCountryCode); if (COUNTRY_TO_REGION_CODES.indexOfKey(countryCodeKey) >= 0) { return potentialCountryCode; } } return null; } @NonNull private static String getCountryCodeForPhoneNumberOrDefault(String normalizedPhoneNumber) { String code = getCountryCodeForPhoneNumber(normalizedPhoneNumber); return code == null ? DEFAULT_COUNTRY_CODE : code; } private static String stripCountryCode(String phoneNumber, String countryCode) { return phoneNumber.replaceFirst("^\\+?" + countryCode, ""); } private static String stripPlusSign(String phoneNumber) { return phoneNumber.replaceFirst("^\\+?", ""); } private static Locale getSimBasedLocale(@NonNull Context context) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String countryIso = tm != null ? tm.getSimCountryIso() : null; return TextUtils.isEmpty(countryIso) ? null : new Locale("", countryIso); } private static Locale getOSLocale() { return Locale.getDefault(); } private static SparseArray<List<String>> createCountryCodeToRegionCodeMap() { SparseArray<List<String>> map = new SparseArray<>(MAX_COUNTRY_CODES); map.put(1, asList( "US", "AG", "AI", "AS", "BB", "BM", "BS", "CA", "DM", "DO", "GD", "GU", "JM", "KN", "KY", "LC", "MP", "MS", "PR", "SX", "TC", "TT", "VC", "VG", "VI")); map.put(7, asList("RU", "KZ")); map.put(20, singletonList("EG")); map.put(27, singletonList("ZA")); map.put(30, singletonList("GR")); map.put(31, singletonList("NL")); map.put(32, singletonList("BE")); map.put(33, singletonList("FR")); map.put(34, singletonList("ES")); map.put(36, singletonList("HU")); map.put(39, singletonList("IT")); map.put(40, singletonList("RO")); map.put(41, singletonList("CH")); map.put(43, singletonList("AT")); map.put(44, asList("GB", "GG", "IM", "JE")); map.put(45, singletonList("DK")); map.put(46, singletonList("SE")); map.put(47, asList("NO", "SJ")); map.put(48, singletonList("PL")); map.put(49, singletonList("DE")); map.put(51, singletonList("PE")); map.put(52, singletonList("MX")); map.put(53, singletonList("CU")); map.put(54, singletonList("AR")); map.put(55, singletonList("BR")); map.put(56, singletonList("CL")); map.put(57, singletonList("CO")); map.put(58, singletonList("VE")); map.put(60, singletonList("MY")); map.put(61, asList("AU", "CC", "CX")); map.put(62, singletonList("ID")); map.put(63, singletonList("PH")); map.put(64, singletonList("NZ")); map.put(65, singletonList("SG")); map.put(66, singletonList("TH")); map.put(81, singletonList("JP")); map.put(82, singletonList("KR")); map.put(84, singletonList("VN")); map.put(86, singletonList("CN")); map.put(90, singletonList("TR")); map.put(91, singletonList("IN")); map.put(92, singletonList("PK")); map.put(93, singletonList("AF")); map.put(94, singletonList("LK")); map.put(95, singletonList("MM")); map.put(98, singletonList("IR")); map.put(211, singletonList("SS")); map.put(212, asList("MA", "EH")); map.put(213, singletonList("DZ")); map.put(216, singletonList("TN")); map.put(218, singletonList("LY")); map.put(220, singletonList("GM")); map.put(221, singletonList("SN")); map.put(222, singletonList("MR")); map.put(223, singletonList("ML")); map.put(224, singletonList("GN")); map.put(225, singletonList("CI")); map.put(226, singletonList("BF")); map.put(227, singletonList("NE")); map.put(228, singletonList("TG")); map.put(229, singletonList("BJ")); map.put(230, singletonList("MU")); map.put(231, singletonList("LR")); map.put(232, singletonList("SL")); map.put(233, singletonList("GH")); map.put(234, singletonList("NG")); map.put(235, singletonList("TD")); map.put(236, singletonList("CF")); map.put(237, singletonList("CM")); map.put(238, singletonList("CV")); map.put(239, singletonList("ST")); map.put(240, singletonList("GQ")); map.put(241, singletonList("GA")); map.put(242, singletonList("CG")); map.put(243, singletonList("CD")); map.put(244, singletonList("AO")); map.put(245, singletonList("GW")); map.put(246, singletonList("IO")); map.put(247, singletonList("AC")); map.put(248, singletonList("SC")); map.put(249, singletonList("SD")); map.put(250, singletonList("RW")); map.put(251, singletonList("ET")); map.put(252, singletonList("SO")); map.put(253, singletonList("DJ")); map.put(254, singletonList("KE")); map.put(255, singletonList("TZ")); map.put(256, singletonList("UG")); map.put(257, singletonList("BI")); map.put(258, singletonList("MZ")); map.put(260, singletonList("ZM")); map.put(261, singletonList("MG")); map.put(262, asList("RE", "YT")); map.put(263, singletonList("ZW")); map.put(264, singletonList("NA")); map.put(265, singletonList("MW")); map.put(266, singletonList("LS")); map.put(267, singletonList("BW")); map.put(268, singletonList("SZ")); map.put(269, singletonList("KM")); map.put(290, asList("SH", "TA")); map.put(291, singletonList("ER")); map.put(297, singletonList("AW")); map.put(298, singletonList("FO")); map.put(299, singletonList("GL")); map.put(350, singletonList("GI")); map.put(351, singletonList("PT")); map.put(352, singletonList("LU")); map.put(353, singletonList("IE")); map.put(354, singletonList("IS")); map.put(355, singletonList("AL")); map.put(356, singletonList("MT")); map.put(357, singletonList("CY")); map.put(358, asList("FI", "AX")); map.put(359, singletonList("BG")); map.put(370, singletonList("LT")); map.put(371, singletonList("LV")); map.put(372, singletonList("EE")); map.put(373, singletonList("MD")); map.put(374, singletonList("AM")); map.put(375, singletonList("BY")); map.put(376, singletonList("AD")); map.put(377, singletonList("MC")); map.put(378, singletonList("SM")); map.put(379, singletonList("VA")); map.put(380, singletonList("UA")); map.put(381, singletonList("RS")); map.put(382, singletonList("ME")); map.put(385, singletonList("HR")); map.put(386, singletonList("SI")); map.put(387, singletonList("BA")); map.put(389, singletonList("MK")); map.put(420, singletonList("CZ")); map.put(421, singletonList("SK")); map.put(423, singletonList("LI")); map.put(500, singletonList("FK")); map.put(501, singletonList("BZ")); map.put(502, singletonList("GT")); map.put(503, singletonList("SV")); map.put(504, singletonList("HN")); map.put(505, singletonList("NI")); map.put(506, singletonList("CR")); map.put(507, singletonList("PA")); map.put(508, singletonList("PM")); map.put(509, singletonList("HT")); map.put(590, asList("GP", "BL", "MF")); map.put(591, singletonList("BO")); map.put(592, singletonList("GY")); map.put(593, singletonList("EC")); map.put(594, singletonList("GF")); map.put(595, singletonList("PY")); map.put(596, singletonList("MQ")); map.put(597, singletonList("SR")); map.put(598, singletonList("UY")); map.put(599, asList("CW", "BQ")); map.put(670, singletonList("TL")); map.put(672, singletonList("NF")); map.put(673, singletonList("BN")); map.put(674, singletonList("NR")); map.put(675, singletonList("PG")); map.put(676, singletonList("TO")); map.put(677, singletonList("SB")); map.put(678, singletonList("VU")); map.put(679, singletonList("FJ")); map.put(680, singletonList("PW")); map.put(681, singletonList("WF")); map.put(682, singletonList("CK")); map.put(683, singletonList("NU")); map.put(685, singletonList("WS")); map.put(686, singletonList("KI")); map.put(687, singletonList("NC")); map.put(688, singletonList("TV")); map.put(689, singletonList("PF")); map.put(690, singletonList("TK")); map.put(691, singletonList("FM")); map.put(692, singletonList("MH")); map.put(800, singletonList("001")); map.put(808, singletonList("001")); map.put(850, singletonList("KP")); map.put(852, singletonList("HK")); map.put(853, singletonList("MO")); map.put(855, singletonList("KH")); map.put(856, singletonList("LA")); map.put(870, singletonList("001")); map.put(878, singletonList("001")); map.put(880, singletonList("BD")); map.put(881, singletonList("001")); map.put(882, singletonList("001")); map.put(883, singletonList("001")); map.put(886, singletonList("TW")); map.put(888, singletonList("001")); map.put(960, singletonList("MV")); map.put(961, singletonList("LB")); map.put(962, singletonList("JO")); map.put(963, singletonList("SY")); map.put(964, singletonList("IQ")); map.put(965, singletonList("KW")); map.put(966, singletonList("SA")); map.put(967, singletonList("YE")); map.put(968, singletonList("OM")); map.put(970, singletonList("PS")); map.put(971, singletonList("AE")); map.put(972, singletonList("IL")); map.put(973, singletonList("BH")); map.put(974, singletonList("QA")); map.put(975, singletonList("BT")); map.put(976, singletonList("MN")); map.put(977, singletonList("NP")); map.put(979, singletonList("001")); map.put(992, singletonList("TJ")); map.put(993, singletonList("TM")); map.put(994, singletonList("AZ")); map.put(995, singletonList("GE")); map.put(996, singletonList("KG")); map.put(998, singletonList("UZ")); return map; } private static void initCountryCodeByIsoMap() { Map<String, Integer> map = new HashMap<>(MAX_COUNTRIES); for (int i = 0; i < COUNTRY_TO_REGION_CODES.size(); i++) { int code = COUNTRY_TO_REGION_CODES.keyAt(i); List<String> regions = COUNTRY_TO_REGION_CODES.get(code); for (String region : regions) { if (region.equals("001")) { continue; } if (map.containsKey(region)) { throw new IllegalStateException("Duplicate regions for country code: " + code); } map.put(region, code); } } // TODO Figure out why these exceptions exist. // This map used to be hardcoded so this is the diff from the generated version. map.remove("TA"); map.put("HM", 672); map.put("GS", 500); map.put("XK", 381); COUNTRY_TO_ISO_CODES = Collections.unmodifiableMap(map); } }
apache-2.0
nkasvosve/beyondj
beyondj-consul-rest-client/src/main/java/com/lenox/consul/HealthService.java
3218
package com.lenox.consul; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.request.GetRequest; import org.json.JSONArray; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class HealthService extends ConsulChain { public static final String INDEX_HEADER = "X-Consul-Index" .toLowerCase(); public HealthService(Consul c) { super(c); } /** * Calls consul's health check for service, only returns services with passing health checks * * https://www.consul.io/docs/agent/http/health.html#health_service * @param name Service name to look up * @return List of HealServiceChecks * @throws ConsulException */ public List<HealthServiceCheck> check(String name) throws ConsulException { return check(name, null, 30, true).getServiceList(); } /** * Call the health service check consul end point * * When consul index is specified the consul service will wait to to return services until either the waitTime has expired or * a change has happened to the specified service. * * More details: https://www.consul.io/docs/agent/watches.html * * @param name Service name to look up * @param consulIndex When not null passes this index to consul to allow a blocked query * @param waitTimeSeconds time to pass to consul to wait for changes to a service * @param passing if true only returns services that are passing their health check. * @return Response object with Consul-Index and a list of services * @throws ConsulException */ public HealthServiceCheckResponse check(String name, String consulIndex, int waitTimeSeconds, boolean passing) throws ConsulException { HttpResponse<String> resp; GetRequest request = Unirest.get(consul().getUrl() + EndpointCategory.HealthService.getUri() + "{name}") .routeParam("name", name); if (consulIndex != null) { request.queryString("index", consulIndex); request.queryString("wait", waitTimeSeconds + "s"); } if (passing) { request.queryString("passing", "true"); } try { resp = request.asStringAsync().get((long)Math.ceil(1.1f * waitTimeSeconds), TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new ConsulException(e); } String newConsulIndex = resp.getHeaders().getFirst(INDEX_HEADER); List<HealthServiceCheck> serviceChecks = new ArrayList<>(); if (resp.getStatus() >= 500) { throw new ConsulException("Error Status Code: " + resp.getStatus() + " body: " + resp.getBody()); } JSONArray arr = parseJson(resp.getBody()).getArray(); for (int i = 0; i < arr.length(); i++) { serviceChecks.add(new HealthServiceCheck(arr.getJSONObject(i))); } return new HealthServiceCheckResponse(newConsulIndex, serviceChecks); } }
apache-2.0
yenki/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/Metadata.java
9236
/** * Copyright 2012-2015 XebiaLabs B.V. * * 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.xebialabs.overcast.support.libvirt; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import static com.xebialabs.overcast.support.libvirt.JDomUtil.getElementText; /** * Utility to deal with the metadata we set on Libvirt Domains. Metadata can be for a provisioned domain or for just a clone. * <p>For a provisioned domain it looks like: * <pre> * &lt;metadata&gt; * &lt;overcast_metdata xmlns=&quot;http://www.xebialabs.com/overcast/metadata/v1&quot;&gt; * &lt;parent_domain&gt;centos6&lt;/parent_domain&gt; * &lt;provisioned_with&gt;/mnt/puppet/Vagrantfile&lt;/provisioned_with&gt; * &lt;provisioned_checksum&gt;2008-10-31T15:07:38.6875000-05:00&lt;/provisioned_checksum&gt; * &lt;creation_time&gt;2008-10-31T15:07:38.6875000-05:00&lt;/provisioned_at&gt; * &lt;/overcast_metdata&gt; * &lt;/metadata&gt; * </pre> * <p>For a cloned domain it looks like: * <pre> * &lt;metadata&gt; * &lt;overcast_metdata xmlns=&quot;http://www.xebialabs.com/overcast/metadata/v1&quot;&gt; * &lt;parent_domain&gt;centos6&lt;/parent_domain&gt; * &lt;creation_time&gt;2008-10-31T15:07:38.6875000-05:00&lt;/provisioned_at&gt; * &lt;/overcast_metdata&gt; * &lt;/metadata&gt; * </pre> */ public class Metadata { private static final String XML_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static final String METADATA_NS_V1 = "http://www.xebialabs.com/overcast/metadata/v1"; public static final String METADATA = "metadata"; public static final String OVERCAST_METADATA = "overcast_metadata"; public static final String CREATION_TIME = "creation_time"; public static final String PROVISIONED_CHECKSUM = "provisioned_checksum"; public static final String PROVISIONED_WITH = "provisioned_with"; public static final String PARENT_DOMAIN = "parent_domain"; private static final TimeZone METADATA_TIMEZONE = TimeZone.getTimeZone("UTC"); private final String parentDomain; private final String provisionedWith; private final String provisionedChecksum; private final Date creationTime; public Metadata(String parentDomain, String provisionedWith, String provisionedChecksum, Date creationTime) { Preconditions.checkNotNull(creationTime, "creationTime cannot be null"); this.parentDomain = checkArgument(parentDomain, "parentDomain"); this.provisionedWith = checkArgument(provisionedWith, "provisionedWith"); this.provisionedChecksum = checkArgument(provisionedChecksum, "provisionedChecksum"); this.creationTime = creationTime; } public Metadata(String parentDomain, Date creationTime) { Preconditions.checkNotNull(creationTime, "creationTime cannot be null"); this.parentDomain = checkArgument(parentDomain, "parentDomain"); this.creationTime = creationTime; this.provisionedWith = null; this.provisionedChecksum = null; } private static String checkArgument(String arg, String argName) { Preconditions.checkArgument(arg != null && !arg.isEmpty(), "%s cannot be null or empty", argName); return arg; } public String getParentDomain() { return parentDomain; } public String getProvisionedWith() { return provisionedWith; } public String getProvisionedChecksum() { return provisionedChecksum; } public Date getCreationTime() { return creationTime; } public boolean isProvisioned() { return provisionedWith != null; } /** * Extract {@link Metadata} from the domain XML. Throws {@link IllegalArgumentException} if the metadata is * malformed. * * @return the metadata or <code>null</code> if there's no metadata */ public static Metadata fromXml(Document domainXml) { try { SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT); Element metadata = getMetadataElement(domainXml); if (metadata == null) { return null; } Namespace ns = Namespace.getNamespace(METADATA_NS_V1); Element ocMetadata = metadata.getChild(OVERCAST_METADATA, ns); if (ocMetadata == null) { return null; } String parentDomain = getElementText(ocMetadata, PARENT_DOMAIN, ns); String creationTime = getElementText(ocMetadata, CREATION_TIME, ns); Date date = sdf.parse(creationTime); if(ocMetadata.getChild(PROVISIONED_WITH, ns) != null) { String provisionedWith = getElementText(ocMetadata, PROVISIONED_WITH, ns); String checkSum = getElementText(ocMetadata, PROVISIONED_CHECKSUM, ns); return new Metadata(parentDomain, provisionedWith, checkSum, date); } return new Metadata(parentDomain, date); } catch (ParseException e) { throw new IllegalArgumentException("Invalid date in metadata on domain", e); } } private static Element createProvisioningMetadata(String parentDomain, String provisionedWith, String provisionedChecksum, Date provisionedAt) { SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT); sdf.setTimeZone(METADATA_TIMEZONE); Element metadata = new Element(METADATA); Element ocmetadata = new Element(OVERCAST_METADATA, METADATA_NS_V1); metadata.addContent(ocmetadata); ocmetadata.addContent(new Element(PARENT_DOMAIN, METADATA_NS_V1).setText(parentDomain)); ocmetadata.addContent(new Element(PROVISIONED_WITH, METADATA_NS_V1).setText(provisionedWith)); ocmetadata.addContent(new Element(PROVISIONED_CHECKSUM, METADATA_NS_V1).setText(provisionedChecksum)); ocmetadata.addContent(new Element(CREATION_TIME, METADATA_NS_V1).setText(sdf.format(provisionedAt))); return metadata; } private static Element createCloningMetadata(String parentDomain, Date creationTime) { SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT); sdf.setTimeZone(METADATA_TIMEZONE); Element metadata = new Element(METADATA); Element ocmetadata = new Element(OVERCAST_METADATA, METADATA_NS_V1); metadata.addContent(ocmetadata); ocmetadata.addContent(new Element(PARENT_DOMAIN, METADATA_NS_V1).setText(parentDomain)); ocmetadata.addContent(new Element(CREATION_TIME, METADATA_NS_V1).setText(sdf.format(creationTime))); return metadata; } private static Element getMetadataElement(Document domainXml) { Element metadata = domainXml.getRootElement().getChild(METADATA); if (metadata == null) { return null; } return metadata; } public static void updateProvisioningMetadata(Document domainXml, String baseDomainName, String provisionCmd, String expirationTag, Date creationTime) { checkArgument(baseDomainName, "baseDomainName"); checkArgument(provisionCmd, "provisionCmd"); checkArgument(expirationTag, "expirationTag"); Preconditions.checkNotNull(creationTime, "creationTime must not be null"); Element element = getMetadataElement(domainXml); if (element != null) { domainXml.getRootElement().removeContent(element); } Element metadata = createProvisioningMetadata(baseDomainName, provisionCmd, expirationTag, creationTime); domainXml.getRootElement().addContent(metadata); } public static void updateCloneMetadata(Document domainXml, String baseDomainName, Date creationTime) { checkArgument(baseDomainName, "baseDomainName"); Preconditions.checkNotNull(creationTime, "creationTime must not be null"); Element element = getMetadataElement(domainXml); if (element != null) { domainXml.getRootElement().removeContent(element); } Element metadata = createCloningMetadata(baseDomainName, creationTime); domainXml.getRootElement().addContent(metadata); } @Override public String toString() { return Objects.toStringHelper(this) .add("parentDomain", parentDomain) .add("creationTime", creationTime) .add("provisionedChecksum", provisionedChecksum) .add("provisionedWith", provisionedWith).toString(); } }
apache-2.0
codders/k2-sling-fork
bundles/commons/log/src/main/java/org/apache/sling/commons/log/internal/slf4j/SlingLoggerWriter.java
10334
/* * 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.sling.commons.log.internal.slf4j; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; /** * The <code>SlingLoggerWriter</code> abstract the output writing functionality * for the Sling Logging implementation. This class is able to write to log * files and manage log file rotation for these files. Alternatively this class * supports writing to the standard output if no log file name is configured. */ class SlingLoggerWriter extends Writer { private static final long FACTOR_KB = 1024; private static final long FACTOR_MB = 1024 * FACTOR_KB; private static final long FACTOR_GB = 1024 * FACTOR_MB; /** * The string to place at the end of a line. This is a platform specific * string set from the <code>line.separator</code> system property. */ private static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * The PID of the configuration from which this instance has been * configured. */ private final String configurationPID; /** * The actual <code>Writer</code> to which this instance delegates any * message writes. */ private Writer delegatee; /** * The object on which access to this instance are serialized in * multi-threading environments. */ protected final Object lock = new Object(); /** * The <code>java.io.File</code> of the log or <code>null</code> if this * instance writes to the standard output. */ private File file; /** * The absolute path to the log file or <code>null</code> if this instance * writes to the standard output. */ private String path; /** * The maximum size of the log file after which the current log file is * rolled. This setting is ignored if logging to standard output. */ private long maxSize; /** * The maximum number of old rotated log files to keep. This setting is * ignored if logging to standard output. */ private int maxNum; /** * Creates a new instance of this class to be configured from the given * <code>configurationPID</code>. This new instance is not ready until * the {@link #configure(String, int, String)} method is being called. */ SlingLoggerWriter(String configurationPID) { this.configurationPID = configurationPID; } /** * (Re)configures this instance to log to the given file. * * @param logFileName The name of the file to log to or <code>null</code> * to log to the standard output. * @param fileNum The maximum number of old (rotated) files to keep. This is * ignored if <code>logFileName</code> is <code>null</code>. * @param fileSize The maximum size of the log file before rotating it. This * is ignored if <code>logFileName</code> is <code>null</code>. * @throws IOException May be thrown if the file indicated by * <code>logFileName</code> cannot be opened for writing. */ void configure(String logFileName, int fileNum, String fileSize) throws IOException { // lock this instance while reconfiguring it synchronized (lock) { // change the log file name (if reconfigured) if (logFileName == null || !logFileName.equals(path)) { // close the current file close(); if (logFileName == null) { this.path = null; this.file = null; } else { // make sure the file is absolute and derive the path from // there File file = new File(logFileName); if (!file.isAbsolute()) { file = file.getAbsoluteFile(); } this.path = file.getAbsolutePath(); this.file = file; } setDelegatee(createWriter()); } else { // make sure, everything is written flush(); } // assign new rotation values this.maxNum = fileNum; this.maxSize = convertMaxSizeSpec(fileSize); // check whether the new values cause different rotation checkRotate(); } } String getConfigurationPID() { return configurationPID; } String getPath() { return path; } long getMaxSize() { return maxSize; } int getMaxNum() { return maxNum; } // ---------- Writer Overwrite --------------------------------------------- @Override public void close() throws IOException { synchronized (lock) { if (delegatee != null) { flush(); delegatee.close(); delegatee = null; } } } @Override public void flush() throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.flush(); // check whether we have to rotate the log file checkRotate(); } } } @Override public void write(int c) throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.write(c); } } } @Override public void write(char[] cbuf) throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.write(cbuf); } } } @Override public void write(char[] cbuf, int off, int len) throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.write(cbuf, off, len); } } } @Override public void write(String str) throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.write(str); } } } @Override public void write(String str, int off, int len) throws IOException { synchronized (lock) { if (delegatee != null) { delegatee.write(str, off, len); } } } public void writeln() throws IOException { synchronized (lock) { write(LINE_SEPARATOR); flush(); } } // ---------- internal ----------------------------------------------------- static long convertMaxSizeSpec(String maxSize) { long factor; int len = maxSize.length() - 1; maxSize = maxSize.toUpperCase(); if (maxSize.endsWith("G")) { factor = FACTOR_GB; } else if (maxSize.endsWith("GB")) { factor = FACTOR_GB; len--; } else if (maxSize.endsWith("M")) { factor = FACTOR_MB; } else if (maxSize.endsWith("MB")) { factor = FACTOR_MB; len--; } else if (maxSize.endsWith("K")) { factor = FACTOR_KB; } else if (maxSize.endsWith("KB")) { factor = FACTOR_KB; len--; } else { factor = 1; len = -1; } if (len > 0) { maxSize = maxSize.substring(0, len); } try { return factor * Long.parseLong(maxSize); } catch (NumberFormatException nfe) { return 10 * 1024 * 1024; } } void setDelegatee(Writer delegatee) { synchronized (lock) { this.delegatee = delegatee; } } Writer getDelegatee() { synchronized (lock) { return delegatee; } } /** * Must be called while the lock is held !! */ private void checkRotate() throws IOException { if (file != null && file.length() > maxSize) { getDelegatee().close(); if (maxNum >= 0) { // remove oldest file File dstFile = new File(path + "." + maxNum); if (dstFile.exists()) { dstFile.delete(); } // rename next files for (int i = maxNum - 1; i >= 0; i--) { File srcFile = new File(path + "." + i); if (srcFile.exists()) { srcFile.renameTo(dstFile); } dstFile = srcFile; } // rename youngest file file.renameTo(dstFile); } else { // just remove the old file if we don't keep backups file.delete(); } // create new file setDelegatee(createWriter()); } } private Writer createWriter() throws IOException { if (file == null) { return new OutputStreamWriter(System.out) { @Override public void close() { // not really !! } }; } // ensure parent path of the file to create file.getParentFile().mkdirs(); // open the file in append mode to not overwrite an existing // log file from a previous instance running return new OutputStreamWriter(new FileOutputStream(file, true)); } }
apache-2.0
mghosh4/druid
processing/src/test/java/org/apache/druid/segment/virtual/ExpressionVectorSelectorsTest.java
10117
/* * 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.druid.segment.virtual; import com.google.common.collect.ImmutableList; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.math.expr.Expr; import org.apache.druid.math.expr.ExprMacroTable; import org.apache.druid.math.expr.ExprType; import org.apache.druid.math.expr.Parser; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.expression.TestExprMacroTable; import org.apache.druid.segment.ColumnInspector; import org.apache.druid.segment.ColumnValueSelector; import org.apache.druid.segment.Cursor; import org.apache.druid.segment.QueryableIndex; import org.apache.druid.segment.QueryableIndexStorageAdapter; import org.apache.druid.segment.VirtualColumns; import org.apache.druid.segment.column.ColumnCapabilities; import org.apache.druid.segment.generator.GeneratorBasicSchemas; import org.apache.druid.segment.generator.GeneratorSchemaInfo; import org.apache.druid.segment.generator.SegmentGenerator; import org.apache.druid.segment.vector.SingleValueDimensionVectorSelector; import org.apache.druid.segment.vector.VectorCursor; import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.partition.LinearShardSpec; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @RunWith(Parameterized.class) public class ExpressionVectorSelectorsTest { private static List<String> EXPRESSIONS = ImmutableList.of( "long1 * long2", "long1 * nonexistent", "double1 * double3", "float1 + float3", "(long1 - long4) / double3", "long5 * float3 * long1 * long4 * double1", "long5 * double3 * long1 * long4 * double1", "max(double3, double5)", "max(nonexistent, double5)", "min(double4, double1)", "cos(float3)", "sin(long4)", "parse_long(string1)", "parse_long(nonexistent)", "parse_long(string1) * double3", "parse_long(string5) * parse_long(string1)", "parse_long(string5) * parse_long(string1) * double3", "'string constant'", "1", "192412.24124", "null", "long2", "float2", "double2", "string3", "string1 + string3", "concat(string1, string2, string3)", "concat(string1, 'x')", "concat(string1, nonexistent)" ); private static final int ROWS_PER_SEGMENT = 100_000; private static QueryableIndex INDEX; private static Closer CLOSER; @BeforeClass public static void setupClass() { CLOSER = Closer.create(); final GeneratorSchemaInfo schemaInfo = GeneratorBasicSchemas.SCHEMA_MAP.get("expression-testbench"); final DataSegment dataSegment = DataSegment.builder() .dataSource("foo") .interval(schemaInfo.getDataInterval()) .version("1") .shardSpec(new LinearShardSpec(0)) .size(0) .build(); final SegmentGenerator segmentGenerator = CLOSER.register(new SegmentGenerator()); INDEX = CLOSER.register( segmentGenerator.generate(dataSegment, schemaInfo, Granularities.HOUR, ROWS_PER_SEGMENT) ); } @AfterClass public static void teardownClass() throws IOException { CLOSER.close(); } @Parameterized.Parameters(name = "expression = {0}") public static Iterable<?> constructorFeeder() { return EXPRESSIONS.stream().map(x -> new Object[]{x}).collect(Collectors.toList()); } private ExprType outputType; private String expression; public ExpressionVectorSelectorsTest(String expression) { this.expression = expression; } @Before public void setup() { Expr parsed = Parser.parse(expression, ExprMacroTable.nil()); outputType = parsed.getOutputType( new ColumnInspector() { @Nullable @Override public ColumnCapabilities getColumnCapabilities(String column) { return QueryableIndexStorageAdapter.getColumnCapabilities(INDEX, column); } } ); if (outputType == null) { outputType = ExprType.STRING; } } @Test public void sanityTestVectorizedExpressionSelector() { sanityTestVectorizedExpressionSelectors(expression, outputType, INDEX, CLOSER, ROWS_PER_SEGMENT); } public static void sanityTestVectorizedExpressionSelectors( String expression, @Nullable ExprType outputType, QueryableIndex index, Closer closer, int rowsPerSegment ) { final List<Object> results = new ArrayList<>(rowsPerSegment); final VirtualColumns virtualColumns = VirtualColumns.create( ImmutableList.of( new ExpressionVirtualColumn( "v", expression, ExprType.toValueType(outputType), TestExprMacroTable.INSTANCE ) ) ); final QueryableIndexStorageAdapter storageAdapter = new QueryableIndexStorageAdapter(index); VectorCursor cursor = storageAdapter.makeVectorCursor( null, index.getDataInterval(), virtualColumns, false, 512, null ); ColumnCapabilities capabilities = virtualColumns.getColumnCapabilities(storageAdapter, "v"); int rowCount = 0; if (capabilities.isDictionaryEncoded().isTrue()) { SingleValueDimensionVectorSelector selector = cursor.getColumnSelectorFactory().makeSingleValueDimensionSelector( DefaultDimensionSpec.of("v") ); while (!cursor.isDone()) { int[] row = selector.getRowVector(); for (int i = 0; i < selector.getCurrentVectorSize(); i++, rowCount++) { results.add(selector.lookupName(row[i])); } cursor.advance(); } } else { VectorValueSelector selector = null; VectorObjectSelector objectSelector = null; if (outputType != null && outputType.isNumeric()) { selector = cursor.getColumnSelectorFactory().makeValueSelector("v"); } else { objectSelector = cursor.getColumnSelectorFactory().makeObjectSelector("v"); } while (!cursor.isDone()) { boolean[] nulls; switch (outputType) { case LONG: nulls = selector.getNullVector(); long[] longs = selector.getLongVector(); for (int i = 0; i < selector.getCurrentVectorSize(); i++, rowCount++) { results.add(nulls != null && nulls[i] ? null : longs[i]); } break; case DOUBLE: // special case to test floats just to get coverage on getFloatVector if ("float2".equals(expression)) { nulls = selector.getNullVector(); float[] floats = selector.getFloatVector(); for (int i = 0; i < selector.getCurrentVectorSize(); i++, rowCount++) { results.add(nulls != null && nulls[i] ? null : (double) floats[i]); } } else { nulls = selector.getNullVector(); double[] doubles = selector.getDoubleVector(); for (int i = 0; i < selector.getCurrentVectorSize(); i++, rowCount++) { results.add(nulls != null && nulls[i] ? null : doubles[i]); } } break; case STRING: Object[] objects = objectSelector.getObjectVector(); for (int i = 0; i < objectSelector.getCurrentVectorSize(); i++, rowCount++) { results.add(objects[i]); } break; } cursor.advance(); } } closer.register(cursor); Sequence<Cursor> cursors = new QueryableIndexStorageAdapter(index).makeCursors( null, index.getDataInterval(), virtualColumns, Granularities.ALL, false, null ); int rowCountCursor = cursors .map(nonVectorized -> { final ColumnValueSelector nonSelector = nonVectorized.getColumnSelectorFactory() .makeColumnValueSelector("v"); int rows = 0; while (!nonVectorized.isDone()) { Assert.assertEquals( StringUtils.format("Failed at row %s", rows), nonSelector.getObject(), results.get(rows) ); rows++; nonVectorized.advance(); } return rows; }).accumulate(0, (acc, in) -> acc + in); Assert.assertTrue(rowCountCursor > 0); Assert.assertEquals(rowCountCursor, rowCount); } }
apache-2.0
htools/htools
src/main/java/io/github/htools/collection/PeekIteratorComparable.java
408
package io.github.htools.collection; import java.util.Iterator; public class PeekIteratorComparable<T extends Comparable<T>> extends PeekIteratorImpl<T> implements Comparable<PeekIteratorComparable<T>> { public PeekIteratorComparable(Iterator<T> data) { super(data); } @Override public int compareTo(PeekIteratorComparable<T> o) { return this.peek().compareTo(o.peek()); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/DescribeDocumentPermissionRequest.java
10781
/* * 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.simplesystemsmanagement.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeDocumentPermission" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeDocumentPermissionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the document for which you are the owner. * </p> */ private String name; /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> */ private String permissionType; /** * <p> * The maximum number of items to return for this call. The call also returns a token that you can specify in a * subsequent call to get the next set of results. * </p> */ private Integer maxResults; /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> */ private String nextToken; /** * <p> * The name of the document for which you are the owner. * </p> * * @param name * The name of the document for which you are the owner. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the document for which you are the owner. * </p> * * @return The name of the document for which you are the owner. */ public String getName() { return this.name; } /** * <p> * The name of the document for which you are the owner. * </p> * * @param name * The name of the document for which you are the owner. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDocumentPermissionRequest withName(String name) { setName(name); return this; } /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> * * @param permissionType * The permission type for the document. The permission type can be <i>Share</i>. * @see DocumentPermissionType */ public void setPermissionType(String permissionType) { this.permissionType = permissionType; } /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> * * @return The permission type for the document. The permission type can be <i>Share</i>. * @see DocumentPermissionType */ public String getPermissionType() { return this.permissionType; } /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> * * @param permissionType * The permission type for the document. The permission type can be <i>Share</i>. * @return Returns a reference to this object so that method calls can be chained together. * @see DocumentPermissionType */ public DescribeDocumentPermissionRequest withPermissionType(String permissionType) { setPermissionType(permissionType); return this; } /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> * * @param permissionType * The permission type for the document. The permission type can be <i>Share</i>. * @see DocumentPermissionType */ public void setPermissionType(DocumentPermissionType permissionType) { withPermissionType(permissionType); } /** * <p> * The permission type for the document. The permission type can be <i>Share</i>. * </p> * * @param permissionType * The permission type for the document. The permission type can be <i>Share</i>. * @return Returns a reference to this object so that method calls can be chained together. * @see DocumentPermissionType */ public DescribeDocumentPermissionRequest withPermissionType(DocumentPermissionType permissionType) { this.permissionType = permissionType.toString(); return this; } /** * <p> * The maximum number of items to return for this call. The call also returns a token that you can specify in a * subsequent call to get the next set of results. * </p> * * @param maxResults * The maximum number of items to return for this call. The call also returns a token that you can specify in * a subsequent call to get the next set of results. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of items to return for this call. The call also returns a token that you can specify in a * subsequent call to get the next set of results. * </p> * * @return The maximum number of items to return for this call. The call also returns a token that you can specify * in a subsequent call to get the next set of results. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of items to return for this call. The call also returns a token that you can specify in a * subsequent call to get the next set of results. * </p> * * @param maxResults * The maximum number of items to return for this call. The call also returns a token that you can specify in * a subsequent call to get the next set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDocumentPermissionRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @param nextToken * The token for the next set of items to return. (You received this token from a previous call.) */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @return The token for the next set of items to return. (You received this token from a previous call.) */ public String getNextToken() { return this.nextToken; } /** * <p> * The token for the next set of items to return. (You received this token from a previous call.) * </p> * * @param nextToken * The token for the next set of items to return. (You received this token from a previous call.) * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDocumentPermissionRequest withNextToken(String nextToken) { setNextToken(nextToken); 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 (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getPermissionType() != null) sb.append("PermissionType: ").append(getPermissionType()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeDocumentPermissionRequest == false) return false; DescribeDocumentPermissionRequest other = (DescribeDocumentPermissionRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getPermissionType() == null ^ this.getPermissionType() == null) return false; if (other.getPermissionType() != null && other.getPermissionType().equals(this.getPermissionType()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getPermissionType() == null) ? 0 : getPermissionType().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public DescribeDocumentPermissionRequest clone() { return (DescribeDocumentPermissionRequest) super.clone(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-opensearch/src/main/java/com/amazonaws/services/opensearch/model/transform/UpgradeStepItemMarshaller.java
2957
/* * 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.opensearch.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.opensearch.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpgradeStepItemMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpgradeStepItemMarshaller { private static final MarshallingInfo<String> UPGRADESTEP_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpgradeStep").build(); private static final MarshallingInfo<String> UPGRADESTEPSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpgradeStepStatus").build(); private static final MarshallingInfo<List> ISSUES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Issues").build(); private static final MarshallingInfo<Double> PROGRESSPERCENT_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProgressPercent").build(); private static final UpgradeStepItemMarshaller instance = new UpgradeStepItemMarshaller(); public static UpgradeStepItemMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpgradeStepItem upgradeStepItem, ProtocolMarshaller protocolMarshaller) { if (upgradeStepItem == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(upgradeStepItem.getUpgradeStep(), UPGRADESTEP_BINDING); protocolMarshaller.marshall(upgradeStepItem.getUpgradeStepStatus(), UPGRADESTEPSTATUS_BINDING); protocolMarshaller.marshall(upgradeStepItem.getIssues(), ISSUES_BINDING); protocolMarshaller.marshall(upgradeStepItem.getProgressPercent(), PROGRESSPERCENT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
gfis/flodskim
src/main/java/org/teherba/flodskim/buffer/DskBuffer.java
5350
/* Class for a buffer for the (e)DSK disk image container format @(#) $Id: Main.java 820 2011-11-07 21:59:07Z gfis $ 2017-05-29: javadoc 1.8 2013-11-05, Georg Fischer c.f. http://web.archive.org/web/20090107021455/http://www.kjthacker.f2s.com/docs/dsk.html and http://simonowen.com/samdisk/formats/ */ /* * Copyright 2013 Dr. Georg Fischer <punctum at punctum dot kom> * * 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.teherba.flodskim.buffer; import org.teherba.flodskim.buffer.BaseBuffer; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** Base class for a byte buffer for the DSK disk image container * defining common properties and methods. The container format * is described in an * <a href="http://web.archive.org/web/20090107021455/http://www.kjthacker.f2s.com/docs/dsk.html">outdated document for CPCEMU</a>. * @author Dr. Georg Fischer */ public class DskBuffer extends BaseBuffer { public final static String CVSID = "@(#) $Id: BaseBuffer.java 852 2012-01-06 08:07:08Z gfis $"; /** whether to write debugging output (iff &gt; 0) */ protected final static int debug = 0; /** log4j logger (category) */ private Logger log; //-------------------------------- // Constructor //-------------------------------- /** Constructor with no arguments, no heavy-weight operations. */ public DskBuffer() { super(); log = LogManager.getLogger(DskBuffer.class.getName()); setCode("dsk"); setDescription("(Extendend) Disk Image"); } // Constructor(0) /** Initializes the buffer */ public void initialize() { super.initialize(); } // initialize /** Fills the buffer from a disk image container file. * @param informLevel amount if diagnostic output: 0 = none, 1 = minimal, 2 = medium, 3 = full */ public void readContainer(int informLevel) { int blockSize = 0x100; // read disk information block setPosition(0); readChunk(blockSize); setPosition(0x30); int trackNo = get1(); setMaxCylinder(trackNo); int headNo = get1(); setMaxHead(headNo); int trackLen = getLsb2(); // not filled by SAMdisk? if (informLevel >= 1) { // minimal: Disc Information Block charWriter.println(getAscii(0, 0x30)); // format descriptor and creator charWriter.println(trackNo + " tracks, " + headNo + " heads"); } // informLevel >= 0 setPosition(0); // overwrite disk information block // read all tracks int itrack = 0; while (itrack < trackNo) { int ihead = 0; while (ihead < headNo) { // first read the track's information block (tib) int tib0 = getPosition(); readChunk(blockSize); setPosition(tib0 + 0x10); int tibTrack = get1(); if (tibTrack == itrack) { int tibHead = get1(); if (tibHead != ihead ) { log.error("wrong head# " + tibHead + " for track " + itrack + ", head " + ihead); } int dummy = getLsb2(); int sectSize = 128 << get1(); // 0 = 128, 1= 256, 2 = 512 ... setSectorSize(sectSize); int sectNo = get1(); setMaxSector(sectNo); if (informLevel >= 2) { // medium charWriter.println("track " + tibTrack + ", head " + tibHead + ": " + sectNo + " sectors of " + sectSize + " bytes" ); } // informLevel >= 2 setPosition(tib0); // overwrite track information block int isect = 0; while (isect < sectNo) { // read 1 sector readChunk(sectSize); isect ++; } // while isect } else if (tibTrack > itrack) { log.error("wrong track# " + tibTrack + " for track " + itrack + ", head " + ihead); // ignore } else { // tibTrack < itrack - ignore any strange tracks at the end of the disk // log.error("wrong track# " + tibTrack + " for track " + itrack + ", head " + ihead); setMaxCylinder(itrack - 1); itrack = trackNo; // will stop loop ihead = headNo; } ihead ++; } // while ihead itrack ++; } // while itrack bufferLength = bufferPos; } // readContainer } // DskBuffer
apache-2.0
edgar615/direwolves
standalone/src/test/java/com/github/edgar615/gateway/test/arg/StrictArgTest.java
2628
package com.github.edgar615.gateway.test.arg; import com.github.edgar615.util.exception.DefaultErrorCode; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.awaitility.Awaitility; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by Edgar on 2017/2/7. * * @author Edgar Date 2017/2/7 */ @RunWith(VertxUnitRunner.class) public class StrictArgTest { @Test public void undefinedArgShouldThrowInvalidArg(TestContext testContext) { AtomicBoolean check = new AtomicBoolean(); Vertx.vertx().createHttpClient().post(9000, "localhost", "/arg/strict") .handler(resp -> { testContext.assertEquals(400, resp.statusCode()); testContext.assertTrue(resp.headers().contains("x-request-id")); resp.bodyHandler(body -> { System.out.println(body.toString()); testContext.assertEquals(DefaultErrorCode.INVALID_ARGS.getNumber(), body.toJsonObject().getInteger("code")); JsonObject details = body.toJsonObject().getJsonObject("details", new JsonObject()); testContext.assertEquals(1, details.size()); testContext.assertTrue(details.containsKey("start")); check.set(true); }); }) .setChunked(true) .end(new JsonObject().put("deviceType", 1).put("start", 5).encode()); Awaitility.await().until(() -> check.get()); } @Test public void testSuccess(TestContext testContext) { AtomicBoolean check = new AtomicBoolean(); String url = "/arg/strict"; Vertx.vertx().createHttpClient().post(9000, "localhost", url) .handler(resp -> { testContext.assertEquals(200, resp.statusCode()); testContext.assertTrue(resp.headers().contains("x-request-id")); resp.bodyHandler(body -> { System.out.println(body.toString()); JsonObject jsonObject = body.toJsonObject(); check.set(true); }); }) .setChunked(true) .end(new JsonObject().put("deviceType", 1).encode()); Awaitility.await().until(() -> check.get()); } }
apache-2.0
sapia-oss/corus_iop
modules/api/src/main/java/org/sapia/corus/interop/api/message/InteropMessageBuilderFactory.java
1017
package org.sapia.corus.interop.api.message; public interface InteropMessageBuilderFactory { public AckMessageCommand.Builder newAckMessageBuilder(); public ConfigurationEventMessageCommand.Builder newConfigurationEventMessageBuilder(); public ConfirmShutdownMessageCommand.Builder newConfirmShutdownMessageBuilder(); public PollMessageCommand.Builder newPollMessageBuilder(); public ProcessEventMessageCommand.Builder newProcessEventMessageBuilder(); public ProcessMessageHeader.Builder newProcessMessageHeaderBuilder(); public RestartMessageCommand.Builder newRestartMessageBuilder(); public ServerMessageHeader.Builder newServerMessageHeaderBuilder(); public ShutdownMessageCommand.Builder newShutdownMessageBuilder(); public StatusMessageCommand.Builder newStatusMessageBuilder(); public ContextMessagePart.Builder newContextBuilder(); public ParamMessagePart.Builder newParamBuilder(); public FaultMessagePart.Builder newFaultMessageBuilder(); }
apache-2.0
Ravmouse/vvasilyev
chapter_001/src/main/java/ru/job4j/array/ArrayDuplicate.java
1047
package ru.job4j.array; import java.util.Arrays; /** * Class ArrayDuplicate. * @author Vitaly Vasilyev * @version $Id$ * @since 0.1 */ public class ArrayDuplicate { /** * The method removes any duplicate string-values from an array of strings. * @param array Array of string elements. * @return The reference to the same object w/out duplicate elements. */ public String[] remove(String[] array) { int i, j, k, end = 0; String tmp; for (i = 0; i < array.length - 1; i++) { for (j = i + 1; j < array.length - end; j++) { if (array[i].equals(array[j])) { tmp = array[j]; k = j; while (k < array.length - 1) { array[k] = array[k + 1]; k++; } array[k] = tmp; end++; j--; } } } return Arrays.copyOf(array, array.length - end); } }
apache-2.0
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrStubFileElementType.java
4090
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.stubs.elements; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.StubBuilder; import com.intellij.psi.stubs.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IStubFileElementType; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.stubs.GrFileStub; import org.jetbrains.plugins.groovy.lang.psi.stubs.GrStubUtils; import org.jetbrains.plugins.groovy.lang.psi.stubs.index.GrAnnotatedMemberIndex; import org.jetbrains.plugins.groovy.lang.psi.stubs.index.GrFullScriptNameIndex; import org.jetbrains.plugins.groovy.lang.psi.stubs.index.GrScriptClassNameIndex; import java.io.IOException; /** * @author ilyas */ public class GrStubFileElementType extends IStubFileElementType<GrFileStub> { public static final int STUB_VERSION = 49; public GrStubFileElementType(Language language) { super(language); } @Override public StubBuilder getBuilder() { return new DefaultStubBuilder() { @NotNull @Override protected StubElement createStubForFile(@NotNull final PsiFile file) { if (file instanceof GroovyFile) { return new GrFileStub((GroovyFile)file); } return super.createStubForFile(file); } @Override public boolean skipChildProcessingWhenBuildingStubs(@NotNull ASTNode parent, @NotNull ASTNode node) { IElementType childType = node.getElementType(); IElementType parentType = parent.getElementType(); if (childType == GroovyElementTypes.PARAMETER && parentType != GroovyElementTypes.PARAMETERS_LIST) { return true; } if (childType == GroovyElementTypes.PARAMETERS_LIST && !(parent.getPsi() instanceof GrMethod)) { return true; } if (childType == GroovyElementTypes.MODIFIERS) { if (parentType == GroovyElementTypes.CLASS_INITIALIZER) { return true; } if (parentType == GroovyElementTypes.VARIABLE_DEFINITION && !GroovyElementTypes.VARIABLE_DEFINITION.shouldCreateStub(parent)) { return true; } } return false; } }; } @Override public int getStubVersion() { return super.getStubVersion() + STUB_VERSION; } @Override @NotNull public String getExternalId() { return "groovy.FILE"; } @Override public void serialize(@NotNull final GrFileStub stub, @NotNull final StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName().toString()); dataStream.writeBoolean(stub.isScript()); GrStubUtils.writeStringArray(dataStream, stub.getAnnotations()); } @NotNull @Override public GrFileStub deserialize(@NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException { StringRef name = dataStream.readName(); boolean isScript = dataStream.readBoolean(); return new GrFileStub(name, isScript, GrStubUtils.readStringArray(dataStream)); } @Override public void indexStub(@NotNull GrFileStub stub, @NotNull IndexSink sink) { String name = stub.getName().toString(); if (stub.isScript() && name != null) { sink.occurrence(GrScriptClassNameIndex.KEY, name); final String pName = GrStubUtils.getPackageName(stub); final String fqn = StringUtil.isEmpty(pName) ? name : pName + "." + name; sink.occurrence(GrFullScriptNameIndex.KEY, fqn.hashCode()); } for (String anno : stub.getAnnotations()) { sink.occurrence(GrAnnotatedMemberIndex.KEY, anno); } } }
apache-2.0
joel-costigliola/assertj-core
src/test/java/org/assertj/core/test/StringSpliterator.java
1349
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.test; import java.util.Spliterator; import java.util.function.Consumer; /** * Dummy spliterator for testing purpose * * @author William Bakker */ public class StringSpliterator implements Spliterator<String> { private final int characteristics; public StringSpliterator() { this(0); } public StringSpliterator(int characteristics) { this.characteristics = characteristics; } @Override public boolean tryAdvance(Consumer<? super String> action) { return false; } @Override public Spliterator<String> trySplit() { return null; } @Override public long estimateSize() { return 0; } @Override public int characteristics() { return characteristics; } }
apache-2.0
xmagicj/HappyVolley
app/src/main/java/com/xmagicj/android/happyvolley/view/MyApplication.java
431
package com.xmagicj.android.happyvolley.view; import android.app.Application; /** * Created by Mumu * on 2015/11/5. */ public class MyApplication extends Application { private static MyApplication applicationContext; public static MyApplication getInstance() { return applicationContext; } @Override public void onCreate() { super.onCreate(); applicationContext = this; } }
apache-2.0
jexp/idea2
platform/platform-api/src/com/intellij/openapi/fileEditor/FileDocumentManagerListener.java
1746
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.vfs.VirtualFile; import java.util.EventListener; public interface FileDocumentManagerListener extends EventListener { /** * Fired before processing FileDocumentManager.saveAllDocuments(). Can be used by plugins * which need to perform additional save operations when documents, rather than settings, * are saved. * * @since 8.0 */ void beforeAllDocumentsSaving(); /** * NOTE: Vetoing facility is deprecated in this listener implement {@link com.intellij.openapi.fileEditor.FileDocumentSynchronizationVetoListener} instead. */ void beforeDocumentSaving(Document document); /** * NOTE: Vetoing facility is deprecated in this listener implement {@link com.intellij.openapi.fileEditor.FileDocumentSynchronizationVetoListener} instead. */ void beforeFileContentReload(VirtualFile file, Document document); void fileWithNoDocumentChanged(VirtualFile file); void fileContentReloaded(VirtualFile file, Document document); void fileContentLoaded(VirtualFile file, Document document); }
apache-2.0
UKQIDA/proteoformer-simulator
src/main/java/uk/ac/liv/proteoformer/simulator/Peak.java
531
package uk.ac.liv.proteoformer.simulator; /** * * @author Da Qi * @institute University of Liverpool * @time 28-Aug-2015 16:39:17 */ public class Peak { private final double mz; private final double intensity; Peak(double mz, double inten) { this.mz = mz; this.intensity = inten; } /** * @return the mz */ public double getMz() { return mz; } /** * @return the intensity */ public double getIntensity() { return intensity; } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/LineItemTemplate.java
9810
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Represents the template that populates the fields of a new line item being * created. * * * <p>Java class for LineItemTemplate complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="LineItemTemplate"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="isDefault" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="lineItemName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="targetPlatform" type="{https://www.google.com/apis/ads/publisher/v201405}TargetPlatform" minOccurs="0"/> * &lt;element name="enabledForSameAdvertiserException" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="lineItemType" type="{https://www.google.com/apis/ads/publisher/v201405}LineItemType" minOccurs="0"/> * &lt;element name="startTime" type="{https://www.google.com/apis/ads/publisher/v201405}DateTime" minOccurs="0"/> * &lt;element name="endTime" type="{https://www.google.com/apis/ads/publisher/v201405}DateTime" minOccurs="0"/> * &lt;element name="deliveryRateType" type="{https://www.google.com/apis/ads/publisher/v201405}DeliveryRateType" minOccurs="0"/> * &lt;element name="roadblockingType" type="{https://www.google.com/apis/ads/publisher/v201405}RoadblockingType" minOccurs="0"/> * &lt;element name="creativeRotationType" type="{https://www.google.com/apis/ads/publisher/v201405}CreativeRotationType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "LineItemTemplate", propOrder = { "id", "name", "isDefault", "lineItemName", "targetPlatform", "enabledForSameAdvertiserException", "notes", "lineItemType", "startTime", "endTime", "deliveryRateType", "roadblockingType", "creativeRotationType" }) public class LineItemTemplate { protected Long id; protected String name; protected Boolean isDefault; protected String lineItemName; protected TargetPlatform targetPlatform; protected Boolean enabledForSameAdvertiserException; protected String notes; protected LineItemType lineItemType; protected DateTime startTime; protected DateTime endTime; protected DeliveryRateType deliveryRateType; protected RoadblockingType roadblockingType; protected CreativeRotationType creativeRotationType; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the isDefault property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsDefault() { return isDefault; } /** * Sets the value of the isDefault property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsDefault(Boolean value) { this.isDefault = value; } /** * Gets the value of the lineItemName property. * * @return * possible object is * {@link String } * */ public String getLineItemName() { return lineItemName; } /** * Sets the value of the lineItemName property. * * @param value * allowed object is * {@link String } * */ public void setLineItemName(String value) { this.lineItemName = value; } /** * Gets the value of the targetPlatform property. * * @return * possible object is * {@link TargetPlatform } * */ public TargetPlatform getTargetPlatform() { return targetPlatform; } /** * Sets the value of the targetPlatform property. * * @param value * allowed object is * {@link TargetPlatform } * */ public void setTargetPlatform(TargetPlatform value) { this.targetPlatform = value; } /** * Gets the value of the enabledForSameAdvertiserException property. * * @return * possible object is * {@link Boolean } * */ public Boolean isEnabledForSameAdvertiserException() { return enabledForSameAdvertiserException; } /** * Sets the value of the enabledForSameAdvertiserException property. * * @param value * allowed object is * {@link Boolean } * */ public void setEnabledForSameAdvertiserException(Boolean value) { this.enabledForSameAdvertiserException = value; } /** * Gets the value of the notes property. * * @return * possible object is * {@link String } * */ public String getNotes() { return notes; } /** * Sets the value of the notes property. * * @param value * allowed object is * {@link String } * */ public void setNotes(String value) { this.notes = value; } /** * Gets the value of the lineItemType property. * * @return * possible object is * {@link LineItemType } * */ public LineItemType getLineItemType() { return lineItemType; } /** * Sets the value of the lineItemType property. * * @param value * allowed object is * {@link LineItemType } * */ public void setLineItemType(LineItemType value) { this.lineItemType = value; } /** * Gets the value of the startTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getStartTime() { return startTime; } /** * Sets the value of the startTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setStartTime(DateTime value) { this.startTime = value; } /** * Gets the value of the endTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getEndTime() { return endTime; } /** * Sets the value of the endTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setEndTime(DateTime value) { this.endTime = value; } /** * Gets the value of the deliveryRateType property. * * @return * possible object is * {@link DeliveryRateType } * */ public DeliveryRateType getDeliveryRateType() { return deliveryRateType; } /** * Sets the value of the deliveryRateType property. * * @param value * allowed object is * {@link DeliveryRateType } * */ public void setDeliveryRateType(DeliveryRateType value) { this.deliveryRateType = value; } /** * Gets the value of the roadblockingType property. * * @return * possible object is * {@link RoadblockingType } * */ public RoadblockingType getRoadblockingType() { return roadblockingType; } /** * Sets the value of the roadblockingType property. * * @param value * allowed object is * {@link RoadblockingType } * */ public void setRoadblockingType(RoadblockingType value) { this.roadblockingType = value; } /** * Gets the value of the creativeRotationType property. * * @return * possible object is * {@link CreativeRotationType } * */ public CreativeRotationType getCreativeRotationType() { return creativeRotationType; } /** * Sets the value of the creativeRotationType property. * * @param value * allowed object is * {@link CreativeRotationType } * */ public void setCreativeRotationType(CreativeRotationType value) { this.creativeRotationType = value; } }
apache-2.0
spring-cloud/spring-cloud-sleuth
spring-cloud-sleuth-api/src/main/java/org/springframework/cloud/sleuth/http/HttpRequest.java
1960
/* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.http; import org.springframework.lang.Nullable; /** * This API is taken from OpenZipkin Brave. * * Abstract request type used for parsing and sampling. Represents an HTTP request. * * @author OpenZipkin Brave Authors * @author Marcin Grzejszczak * @since 3.0.0 */ public interface HttpRequest extends Request { /** * @return HTTP method. */ String method(); /** * @return HTTP path or {@code null} if not set. */ @Nullable String path(); /** * Returns an expression such as "/items/:itemId" representing an application * endpoint, conventionally associated with the tag key "http.route". If no route * matched, "" (empty string) is returned. {@code null} indicates this instrumentation * doesn't understand http routes. * @return HTTP route or {@code null} if not set. */ @Nullable default String route() { return null; } /** * @return HTTP URL or {@code null} if not set. */ @Nullable String url(); /** * @param name header name * @return HTTP header or {@code null} if not set. */ @Nullable String header(String name); /** * @return remote IP for the given connection. */ default String remoteIp() { return null; } /** * @return remote port for the given connection. */ default int remotePort() { return 0; } }
apache-2.0
MorpG/Java-course
package_1/chapter_002/Chess/src/main/java/ru/agolovin/models/Bishop.java
1691
package ru.agolovin.models; /** * Class for chess figure Bishop. * * @author agolovin (agolovin@list.ru) * @version $Id$ * @since 0.1 */ public class Bishop extends Figure { /** * constructor. * @param cell cell */ Bishop(final Cell cell) { super(cell); } /** * clone figure to dist cell. * @param dist cell * @return new figure. */ @Override public final Bishop clone(final Cell dist) { return new Bishop(dist); } /** * array of move cells. * @param dist Cell * @return array of cells * @throws ImpossibleMoveException error */ @Override public final Cell[] way(final Cell dist) throws ImpossibleMoveException { int startCol = this.getPosition().getCol(); int startRow = this.getPosition().getRow(); int endCol = dist.getCol(); int endRow = dist.getRow(); int maxSize = Math.abs(endCol - startCol); int step = 1; Cell[] res = new Cell[maxSize]; if ((Math.abs(endCol - startCol) == Math.abs(endRow - startRow)) && ((endCol - startCol) != 0) && (endRow - startRow) != 0) { if (startCol > endCol) { step = -1; } for (int i = 1; i <= maxSize; i++) { int stepCol = startCol + step * i; int stepRow = (stepCol - startCol) * (endRow - startRow) / (endCol - startCol) + startRow; res[i - 1] = new Cell(stepCol, stepRow); } } else { throw new ImpossibleMoveException("Error: impossible move"); } return res; } }
apache-2.0
ktr-skmt/FelisCatusZero
src/main/java/jeqa/types/ja/DependencyAnalysis.java
4297
/* First created by JCasGen Wed Jan 25 19:24:52 JST 2017 */ package jeqa.types.ja; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.TOP_Type; import org.apache.uima.jcas.cas.FSList; import jeqa.types.Analysis; /** CaboChaやKNPの結果を保持する * Updated by JCasGen Wed Jan 25 19:24:52 JST 2017 * XML source: src/main/resources/desc/ts/typeSystem.xml * @generated */ public class DependencyAnalysis extends Analysis { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(DependencyAnalysis.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated * @return index of the type */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected DependencyAnalysis() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated * @param addr low level Feature Structure reference * @param type the type of this Feature Structure */ public DependencyAnalysis(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs */ public DependencyAnalysis(JCas jcas) { super(jcas); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs * @param begin offset to the begin spot in the SofA * @param end offset to the end spot in the SofA */ public DependencyAnalysis(JCas jcas, int begin, int end) { super(jcas); setBegin(begin); setEnd(end); readObject(); } /** * <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> * * @generated modifiable */ private void readObject() {/*default - does nothing empty block */} //*--------------* //* Feature: analysisResultTreeFormat /** getter for analysisResultTreeFormat - gets ツリー形式の解析結果 * @generated * @return value of the feature */ public String getAnalysisResultTreeFormat() { if (DependencyAnalysis_Type.featOkTst && ((DependencyAnalysis_Type)jcasType).casFeat_analysisResultTreeFormat == null) jcasType.jcas.throwFeatMissing("analysisResultTreeFormat", "jeqa.types.ja.DependencyAnalysis"); return jcasType.ll_cas.ll_getStringValue(addr, ((DependencyAnalysis_Type)jcasType).casFeatCode_analysisResultTreeFormat);} /** setter for analysisResultTreeFormat - sets ツリー形式の解析結果 * @generated * @param v value to set into the feature */ public void setAnalysisResultTreeFormat(String v) { if (DependencyAnalysis_Type.featOkTst && ((DependencyAnalysis_Type)jcasType).casFeat_analysisResultTreeFormat == null) jcasType.jcas.throwFeatMissing("analysisResultTreeFormat", "jeqa.types.ja.DependencyAnalysis"); jcasType.ll_cas.ll_setStringValue(addr, ((DependencyAnalysis_Type)jcasType).casFeatCode_analysisResultTreeFormat, v);} //*--------------* //* Feature: bunsetsuList /** getter for bunsetsuList - gets 文節のリスト * @generated * @return value of the feature */ public FSList getBunsetsuList() { if (DependencyAnalysis_Type.featOkTst && ((DependencyAnalysis_Type)jcasType).casFeat_bunsetsuList == null) jcasType.jcas.throwFeatMissing("bunsetsuList", "jeqa.types.ja.DependencyAnalysis"); return (FSList)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((DependencyAnalysis_Type)jcasType).casFeatCode_bunsetsuList)));} /** setter for bunsetsuList - sets 文節のリスト * @generated * @param v value to set into the feature */ public void setBunsetsuList(FSList v) { if (DependencyAnalysis_Type.featOkTst && ((DependencyAnalysis_Type)jcasType).casFeat_bunsetsuList == null) jcasType.jcas.throwFeatMissing("bunsetsuList", "jeqa.types.ja.DependencyAnalysis"); jcasType.ll_cas.ll_setRefValue(addr, ((DependencyAnalysis_Type)jcasType).casFeatCode_bunsetsuList, jcasType.ll_cas.ll_getFSRef(v));} }
apache-2.0
arturmkrtchyan/sizeof4j
src/main/java/com/arturmkrtchyan/sizeof4j/SizeOfException.java
418
package com.arturmkrtchyan.sizeof4j; public class SizeOfException extends RuntimeException { private static final long serialVersionUID = 602133648144972294L; public SizeOfException(String message) { super(message); } public SizeOfException(String message, Throwable cause) { super(message, cause); } public SizeOfException(Throwable cause) { super(cause); } }
apache-2.0
rfuertesp/pruebas2
common/app/com/commercetools/sunrise/common/contexts/RequestScoped.java
395
package com.commercetools.sunrise.common.contexts; import com.google.inject.ScopeAnnotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @ScopeAnnotation public @interface RequestScoped { }
apache-2.0
gbif/gbif-api
src/main/java/org/gbif/api/vocabulary/DatasetType.java
1262
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.api.vocabulary; import org.gbif.api.util.VocabularyUtils; /** * Enumeration for all possible dataset types. */ public enum DatasetType { /** * An occurrence dataset. */ OCCURRENCE, /** * A checklist dataset. */ CHECKLIST, /** * External metadata about any kind of biodiversity dataset. */ METADATA, /** * A dataset about a sampling event. */ SAMPLING_EVENT; /** * @return the matching DatasetType or null */ public static DatasetType fromString(String datasetType) { return (DatasetType) VocabularyUtils.lookupEnum(datasetType, DatasetType.class); } }
apache-2.0
warnerbros/cpe-manifest-android-experience
src/com/wb/nextgenlibrary/parser/manifest/schema/v1_4/ContainerReferenceType.java
6328
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // 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.02.08 at 03:02:05 PM PST // package com.wb.nextgenlibrary.parser.manifest.schema.v1_4; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import com.wb.nextgenlibrary.parser.XmlAccessType; import com.wb.nextgenlibrary.parser.XmlAccessorType; import com.wb.nextgenlibrary.parser.XmlElement; import com.wb.nextgenlibrary.parser.XmlSchemaType; import com.wb.nextgenlibrary.parser.XmlSeeAlso; import com.wb.nextgenlibrary.parser.XmlType; import com.wb.nextgenlibrary.parser.md.schema.v2_3.ContentIdentifierType; import com.wb.nextgenlibrary.parser.md.schema.v2_3.HashType; /** * <p>Java class for ContainerReference-type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ContainerReference-type"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ContainerLocation" type="{http://www.movielabs.com/schema/manifest/v1.4/manifest}Location-type" minOccurs="0"/&gt; * &lt;element name="ParentContainer" type="{http://www.movielabs.com/schema/manifest/v1.4/manifest}ContainerReference-type" minOccurs="0"/&gt; * &lt;element name="ContainerIdentifier" type="{http://www.movielabs.com/schema/md/v2.3/md}ContentIdentifier-type" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;element name="Length" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/&gt; * &lt;element name="Hash" type="{http://www.movielabs.com/schema/md/v2.3/md}Hash-type" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ContainerReference-type", propOrder = { "containerLocation", "parentContainer", "containerIdentifier", "length", "hash" }) @XmlSeeAlso({ com.wb.nextgenlibrary.parser.manifest.schema.v1_4.InventoryMetadataType.ContainerReference.class, com.wb.nextgenlibrary.parser.manifest.schema.v1_4.InventoryTextObjectType.ContainerReference.class }) public class ContainerReferenceType { @XmlElement(name = "ContainerLocation") @XmlSchemaType(name = "anyURI") protected String containerLocation; @XmlElement(name = "ParentContainer") protected ContainerReferenceType parentContainer; @XmlElement(name = "ContainerIdentifier") protected List<ContentIdentifierType> containerIdentifier; @XmlElement(name = "Length") @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger length; @XmlElement(name = "Hash") protected List<HashType> hash; /** * Gets the value of the containerLocation property. * * @return * possible object is * {@link String } * */ public String getContainerLocation() { return containerLocation; } /** * Sets the value of the containerLocation property. * * @param value * allowed object is * {@link String } * */ public void setContainerLocation(String value) { this.containerLocation = value; } /** * Gets the value of the parentContainer property. * * @return * possible object is * {@link ContainerReferenceType } * */ public ContainerReferenceType getParentContainer() { return parentContainer; } /** * Sets the value of the parentContainer property. * * @param value * allowed object is * {@link ContainerReferenceType } * */ public void setParentContainer(ContainerReferenceType value) { this.parentContainer = value; } /** * Gets the value of the containerIdentifier 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 containerIdentifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContainerIdentifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ContentIdentifierType } * * */ public List<ContentIdentifierType> getContainerIdentifier() { if (containerIdentifier == null) { containerIdentifier = new ArrayList<ContentIdentifierType>(); } return this.containerIdentifier; } /** * Gets the value of the length property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getLength() { return length; } /** * Sets the value of the length property. * * @param value * allowed object is * {@link BigInteger } * */ public void setLength(BigInteger value) { this.length = value; } /** * Gets the value of the hash 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 hash property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHash().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link HashType } * * */ public List<HashType> getHash() { if (hash == null) { hash = new ArrayList<HashType>(); } return this.hash; } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/viewitem/summary/section/DisplaySectionConfiguration.java
1141
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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.tle.web.viewitem.summary.section; import com.tle.annotation.NonNullByDefault; import com.tle.beans.entity.itemdef.SummarySectionsConfig; import com.tle.web.sections.SectionId; @NonNullByDefault public interface DisplaySectionConfiguration extends SectionId { void associateConfiguration(SummarySectionsConfig config); }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/wizard/page/WizardPageService.java
1098
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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.tle.web.wizard.page; import com.dytech.devlib.PropBagEx; import com.dytech.edge.wizard.beans.DefaultWizardPage; public interface WizardPageService { WizardPage createSimplePage( DefaultWizardPage wizardPage, PropBagEx docxml, WebWizardPageState state, boolean expert); }
apache-2.0
akumarb2010/incubator-drill
exec/java-exec/src/main/java/org/apache/drill/exec/server/BootStrapContext.java
11103
/* * 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.drill.exec.server; import com.codahale.metrics.MetricRegistry; import io.netty.channel.EventLoopGroup; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.SynchronousQueue; import org.apache.drill.common.AutoCloseables; import org.apache.drill.common.KerberosUtil; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.map.CaseInsensitiveMap; import org.apache.drill.common.scanner.persistence.ScanResult; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.exception.DrillbitStartupException; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.memory.RootAllocatorFactory; import org.apache.drill.exec.metrics.DrillMetrics; import org.apache.drill.exec.rpc.NamedThreadFactory; import org.apache.drill.exec.rpc.TransportCheck; import org.apache.drill.exec.rpc.security.AuthenticatorProvider; import org.apache.drill.exec.rpc.security.AuthenticatorProviderImpl; import org.apache.drill.exec.server.options.OptionDefinition; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.security.UserGroupInformation; public class BootStrapContext implements AutoCloseable { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BootStrapContext.class); // Tests and embedded servers need a small footprint, so the minimum // scan count is small. The actual value is set by the // ExecConstants.SCAN_THREADPOOL_SIZE. If the number below // is large, then tests cannot shrink the number using the // config property. private static final int MIN_SCAN_THREADPOOL_SIZE = 4; // Magic num // DRILL_HOST_NAME sets custom host name. See drill-env.sh for details. private static final String customHostName = System.getenv("DRILL_HOST_NAME"); private static final String processUserName = System.getProperty("user.name"); private static final String SERVICE_LOGIN_PREFIX = "drill.exec.security.auth"; public static final String SERVICE_PRINCIPAL = SERVICE_LOGIN_PREFIX + ".principal"; public static final String SERVICE_KEYTAB_LOCATION = SERVICE_LOGIN_PREFIX + ".keytab"; public static final String KERBEROS_NAME_MAPPING = SERVICE_LOGIN_PREFIX + ".auth_to_local"; private final DrillConfig config; private final CaseInsensitiveMap<OptionDefinition> definitions; private final AuthenticatorProvider authProvider; private final EventLoopGroup loop; private final EventLoopGroup loop2; private final MetricRegistry metrics; private final BufferAllocator allocator; private final ScanResult classpathScan; private final ExecutorService executor; private final ExecutorService scanExecutor; private final ExecutorService scanDecodeExecutor; private final String hostName; public BootStrapContext(DrillConfig config, CaseInsensitiveMap<OptionDefinition> definitions, ScanResult classpathScan) throws DrillbitStartupException { this.config = config; this.definitions = definitions; this.classpathScan = classpathScan; this.hostName = getCanonicalHostName(); login(config); this.authProvider = new AuthenticatorProviderImpl(config, classpathScan); this.loop = TransportCheck.createEventLoopGroup(config.getInt(ExecConstants.BIT_SERVER_RPC_THREADS), "BitServer-"); this.loop2 = TransportCheck.createEventLoopGroup(config.getInt(ExecConstants.BIT_SERVER_RPC_THREADS), "BitClient-"); // Note that metrics are stored in a static instance this.metrics = DrillMetrics.getRegistry(); this.allocator = RootAllocatorFactory.newRoot(config); this.executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("drill-executor-")) { @Override protected void afterExecute(final Runnable r, final Throwable t) { if (t != null) { logger.error("{}.run() leaked an exception.", r.getClass().getName(), t); } super.afterExecute(r, t); } }; // Setup two threadpools one for reading raw data from disk and another for decoding the data // A good guideline is to have the number threads in the scan pool to be a multiple (fractional // numbers are ok) of the number of disks. // A good guideline is to have the number threads in the decode pool to be a small multiple (fractional // numbers are ok) of the number of cores. final int numCores = Runtime.getRuntime().availableProcessors(); final int numScanThreads = (int) (config.getDouble(ExecConstants.SCAN_THREADPOOL_SIZE)); final int numScanDecodeThreads = (int) config.getDouble(ExecConstants.SCAN_DECODE_THREADPOOL_SIZE); final int scanThreadPoolSize = MIN_SCAN_THREADPOOL_SIZE > numScanThreads ? MIN_SCAN_THREADPOOL_SIZE : numScanThreads; final int scanDecodeThreadPoolSize = (numCores + 1) / 2 > numScanDecodeThreads ? (numCores + 1) / 2 : numScanDecodeThreads; this.scanExecutor = Executors.newFixedThreadPool(scanThreadPoolSize, new NamedThreadFactory("scan-")); this.scanDecodeExecutor = Executors.newFixedThreadPool(scanDecodeThreadPoolSize, new NamedThreadFactory("scan-decode-")); } private void login(final DrillConfig config) throws DrillbitStartupException { try { if (config.hasPath(SERVICE_PRINCIPAL)) { // providing a service principal => Kerberos mechanism final Configuration loginConf = new Configuration(); loginConf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, UserGroupInformation.AuthenticationMethod.KERBEROS.toString()); // set optional user name mapping if (config.hasPath(KERBEROS_NAME_MAPPING)) { loginConf.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTH_TO_LOCAL, config.getString(KERBEROS_NAME_MAPPING)); } UserGroupInformation.setConfiguration(loginConf); // service principal canonicalization final String principal = config.getString(SERVICE_PRINCIPAL); final String parts[] = KerberosUtil.splitPrincipalIntoParts(principal); if (parts.length != 3) { throw new DrillbitStartupException( String.format("Invalid %s, Drill service principal must be of format: primary/instance@REALM", SERVICE_PRINCIPAL)); } parts[1] = KerberosUtil.canonicalizeInstanceName(parts[1], hostName); final String canonicalizedPrincipal = KerberosUtil.getPrincipalFromParts(parts[0], parts[1], parts[2]); final String keytab = config.getString(SERVICE_KEYTAB_LOCATION); // login to KDC (AS) // Note that this call must happen before any call to UserGroupInformation#getLoginUser, // but there is no way to enforce the order (this static init. call and parameters from // DrillConfig are both required). UserGroupInformation.loginUserFromKeytab(canonicalizedPrincipal, keytab); logger.info("Process user name: '{}' and logged in successfully as '{}'", processUserName, canonicalizedPrincipal); } else { UserGroupInformation.getLoginUser(); // init } // ugi does not support logout } catch (final IOException e) { throw new DrillbitStartupException("Failed to login.", e); } } private static String getCanonicalHostName() throws DrillbitStartupException { try { return customHostName != null ? customHostName : InetAddress.getLocalHost().getCanonicalHostName(); } catch (final UnknownHostException e) { throw new DrillbitStartupException("Could not get canonical hostname.", e); } } public String getHostName() { return hostName; } public ExecutorService getExecutor() { return executor; } public ExecutorService getScanExecutor() { return scanExecutor; } public ExecutorService getScanDecodeExecutor() { return scanDecodeExecutor; } public DrillConfig getConfig() { return config; } public CaseInsensitiveMap<OptionDefinition> getDefinitions() { return definitions; } public EventLoopGroup getBitLoopGroup() { return loop; } public EventLoopGroup getBitClientLoopGroup() { return loop2; } public MetricRegistry getMetrics() { return metrics; } public BufferAllocator getAllocator() { return allocator; } public ScanResult getClasspathScan() { return classpathScan; } public AuthenticatorProvider getAuthProvider() { return authProvider; } @Override public void close() { try { DrillMetrics.resetMetrics(); } catch (Error | Exception e) { logger.warn("failure resetting metrics.", e); } if (executor != null) { executor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { executor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { logger.warn("Executor interrupted while awaiting termination"); // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } try { AutoCloseables.close(allocator, authProvider); shutdown(loop); shutdown(loop2); } catch (final Exception e) { logger.error("Error while closing", e); } } private static void shutdown(EventLoopGroup loopGroup) { if (loopGroup != null && !(loopGroup.isShutdown() || loopGroup.isShuttingDown())) { try { loopGroup.shutdownGracefully(); } catch (final Exception e) { logger.error("Error while closing", e); } } } }
apache-2.0
hudak/pentaho-kettle
engine/src/org/pentaho/di/trans/ael/adapters/TransMetaConverter.java
7495
/* * ! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.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.pentaho.di.trans.ael.adapters; import com.google.common.base.Throwables; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.util.Utils; import org.pentaho.di.engine.api.model.Hop; import org.pentaho.di.engine.api.model.Operation; import org.pentaho.di.engine.api.model.Transformation; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; public class TransMetaConverter { public static final String TRANS_META_CONF_KEY = "TransMeta"; public static final String TRANS_META_NAME_CONF_KEY = "TransMetaName"; public static final String STEP_META_CONF_KEY = "StepMeta"; public static final String TRANS_DEFAULT_NAME = "No Name"; public static Transformation convert( TransMeta transMeta ) { final org.pentaho.di.engine.model.Transformation transformation = new org.pentaho.di.engine.model.Transformation( createTransformationId( transMeta ) ); try { TransMeta copyTransMeta = cleanupDisabledHops( transMeta ); copyTransMeta.getSteps().forEach( createOperation( transformation ) ); findHops( copyTransMeta, hop -> true ).forEach( createHop( transformation ) ); transformation.setConfig( TRANS_META_CONF_KEY, copyTransMeta.getXML() ); transformation.setConfig( TRANS_META_NAME_CONF_KEY, Optional.ofNullable( transMeta.getName() ).orElse( TRANS_DEFAULT_NAME ) ); } catch ( KettleException e ) { Throwables.propagate( e ); } return transformation; } private static String createTransformationId( TransMeta transMeta ) { String filename = transMeta.getFilename(); if ( !Utils.isEmpty( filename ) ) { return filename; } return transMeta.getPathAndName(); } private static Consumer<StepMeta> createOperation( org.pentaho.di.engine.model.Transformation transformation ) { return stepMeta -> { org.pentaho.di.engine.model.Operation operation = transformation.createOperation( stepMeta.getName() ); try { operation.setConfig( STEP_META_CONF_KEY, stepMeta.getXML() ); } catch ( KettleException e ) { Throwables.propagate( e ); } }; } private static Consumer<TransHopMeta> createHop( org.pentaho.di.engine.model.Transformation transformation ) { return hop -> { try { Operation from = getOp( transformation, hop.getFromStep() ); Operation to = getOp( transformation, hop.getToStep() ); transformation.createHop( from, to, hop.isErrorHop() ? Hop.TYPE_ERROR : Hop.TYPE_NORMAL ); } catch ( KettleException e ) { Throwables.propagate( e ); } }; } private static Operation getOp( org.pentaho.di.engine.model.Transformation transformation, StepMeta step ) throws KettleException { return transformation.getOperations().stream() .filter( op -> step.getName().equals( op.getId() ) ) .findFirst() .orElseThrow( () -> new KettleException( "Could not find operation: " + step.getName() ) ); } /** * Removes disabled hops, unreachable steps and unused inputs. Doesn't change input transMeta object, operates * on it's clone. * * @param transMeta transMeta to process * @return processed clone of input transMeta */ private static TransMeta cleanupDisabledHops( TransMeta transMeta ) { TransMeta copyTransMeta = (TransMeta) transMeta.clone(); removeUnusedInputs( copyTransMeta ); removeInactivePaths( copyTransMeta, null ); return copyTransMeta; } /** * Removes steps which cannot be reached using enabled hops. Steps removed along with every input and * output hops they have. Downstream steps processed recursively in the same way. Should be invoked with null second arg. * * @param trans trans object to process * @param steps */ private static void removeInactivePaths( TransMeta trans, List<StepMeta> steps ) { if ( steps == null ) { List<TransHopMeta> disabledHops = findHops( trans, hop -> !hop.isEnabled() ); List<StepMeta> disabledSteps = disabledHops.stream() .map( hop -> hop.getToStep() ).collect( Collectors.toList() ); removeInactivePaths( trans, disabledSteps ); } else { for ( StepMeta step : steps ) { List<TransHopMeta> enabledInHops = findHops( trans, hop -> hop.getToStep().equals( step ) && hop.isEnabled() ); List<TransHopMeta> disabledInHops = findHops( trans, hop -> hop.getToStep().equals( step ) && !hop.isEnabled() ); if ( enabledInHops.size() == 0 ) { List<StepMeta> nextSteps = trans.findNextSteps( step ); findHops( trans, hop -> hop.getToStep().equals( step ) || hop.getFromStep().equals( step ) ) .forEach( trans::removeTransHop ); trans.getSteps().remove( step ); removeInactivePaths( trans, nextSteps ); } else { disabledInHops.forEach( trans::removeTransHop ); } } } } /** * Removes input steps having only disabled output hops so they will not be executed. * @param transMeta transMeta to process */ private static void removeUnusedInputs( TransMeta transMeta ) { List<StepMeta> unusedInputs = findHops( transMeta, hop -> !hop.isEnabled() ).stream() .map( hop -> hop.getFromStep() ) .filter( step -> isUnusedInput( transMeta, step ) ) .collect( Collectors.toList() ); for ( StepMeta unusedInput : unusedInputs ) { transMeta.findAllTransHopFrom( unusedInput ).forEach( transMeta::removeTransHop ); transMeta.getSteps().remove( unusedInput ); } } private static List<TransHopMeta> findHops( TransMeta trans, Predicate<TransHopMeta> condition ) { return IntStream.range( 0, trans.nrTransHops() ).mapToObj( trans::getTransHop ).filter( condition ).collect( Collectors.toList() ); } private static boolean isUnusedInput( TransMeta trans, StepMeta step ) { int nrEnabledOutHops = findHops( trans, hop -> hop.getFromStep().equals( step ) && hop.isEnabled() ).size(); int nrDisabledOutHops = findHops( trans, hop -> hop.getFromStep().equals( step ) && !hop.isEnabled() ).size(); int nrInputHops = findHops( trans, hop -> hop.getToStep().equals( step ) ).size(); return ( nrEnabledOutHops == 0 && nrDisabledOutHops > 0 && nrInputHops == 0 ); } }
apache-2.0
EvilGreenArmy/ams
src/main/java/com/ams/controller/admin/LoginController.java
5772
package com.ams.controller.admin; import com.ams.entities.admin.UserInfo; import com.ams.service.admin.MessageService; import com.ams.service.admin.SourceService; import com.ams.service.admin.UserService; import com.ams.util.Constant; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 登录控制器. * Created by Evan on 2016/3/21. */ @Controller @RequestMapping("/admin") public class LoginController extends BaseController { @Autowired private UserService userService; @Autowired private SourceService sourceService; @Autowired private MessageService messageService; @RequestMapping(value = "index", method = RequestMethod.GET) public String index(String userName, String password, HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam(value="t", required = false, defaultValue = "") String type) { return "login/login"+type; } @RequestMapping(value = "login", method = RequestMethod.POST) public String doLogin(String userName, String password, HttpServletRequest request, HttpServletResponse response, Model model) { UserInfo user = this.userService.getUserByLogin(userName, password); if (user != null) { if (Constant.ACTIVE_STATUS.equalsIgnoreCase(user.getStatus())) { HttpSession session = getSession(request); session.setAttribute(Constant.SESSION_LOGIN_USER, user); StringBuffer basePath = new StringBuffer(); basePath.append(request.getScheme()).append("://"); basePath.append(request.getServerName()).append(":"); basePath.append(request.getServerPort()).append(request.getContextPath()); session.setAttribute(Constant.BASE_PATH, basePath.toString()); return "redirect:/admin/main.do"; } else { model.addAttribute("errMsg", "当前用户已被禁止登录"); return "login/login"; } } else { model.addAttribute("errMsg", "用户名或密码错误"); return "login/login"; } } @RequestMapping(value = "main", method = RequestMethod.GET) public String main(HttpServletRequest request, HttpServletResponse response, Model model) { HttpSession session = getSession(request); UserInfo user = (UserInfo)session.getAttribute(Constant.SESSION_LOGIN_USER); //一级菜单 model.addAttribute("parentList", sourceService.getParentSource(user)); //二级菜单 model.addAttribute("menuList", sourceService.getChildrenSource(user)); //未读消息数量 model.addAttribute("UnreadMessages", messageService.queryUnreadMessage(user.getId())); return "base.definition"; } @RequestMapping(value = "modifyPassword", method = RequestMethod.GET) public String initModifyPassword(HttpServletRequest request, HttpServletResponse response, Model model) { return "user/password"; } @RequestMapping(value = "modifyPassword", method = RequestMethod.POST) public @ResponseBody String modifyPassword(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, @RequestParam("newPasswordReply") String newPasswordReply) { UserInfo user = (UserInfo)getSession(request).getAttribute(Constant.SESSION_LOGIN_USER); if(!this.userService.encodePassword(oldPassword).equals(user.getPassword())) { return "{\"state\":\"0\", \"errMsg\":\"原密码不正确!\"}"; } if(!newPassword.equals(newPasswordReply)) { return "{\"state\":\"0\", \"errMsg\":\"两次密码不一致!\"}"; } newPassword = this.userService.encodePassword(newPassword); user.setPassword(newPassword); this.userService.modifyPassword(user); getSession(request).setAttribute(Constant.SESSION_LOGIN_USER, user); return "{\"state\":\"1\", \"errMsg\":\"\"}"; } @RequestMapping(value = "register", method = RequestMethod.GET) public String initRegister(HttpServletRequest request, HttpServletResponse response, Model model) { HttpSession session = getSession(request); StringBuffer basePath = new StringBuffer(); basePath.append(request.getScheme()).append("://"); basePath.append(request.getServerName()).append(":"); basePath.append(request.getServerPort()).append(request.getContextPath()); session.setAttribute(Constant.BASE_PATH, basePath.toString()); return "login/register"; } @RequestMapping(value = "register", method = RequestMethod.POST) public String register(HttpServletRequest request, HttpServletResponse response, Model model, UserInfo userInfo) { userInfo.setStatus(Constant.ACTIVE_STATUS); this.userService.saveUser(userInfo); return "login/login"; } }
apache-2.0
anandimous/Master_Labyrinth-Game
Stage_2/src/tests/player/GetHasInsertedThisTurnTests.java
3984
package tests.player; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import code.gui.GameBoardGUI; import code.model.GameBoard; import code.model.MoveableTile; import code.model.Player; public class GetHasInsertedThisTurnTests { @Test public void test0() { GameBoard gb = new GameBoard(4); ArrayList<MoveableTile> al = staticMoveableTileArray1(); gb.populateStaticMoveableTileArray(al); gb.setupStaticBoard(); GameBoardGUI gbGUI = new GameBoardGUI(gb); gbGUI.run(); Player p = gb.getPlayers()[0]; p.insertShiftableTile(41); boolean expected = p.getHasInsertedThisTurn(); boolean actual = true; assertTrue("",expected==actual); } @Test public void test1() { GameBoard gb = new GameBoard(4); ArrayList<MoveableTile> al = staticMoveableTileArray1(); gb.populateStaticMoveableTileArray(al); gb.setupStaticBoard(); GameBoardGUI gbGUI = new GameBoardGUI(gb); gbGUI.run(); Player p = gb.getPlayers()[0]; boolean expected = p.getHasInsertedThisTurn(); boolean actual = false; assertTrue("",expected==actual); } public ArrayList<MoveableTile> staticMoveableTileArray1(){ ArrayList<MoveableTile> al = new ArrayList<MoveableTile>(); //MOveableCol1 MoveableTile m1 = new MoveableTile("I"); al.add(m1); MoveableTile m2 = new MoveableTile("I"); al.add(m2); MoveableTile m3 = new MoveableTile("I"); m3.rotate(90); al.add(m3); MoveableTile m4 = new MoveableTile("I"); m4.rotate(90); al.add(m4); MoveableTile m5 = new MoveableTile("L"); m5.rotate(90); al.add(m5); MoveableTile m6 = new MoveableTile("I"); m6.rotate(90); al.add(m6); MoveableTile m7 = new MoveableTile("I"); al.add(m7); //MoveableCol2 MoveableTile m8 = new MoveableTile("L"); m8.rotate(180); al.add(m8); MoveableTile m9 = new MoveableTile("I"); m9.rotate(90); al.add(m9); MoveableTile m10 = new MoveableTile("T"); al.add(m10); MoveableTile m11 = new MoveableTile("I"); m11.rotate(0); al.add(m11); MoveableTile m12 = new MoveableTile("L"); m12.rotate(0); al.add(m12); MoveableTile m13 = new MoveableTile("T"); m13.rotate(0); al.add(m13); MoveableTile m14 = new MoveableTile("L"); m14.rotate(0); al.add(m14); //MoveableCol3 MoveableTile m15 = new MoveableTile("L"); al.add(m15); MoveableTile m16 = new MoveableTile("T"); m16.rotate(0); al.add(m16); MoveableTile m17 = new MoveableTile("L"); al.add(m17); MoveableTile m18 = new MoveableTile("L"); m18.rotate(180); al.add(m18); MoveableTile m19 = new MoveableTile("T"); m19.rotate(90); al.add(m19); MoveableTile m20 = new MoveableTile("L"); m20.rotate(180); al.add(m20); MoveableTile m21 = new MoveableTile("T"); m21.rotate(90); al.add(m21); //MoveableRow1 MoveableTile m22 = new MoveableTile("T"); m22.rotate(0); al.add(m22); MoveableTile m23 = new MoveableTile("L"); m23.rotate(90); al.add(m23); MoveableTile m24 = new MoveableTile("I"); m24.rotate(0); al.add(m24); MoveableTile m25 = new MoveableTile("L"); m25.rotate(90); al.add(m25); //MoveableRow2 MoveableTile m26 = new MoveableTile("L"); m26.rotate(90); al.add(m26); MoveableTile m27 = new MoveableTile("I"); m27.rotate(90); al.add(m27); MoveableTile m28 = new MoveableTile("L"); m28.rotate(0); al.add(m28); MoveableTile m29 = new MoveableTile("L"); m29.rotate(90); al.add(m29); //MoveableRow3 MoveableTile m30 = new MoveableTile("L"); m30.rotate(0); al.add(m30); MoveableTile m31 = new MoveableTile("I"); m31.rotate(0); al.add(m31); MoveableTile m32 = new MoveableTile("I"); m32.rotate(90); al.add(m32); MoveableTile m33 = new MoveableTile("I"); m33.rotate(90); al.add(m33); MoveableTile m34 = new MoveableTile("L"); al.add(m34); return al; } }
apache-2.0
Clinical3PO/Platform
dev/ML-Flex/Internals/Java/helper/AnalysisFileCreator.java
17639
// THIS SOURCE CODE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND, AND ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR NON INFRINGEMENT. THE USER ASSUMES ALL LIABILITY AND RESPONSIBILITY FOR USE OF THIS SOURCE CODE, AND NEITHER THE AUTHOR NOR JMLR, NOR JMLR'S PUBLISHERS AND DISTRIBUTORS, WILL BE LIABLE FOR DAMAGES OF ANY KIND RESULTING FROM ITS USE. Without lim- iting the generality of the foregoing, neither the author, nor JMLR, nor JMLR's publishers and distributors, warrant that the Source Code will be error-free, will operate without interruption, or will meet the needs of the user. // // -------------------------------------------------------------------------- // // Copyright 2016 Stephen Piccolo // // This file is part of ML-Flex. // // ML-Flex is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // ML-Flex is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ML-Flex. If not, see <http://www.gnu.org/licenses/>. package mlflex.helper; import mlflex.core.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; /** This class is used to transform data from the ML-Flex data format to the format that is required for external software components. * @author Stephen Piccolo */ public class AnalysisFileCreator { /** These represent file extensions */ public enum Extension { ARFF(".arff"), ORANGE(".tab"), GCT(".gct"), CLS(".cls"), SURVIVAL("_survival.txt"), TAB(".tab"), C5NAMES(".names"), C5TRAINDATA(".data"), C5TESTDATA(".cases"); private final String _extension; Extension(String extension) { _extension = extension; } @Override public String toString() { return _extension; } } private String _outputDir; private String _fileNamePrefix; private DataInstanceCollection _dataInstances; private DataInstanceCollection _otherInstances; private boolean _includeDependentVariable; private ArrayList<String> _features; /** Constructor * * @param outputDirectory Absolute path of directory where files will be saved * @param fileNamePrefix Text that will be prepended to each file name that is saved * @param dataInstances Collection of data dataInstances * @param otherInstances Collection of other data instances that may be necessary for determining all options for a given data point (may be left null) * @param includeDependentVariable Whether to include dependent-variable values in the output */ public AnalysisFileCreator(String outputDirectory, String fileNamePrefix, DataInstanceCollection dataInstances, DataInstanceCollection otherInstances, boolean includeDependentVariable, ArrayList<String> features) { _outputDir = outputDirectory; _fileNamePrefix = fileNamePrefix; _dataInstances = dataInstances; _otherInstances = otherInstances; _includeDependentVariable = includeDependentVariable; _features = features; } private String GetDependentVariableValue(String instanceID) throws Exception { return Singletons.InstanceVault.GetDependentVariableValue(instanceID); } /** Generates files in the ARFF format. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateArffFile() throws Exception { String outFilePath = GetFilePath(Extension.ARFF); PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(outFilePath))); outFile.write("@relation thedata\n\n"); Singletons.Log.Debug("Sorting data point names"); ArrayList<String> dataPointNames = ListUtilities.SortStringList(ListUtilities.Intersect(_features, _dataInstances.GetDataPointNames())); Singletons.Log.Debug("Sorting instance IDs"); ArrayList<String> instanceIDs = ListUtilities.SortStringList(_dataInstances.GetIDs()); Singletons.Log.Debug("Appending ARFF attributes for independent variables"); for (String dataPointName : dataPointNames) { HashSet<String> uniqueValues = new HashSet<String>(_dataInstances.GetUniqueValues(dataPointName)); if (_otherInstances != null) uniqueValues.addAll(_otherInstances.GetUniqueValues(dataPointName)); AppendArffAttribute(new ArrayList<String>(uniqueValues), dataPointName, outFile); } Singletons.Log.Debug("Appending ARFF attributes for dependent variable"); if (_includeDependentVariable) AppendArffAttribute(Singletons.InstanceVault.DependentVariableOptions, Singletons.ProcessorVault.DependentVariableDataProcessor.DataPointName, outFile); outFile.write("\n@data"); Singletons.Log.Debug("Creating ARFF output text object"); for (String instanceID : instanceIDs) { for (String x : _dataInstances.GetDataPointValues(instanceID, dataPointNames)) if (x == null) { Singletons.Log.Info("null value found!!!"); Singletons.Log.Info(dataPointNames); Singletons.Log.Info(_dataInstances.GetDataPointValues(instanceID, dataPointNames)); System.exit(0); } outFile.write("\n" + ListUtilities.Join(FormatOutputValues(_dataInstances.GetDataPointValues(instanceID, dataPointNames)), ",")); if (_includeDependentVariable) outFile.write("," + FormatOutputValue(GetDependentVariableValue(instanceID))); } outFile.close(); return this; } private void AppendArffAttribute(ArrayList<String> values, String dataPointName, PrintWriter outFile) throws Exception { outFile.write("@attribute " + dataPointName + " "); if (DataTypeUtilities.HasOnlyBinary(values)) outFile.write("{" + ListUtilities.Join(ListUtilities.SortStringList(values), ",") + "}"); else { if (DataTypeUtilities.HasOnlyNumeric(values)) outFile.write("real"); else { FormatOutputValues(values); outFile.write("{" + ListUtilities.Join(ListUtilities.SortStringList(values), ",") + "}"); } } outFile.write("\n"); } /** This method generates a basic tab-delimited file with variables as rows and instances as columns. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateTabDelimitedFile() throws Exception { PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(GetTabDelimitedFilePath()))); ArrayList<String> dataPoints = ListUtilities.SortStringList(ListUtilities.Intersect(_features, _dataInstances.GetDataPointNames())); ArrayList<String> instanceIDs = ListUtilities.SortStringList(_dataInstances.GetIDs()); ArrayList<String> headerItems = MiscUtilities.UnformatNames(instanceIDs); headerItems.add(0, ""); outFile.write(ListUtilities.Join(headerItems, "\t") + "\n"); for (String dataPoint : dataPoints) { ArrayList<String> rowItems = ListUtilities.CreateStringList(dataPoint); for (String instanceID : instanceIDs) rowItems.add(_dataInstances.GetDataPointValue(instanceID, dataPoint)); rowItems = ListUtilities.ReplaceAllExactMatches(rowItems, Settings.MISSING_VALUE_STRING, "NA"); FormatOutputValues(rowItems); outFile.write(ListUtilities.Join(rowItems, "\t") + "\n"); } if (_includeDependentVariable) { ArrayList<String> rowItems = ListUtilities.CreateStringList(Singletons.ProcessorVault.DependentVariableDataProcessor.DataPointName); for (String instanceID : instanceIDs) rowItems.add(Singletons.InstanceVault.GetDependentVariableValue(instanceID)); outFile.write(ListUtilities.Join(rowItems, "\t") + "\n"); } outFile.close(); return this; } /** This method generates a transposed tab-delimited file with variables as columns and instances as rows. * @param includeInstanceIDs Whether to include the ID of each instance in the file * @return This instance * @throws Exception */ public AnalysisFileCreator CreateTransposedTabDelimitedFile(boolean includeInstanceIDs) throws Exception { PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(GetTabDelimitedFilePath()))); ArrayList<String> dataPointNames = ListUtilities.SortStringList(ListUtilities.Intersect(_features, _dataInstances.GetDataPointNames())); ArrayList<String> headerDataPoints = MiscUtilities.UnformatNames(new ArrayList<String>(dataPointNames)); if (includeInstanceIDs) headerDataPoints.add(0, "ID"); if (_includeDependentVariable) headerDataPoints.add(Singletons.ProcessorVault.DependentVariableDataProcessor.DataPointName); outFile.write(ListUtilities.Join(headerDataPoints, "\t") + "\n"); for (String instanceID : _dataInstances) { ArrayList<String> values = _dataInstances.GetDataPointValues(instanceID, dataPointNames); if (includeInstanceIDs) values.add(0, instanceID); if (_includeDependentVariable) values.add(GetDependentVariableValue(instanceID)); values = ListUtilities.ReplaceAllExactMatches(values, Settings.MISSING_VALUE_STRING, "NA"); FormatOutputValues(values); outFile.write(ListUtilities.Join(values, "\t") + "\n"); } outFile.close(); return this; } /** This method generates a text file in the format required by the Orange machine-learning framework. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateOrangeFile() throws Exception { DataInstanceCollection instances = _dataInstances; String outFilePath = GetFilePath(Extension.ORANGE); ArrayList<String> dataPointNames = ListUtilities.SortStringList(ListUtilities.Intersect(_features, _dataInstances.GetDataPointNames())); String header = ListUtilities.Join(dataPointNames, "\t"); header += _includeDependentVariable ? "\t" + Singletons.ProcessorVault.DependentVariableDataProcessor.DataPointName : ""; header += "\n" + ListUtilities.Join(GetOrangeAttributeHeader(instances, dataPointNames), "\t"); header += _includeDependentVariable ? "\td" : ""; header += "\n" + ListUtilities.Join(ListUtilities.CreateStringList("", dataPointNames.size() + 1), "\t"); header += _includeDependentVariable ? "class" : ""; header += "\n"; FileUtilities.WriteTextToFile(outFilePath, header); for (String instanceID : instances) { String line = ListUtilities.Join(FormatOutputValues(_dataInstances.GetDataPointValues(instanceID, dataPointNames)), "\t"); if (_includeDependentVariable) line += "\t" + FormatOutputValue(GetDependentVariableValue(instanceID)); FileUtilities.AppendTextToFile(outFilePath, line + "\n"); } return this; } private ArrayList<String> GetOrangeAttributeHeader(DataInstanceCollection instances, ArrayList<String> dataPointNames) { ArrayList<String> results = new ArrayList<String>(); for (String dataPointName : dataPointNames) { ArrayList<String> uniqueValues = instances.GetUniqueValues(dataPointName); results.add((DataTypeUtilities.HasOnlyNumeric(uniqueValues) && !DataTypeUtilities.HasOnlyBinary(uniqueValues)) ? "c" : "d"); } return results; } /** This method creates text files in the format required by the C5.0 software. Specifically, it generates .names files. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateC5NamesFile() throws Exception { StringBuilder output = new StringBuilder(); output.append(ListUtilities.Join(Singletons.InstanceVault.DependentVariableOptions, ", ") + ".\n\n"); ArrayList<String> dataPointNames = ListUtilities.SortStringList(ListUtilities.Intersect(_features, _dataInstances.GetDataPointNames())); for (String dataPointName : dataPointNames) { output.append(dataPointName + ":\t"); ArrayList<String> uniqueDataValues = _dataInstances.GetUniqueValues(dataPointName); if (DataTypeUtilities.HasOnlyNumeric(uniqueDataValues) && !DataTypeUtilities.HasOnlyBinary(uniqueDataValues)) output.append("continuous"); else { AnalysisFileCreator.FormatOutputValues(uniqueDataValues); output.append(ListUtilities.Join(uniqueDataValues, ", ")); } output.append(".\n"); } FileUtilities.WriteTextToFile(GetC5NamesFilePath(), output.toString()); return this; } /** This method creates text files in the format required by the C5.0 software. Specifically, it generates a .data file to be used for training a model. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateC5TrainDataFile() throws Exception { return CreateC5DataFile(GetC5TrainDataFilePath(), false); } /** This method creates text files in the format required by the C5.0 software. Specifically, it generates a .data file to be used for Action. * @return This instance * @throws Exception */ public AnalysisFileCreator CreateC5TestDataFile() throws Exception { return CreateC5DataFile(GetC5TestDataFilePath(), true); } private AnalysisFileCreator CreateC5DataFile(String filePath, boolean areTestInstances) throws Exception { StringBuilder output = new StringBuilder(); for (String instanceID : _dataInstances) { ArrayList<String> values = _dataInstances.GetDataPointValues(instanceID, _dataInstances.GetDataPointNames()); values.add(areTestInstances ? "?" : GetDependentVariableValue(instanceID)); output.append(ListUtilities.Join(values, ",") + "\n"); } FileUtilities.WriteTextToFile(filePath, output.toString()); return this; } /** Deletes an analysis file that has already been created. * @param extension File extension * @throws Exception */ public void DeleteFile(Extension extension) throws Exception { FileUtilities.DeleteFile(GetFilePath(extension)); } /** Deletes an ARFF file that has already been created. * @throws Exception */ public void DeleteArffFile() throws Exception { DeleteFile(Extension.ARFF); } /** Deletes an Orange file that has already been created. * @throws Exception */ public void DeleteOrangeFile() throws Exception { DeleteFile(Extension.ORANGE); } // public void DeleteMlpyFile() throws Exception // { // DeleteFile(Extension.MLPY); // } /** Deletes a tab-delimited file that has already been created. * * @throws Exception */ public void DeleteTabDelimitedFile() throws Exception { DeleteFile(Extension.TAB); } /** Deletes a tab-delimited file that has already been created. * * @throws Exception */ public void DeleteTransposedTabDelimitedFile() throws Exception { DeleteFile(Extension.TAB); } private String GetFilePath(Extension extension) { return _outputDir + _fileNamePrefix + extension.toString(); } public String GetArffFilePath() { return GetFilePath(Extension.ARFF); } public String GetTabDelimitedFilePath() { return GetFilePath(Extension.TAB); } public String GetTransposedTabDelimitedFilePath() { return GetFilePath(Extension.TAB); } public String GetC5NamesFilePath() { return GetFilePath(Extension.C5NAMES); } public String GetC5TrainDataFilePath() { return GetFilePath(Extension.C5TRAINDATA); } public String GetC5TestDataFilePath() { return GetFilePath(Extension.C5TESTDATA); } public String GetOrangeFilePath() { return GetFilePath(Extension.ORANGE); } // public String GetMlpyFilePath() // { // return GetFilePath(Extension.MLPY); // } public static ArrayList<String> FormatOutputValues(ArrayList<String> values) { for (int i = 0; i < values.size(); i++) values.set(i, FormatOutputValue(values.get(i))); return values; } public static String FormatOutputValue(String value) { return value.replace(" ", "_"); } }
apache-2.0
izaynutdinov/java-examples
project-management/src/main/java/net/iskandar/examples/project_management/jsf/breadcrumb/AddProjectItem.java
551
/* * 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 net.iskandar.examples.project_management.jsf.breadcrumb; import java.io.DataInputStream; import java.io.IOException; /** * * @author iskandar */ public class AddProjectItem extends BaseItem { public AddProjectItem() { super("addProject"); } @Override protected String createLabel() { return "Add Project"; } }
apache-2.0
mbrukman/gcloud-java
google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/GroupServiceSettings.java
10025
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.monitoring.v3; import static com.google.cloud.monitoring.v3.PagedResponseWrappers.ListGroupMembersPagedResponse; import static com.google.cloud.monitoring.v3.PagedResponseWrappers.ListGroupsPagedResponse; 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.PagedCallSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.monitoring.v3.stub.GroupServiceStubSettings; import com.google.monitoring.v3.CreateGroupRequest; import com.google.monitoring.v3.DeleteGroupRequest; import com.google.monitoring.v3.GetGroupRequest; import com.google.monitoring.v3.Group; import com.google.monitoring.v3.ListGroupMembersRequest; import com.google.monitoring.v3.ListGroupMembersResponse; import com.google.monitoring.v3.ListGroupsRequest; import com.google.monitoring.v3.ListGroupsResponse; import com.google.monitoring.v3.UpdateGroupRequest; import com.google.protobuf.Empty; 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 GroupServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (monitoring.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. For * example, to set the total timeout of getGroup to 30 seconds: * * <pre> * <code> * GroupServiceSettings.Builder groupServiceSettingsBuilder = * GroupServiceSettings.newBuilder(); * groupServiceSettingsBuilder.getGroupSettings().getRetrySettingsBuilder() * .setTotalTimeout(Duration.ofSeconds(30)); * GroupServiceSettings groupServiceSettings = groupServiceSettingsBuilder.build(); * </code> * </pre> */ @Generated("by GAPIC v0.0.5") @BetaApi public class GroupServiceSettings extends ClientSettings<GroupServiceSettings> { /** Returns the object with the settings used for calls to listGroups. */ public PagedCallSettings<ListGroupsRequest, ListGroupsResponse, ListGroupsPagedResponse> listGroupsSettings() { return ((GroupServiceStubSettings) getStubSettings()).listGroupsSettings(); } /** Returns the object with the settings used for calls to getGroup. */ public UnaryCallSettings<GetGroupRequest, Group> getGroupSettings() { return ((GroupServiceStubSettings) getStubSettings()).getGroupSettings(); } /** Returns the object with the settings used for calls to createGroup. */ public UnaryCallSettings<CreateGroupRequest, Group> createGroupSettings() { return ((GroupServiceStubSettings) getStubSettings()).createGroupSettings(); } /** Returns the object with the settings used for calls to updateGroup. */ public UnaryCallSettings<UpdateGroupRequest, Group> updateGroupSettings() { return ((GroupServiceStubSettings) getStubSettings()).updateGroupSettings(); } /** Returns the object with the settings used for calls to deleteGroup. */ public UnaryCallSettings<DeleteGroupRequest, Empty> deleteGroupSettings() { return ((GroupServiceStubSettings) getStubSettings()).deleteGroupSettings(); } /** Returns the object with the settings used for calls to listGroupMembers. */ public PagedCallSettings< ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings() { return ((GroupServiceStubSettings) getStubSettings()).listGroupMembersSettings(); } public static final GroupServiceSettings create(GroupServiceStubSettings stub) throws IOException { return new GroupServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return GroupServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return GroupServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return GroupServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GroupServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return GroupServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return GroupServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return GroupServiceStubSettings.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 GroupServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for GroupServiceSettings. */ public static class Builder extends ClientSettings.Builder<GroupServiceSettings, Builder> { protected Builder() throws IOException { this((ClientContext) null); } protected Builder(ClientContext clientContext) { super(GroupServiceStubSettings.newBuilder(clientContext)); } private static Builder createDefault() { return new Builder(GroupServiceStubSettings.newBuilder()); } protected Builder(GroupServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(GroupServiceStubSettings.Builder stubSettings) { super(stubSettings); } public GroupServiceStubSettings.Builder getStubSettingsBuilder() { return ((GroupServiceStubSettings.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) throws Exception { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to listGroups. */ public PagedCallSettings.Builder<ListGroupsRequest, ListGroupsResponse, ListGroupsPagedResponse> listGroupsSettings() { return getStubSettingsBuilder().listGroupsSettings(); } /** Returns the builder for the settings used for calls to getGroup. */ public UnaryCallSettings.Builder<GetGroupRequest, Group> getGroupSettings() { return getStubSettingsBuilder().getGroupSettings(); } /** Returns the builder for the settings used for calls to createGroup. */ public UnaryCallSettings.Builder<CreateGroupRequest, Group> createGroupSettings() { return getStubSettingsBuilder().createGroupSettings(); } /** Returns the builder for the settings used for calls to updateGroup. */ public UnaryCallSettings.Builder<UpdateGroupRequest, Group> updateGroupSettings() { return getStubSettingsBuilder().updateGroupSettings(); } /** Returns the builder for the settings used for calls to deleteGroup. */ public UnaryCallSettings.Builder<DeleteGroupRequest, Empty> deleteGroupSettings() { return getStubSettingsBuilder().deleteGroupSettings(); } /** Returns the builder for the settings used for calls to listGroupMembers. */ public PagedCallSettings.Builder< ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings() { return getStubSettingsBuilder().listGroupMembersSettings(); } @Override public GroupServiceSettings build() throws IOException { return new GroupServiceSettings(this); } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/transform/DeleteExternalModelRequestMarshaller.java
2083
/* * 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.frauddetector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.frauddetector.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteExternalModelRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteExternalModelRequestMarshaller { private static final MarshallingInfo<String> MODELENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("modelEndpoint").build(); private static final DeleteExternalModelRequestMarshaller instance = new DeleteExternalModelRequestMarshaller(); public static DeleteExternalModelRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteExternalModelRequest deleteExternalModelRequest, ProtocolMarshaller protocolMarshaller) { if (deleteExternalModelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteExternalModelRequest.getModelEndpoint(), MODELENDPOINT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
benjchristensen/RxJava
src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java
7425
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.flowable; import org.reactivestreams.Subscriber; import io.reactivex.Flowable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.ConditionalSubscriber; import io.reactivex.internal.subscriptions.*; import io.reactivex.internal.util.BackpressureHelper; public final class FlowableFromArray<T> extends Flowable<T> { final T[] array; public FlowableFromArray(T[] array) { this.array = array; } @Override public void subscribeActual(Subscriber<? super T> s) { if (s instanceof ConditionalSubscriber) { s.onSubscribe(new ArrayConditionalSubscription<T>( (ConditionalSubscriber<? super T>)s, array)); } else { s.onSubscribe(new ArraySubscription<T>(s, array)); } } abstract static class BaseArraySubscription<T> extends BasicQueueSubscription<T> { private static final long serialVersionUID = -2252972430506210021L; final T[] array; int index; volatile boolean cancelled; BaseArraySubscription(T[] array) { this.array = array; } @Override public final int requestFusion(int mode) { return mode & SYNC; } @Override public final T poll() { int i = index; T[] arr = array; if (i == arr.length) { return null; } index = i + 1; return ObjectHelper.requireNonNull(arr[i], "array element is null"); } @Override public final boolean isEmpty() { return index == array.length; } @Override public final void clear() { index = array.length; } @Override public final void request(long n) { if (SubscriptionHelper.validate(n)) { if (BackpressureHelper.add(this, n) == 0L) { if (n == Long.MAX_VALUE) { fastPath(); } else { slowPath(n); } } } } @Override public final void cancel() { cancelled = true; } abstract void fastPath(); abstract void slowPath(long r); } static final class ArraySubscription<T> extends BaseArraySubscription<T> { private static final long serialVersionUID = 2587302975077663557L; final Subscriber<? super T> actual; ArraySubscription(Subscriber<? super T> actual, T[] array) { super(array); this.actual = actual; } @Override void fastPath() { T[] arr = array; int f = arr.length; Subscriber<? super T> a = actual; for (int i = index; i != f; i++) { if (cancelled) { return; } T t = arr[i]; if (t == null) { a.onError(new NullPointerException("array element is null")); return; } else { a.onNext(t); } } if (cancelled) { return; } a.onComplete(); } @Override void slowPath(long r) { long e = 0; T[] arr = array; int f = arr.length; int i = index; Subscriber<? super T> a = actual; for (;;) { while (e != r && i != f) { if (cancelled) { return; } T t = arr[i]; if (t == null) { a.onError(new NullPointerException("array element is null")); return; } else { a.onNext(t); } e++; i++; } if (i == f) { if (!cancelled) { a.onComplete(); } return; } r = get(); if (e == r) { index = i; r = addAndGet(-e); if (r == 0L) { return; } e = 0L; } } } } static final class ArrayConditionalSubscription<T> extends BaseArraySubscription<T> { private static final long serialVersionUID = 2587302975077663557L; final ConditionalSubscriber<? super T> actual; ArrayConditionalSubscription(ConditionalSubscriber<? super T> actual, T[] array) { super(array); this.actual = actual; } @Override void fastPath() { T[] arr = array; int f = arr.length; ConditionalSubscriber<? super T> a = actual; for (int i = index; i != f; i++) { if (cancelled) { return; } T t = arr[i]; if (t == null) { a.onError(new NullPointerException("array element is null")); return; } else { a.tryOnNext(t); } } if (cancelled) { return; } a.onComplete(); } @Override void slowPath(long r) { long e = 0; T[] arr = array; int f = arr.length; int i = index; ConditionalSubscriber<? super T> a = actual; for (;;) { while (e != r && i != f) { if (cancelled) { return; } T t = arr[i]; if (t == null) { a.onError(new NullPointerException("array element is null")); return; } else { if (a.tryOnNext(t)) { e++; } i++; } } if (i == f) { if (!cancelled) { a.onComplete(); } return; } r = get(); if (e == r) { index = i; r = addAndGet(-e); if (r == 0L) { return; } e = 0L; } } } } }
apache-2.0
adbrucker/SecureBPMN
designer/src/org.activiti.designer.gui/src/main/java/org/activiti/designer/property/extension/util/ExtensionPropertyUtil.java
2916
/* 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.designer.property.extension.util; import org.activiti.designer.integration.servicetask.PropertyType; import org.activiti.designer.property.custom.PeriodPropertyElement; import org.apache.commons.lang.StringUtils; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Spinner; /** * Provides utilities for extension property editing. * * @author Tiese Barrell * @since 0.6.1 * @version 1 */ public final class ExtensionPropertyUtil { private ExtensionPropertyUtil() { } /** * Inspects the provided parent component and extracts the value for the * {@link PropertyType#PERIOD} enclosed. * * @param parent * the parent component */ public static final String getPeriodValueFromParent(final Composite parent) { String[] values = new String[PeriodPropertyElement.values().length]; for (final Control control : parent.getChildren()) { if (control instanceof Spinner) { final String periodKey = (String) control.getData("PERIOD_KEY"); final PeriodPropertyElement element = PeriodPropertyElement.byShortFormat(periodKey); if (element != null) { final int elementValue = ((Spinner) control).getSelection(); final String elementStringValue = elementValue + element.getShortFormat(); values[element.getOrder()] = elementStringValue; } } } final StringBuilder builder = new StringBuilder(); for (int i = 0; i < values.length; i++) { builder.append(values[i]); if (i != values.length - 1) { builder.append(" "); } } String value = builder.toString(); return value; } /** * Inspects the provided value and extracts the value for the * {@link PeriodPropertyElement} provided. * * @param parent * the parent component */ public static final int getPeriodPropertyElementFromValue(final String value, final PeriodPropertyElement propertyElement) { int result = 0; final String[] elementValues = value.split(" "); if (propertyElement != null) { final String stripped = StringUtils.substringBeforeLast(elementValues[propertyElement.getOrder()], propertyElement.getShortFormat()); result = Integer.parseInt(stripped); } return result; } }
apache-2.0