repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
LuckyJayce/EventBus-Apt
app/src/main/java/com/shizhefei/eventbusdemo/events/ISendMessageEvent.java
372
package com.shizhefei.eventbusdemo.events; import com.shizhefei.eventbus.IRemoteEvent; import com.shizhefei.eventbus.annotation.Event; import com.shizhefei.eventbus.demo.MessageCallback; /** * Created by luckyjayce on 18-3-23. */ @Event public interface ISendMessageEvent extends IRemoteEvent { void sendMessage(String content, MessageCallback messageCallback); }
apache-2.0
snuk182/aceim
app/src/main/java/aceim/app/view/page/chat/TextSmileyAdapter.java
1432
package aceim.app.view.page.chat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import aceim.app.MainActivity; import aceim.app.dataentity.SmileyResources; import aceim.app.utils.ViewUtils; import aceim.app.widgets.adapters.SingleViewAdapter; import android.content.Context; import android.view.Gravity; import android.widget.TextView; public class TextSmileyAdapter extends SingleViewAdapter<String, TextView> { private TextSmileyAdapter(Context context, List<String> objects) { super(context, objects); } @Override protected void fillView(String item, TextView view) { view.setText(item); view.setGravity(Gravity.CENTER); } public static final TextSmileyAdapter fromTypedArray(MainActivity activity){ Set<String> set = new HashSet<String>(); for (SmileyResources smr : activity.getSmileysManager().getUnmanagedSmileys()) { set.addAll(Arrays.asList(smr.getNames())); } List<String> list = new ArrayList<String>(set); for (int i=0; i<list.size(); i++) { String smiley = list.get(i); if (!ViewUtils.isSmileyReadOnly(smiley)) { list.set(i, smiley); } } return fromStringList(activity, list); } public static final TextSmileyAdapter fromStringList(Context context, List<String> list){ return new TextSmileyAdapter(context, list); } }
apache-2.0
xushaomin/apple-cache
apple-cache-springredis/src/main/java/com/appleframework/cache/redis/spring/SpringCacheManager.java
843
package com.appleframework.cache.redis.spring; import org.springframework.cache.Cache; import org.springframework.data.redis.core.RedisTemplate; import com.appleframework.cache.core.spring.BaseSpringCacheManager; public class SpringCacheManager extends BaseSpringCacheManager { private RedisTemplate<String, Object> redisTemplate; public SpringCacheManager() { } @Override public Cache getCache(String name) { Cache cache = cacheMap.get(name); if (cache == null) { Integer expire = expireMap.get(name); if (expire == null) { expire = 0; expireMap.put(name, expire); } cache = new SpringCache(redisTemplate, name, expire.intValue()); cacheMap.put(name, cache); } return cache; } public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } }
apache-2.0
leouy/arqui-java
callao-puertos/src/uy/edu/ort/main/MainBarco.java
6821
package uy.edu.ort.main; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import uy.edu.ort.api.exceptions.ServiceException; import uy.edu.ort.api.model.Barco; import uy.edu.ort.api.service.BarcoService; /** * * @author Leo */ public class MainBarco { private static BarcoService barcoService; public static void setBarcoService(BarcoService barcoService) { MainBarco.barcoService = barcoService; } public static void altaBarco() { System.out.println("------ Alta de barcos ------"); System.out.println("Ingrese todos los datos: "); System.out.print("Codigo: "); String codigo = leerEntrada(); System.out.print("Nombre: "); String nombre = leerEntrada(); System.out.print("Bandera: "); String bandera = leerEntrada(); System.out.print("Capacidad: "); String capacidad = leerEntrada(); System.out.print("Año: "); String ano = leerEntrada(); System.out.print("Tripulantes: "); String tripulantes = leerEntrada(); Barco nuevoBarco = new Barco(); try { nuevoBarco.setCodigo(codigo); nuevoBarco.setNombre(nombre); nuevoBarco.setBandera(bandera); nuevoBarco.setCapacidad(Integer.parseInt(capacidad)); nuevoBarco.setAno(Integer.parseInt(ano)); nuevoBarco.setTripulantes(Integer.parseInt(tripulantes)); barcoService.addBarco(nuevoBarco); System.out.println("Se ha ingresado el barco código: " + codigo + " correctamente."); } catch (NumberFormatException ex) { System.out.println("Ha ocurrido un error en el formato: " + ex.getMessage()); } catch (ServiceException ex) { System.out.println("Ha ocurrido un error en DB: " + ex.getMessage()); } catch (Exception ex) { System.out.println("ERROR DESCONOCIDO: " + ex.getMessage()); } } public static void modificacionBarco() { System.out.println("------ Modificacion de barcos ------"); System.out.println("Ingrese el código del barco que desea modificar: "); String codigo = leerEntrada(); String nombre = ""; String bandera = ""; String capacidad = "-1"; String ano = "-1"; String tripulantes = "-1"; System.out.print("Desea modificar Nombre: "); if (leerPregunta()) { System.out.print("Ingrese el nuevo Nombre: "); nombre = leerEntrada(); } System.out.print("Desea modificar Bandera: "); if (leerPregunta()) { System.out.print("Ingrese la nuevo Bandera: "); bandera = leerEntrada(); } System.out.print("Desea modificar Capacidad: "); if (leerPregunta()) { System.out.print("Ingrese la nueva Capacidad: "); capacidad = leerEntrada(); } System.out.print("Desea modificar Año: "); if (leerPregunta()) { System.out.print("Ingrese el nuevo Año: "); ano = leerEntrada(); } System.out.print("Desea modificar Tripulantes: "); if (leerPregunta()) { System.out.print("Ingrese el nuevo Tripulantes: "); tripulantes = leerEntrada(); } Barco nuevoBarco = new Barco(); try { nuevoBarco.setCodigo(codigo); nuevoBarco.setNombre(nombre); nuevoBarco.setBandera(bandera); nuevoBarco.setCapacidad(Integer.parseInt(capacidad)); nuevoBarco.setAno(Integer.parseInt(ano)); nuevoBarco.setTripulantes(Integer.parseInt(tripulantes)); barcoService.updateBarco(nuevoBarco); System.out.println("Se ha actualizado el barco código: " + codigo + " correctamente."); } catch (NumberFormatException ex) { System.out.println("Ha ocurrido un error en el formato: " + ex.getMessage()); } catch (ServiceException ex) { System.out.println("Ha ocurrido un error en DB: " + ex.getMessage()); } catch (Exception ex) { System.out.println("ERROR DESCONOCIDO: " + ex.getMessage()); } } public static void bajaBarco() { System.out.println("------ Baja de barcos ------"); System.out.println("Ingrese el código del barco que desea eliminar"); String input = leerEntrada(); try { barcoService.removeBarco(input); } catch (ServiceException ex) { System.out.println("Ha ocurrido un error en DB: " + ex.getMessage()); } catch (Exception ex) { System.out.println("ERROR DESCONOCIDO: " + ex.getMessage()); } } public static void listarBarcos() { System.out.println("------ Listado de barcos ------"); try { List<Barco> listadoBarcos = barcoService.listBarcos(); int index = 0; for (Barco barco : listadoBarcos) { System.out.println("" + ++index + ") " + barco); } } catch (ServiceException ex) { System.out.println("Ha ocurrido un error en DB: " + ex.getMessage()); } catch (Exception ex) { System.out.println("ERROR DESCONOCIDO: " + ex.getMessage()); } } private static String leerEntrada() { String ret = null; BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); try { String entrada = bufferRead.readLine().trim(); ret = entrada.equals("") ? null : entrada; } catch (IOException ex) { System.out.println("Ha ocurrido un error. Ingrese los datos nuevamente: " + ex.getMessage()); } return ret; } private static boolean leerPregunta() { BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); boolean correcto = false; boolean ret = false; while (!correcto) { try { System.out.println("S/N"); String entrada = bufferRead.readLine().trim().toUpperCase(); switch (entrada) { case "S": ret = true; correcto = true; break; case "N": correcto = true; break; default: break; } }catch (IOException ex) { System.out.println("Ha ocurrido un error. Ingrese los datos nuevamente: " + ex.getMessage()); } } return ret; } }
apache-2.0
mohanaraosv/commons-jcs
commons-jcs-core/src/main/java/org/apache/commons/jcs/engine/memory/shrinking/ShrinkerThread.java
7897
package org.apache.commons.jcs.engine.memory.shrinking; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.jcs.engine.behavior.ICacheElement; import org.apache.commons.jcs.engine.behavior.IElementAttributes; import org.apache.commons.jcs.engine.control.CompositeCache; import org.apache.commons.jcs.engine.control.event.behavior.ElementEventType; import org.apache.commons.jcs.engine.memory.behavior.IMemoryCache; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Set; /** * A background memory shrinker. Memory problems and concurrent modification exception caused by * acting directly on an iterator of the underlying memory cache should have been solved. * @version $Id$ */ public class ShrinkerThread<K, V> implements Runnable { /** The logger */ private static final Log log = LogFactory.getLog( ShrinkerThread.class ); /** The CompositeCache instance which this shrinker is watching */ private final CompositeCache<K, V> cache; /** Maximum memory idle time for the whole cache */ private final long maxMemoryIdleTime; /** Maximum number of items to spool per run. Default is -1, or no limit. */ private final int maxSpoolPerRun; /** Should we limit the number spooled per run. If so, the maxSpoolPerRun will be used. */ private boolean spoolLimit = false; /** * Constructor for the ShrinkerThread object. * <p> * @param cache The MemoryCache which the new shrinker should watch. */ public ShrinkerThread( CompositeCache<K, V> cache ) { super(); this.cache = cache; long maxMemoryIdleTimeSeconds = cache.getCacheAttributes().getMaxMemoryIdleTimeSeconds(); if ( maxMemoryIdleTimeSeconds < 0 ) { this.maxMemoryIdleTime = -1; } else { this.maxMemoryIdleTime = maxMemoryIdleTimeSeconds * 1000; } this.maxSpoolPerRun = cache.getCacheAttributes().getMaxSpoolPerRun(); if ( this.maxSpoolPerRun != -1 ) { this.spoolLimit = true; } } /** * Main processing method for the ShrinkerThread object */ @Override public void run() { shrink(); } /** * This method is called when the thread wakes up. First the method obtains an array of keys for * the cache region. It iterates through the keys and tries to get the item from the cache * without affecting the last access or position of the item. The item is checked for * expiration, the expiration check has 3 parts: * <ol> * <li>Has the cacheattributes.MaxMemoryIdleTimeSeconds defined for the region been exceeded? If * so, the item should be move to disk.</li> <li>Has the item exceeded MaxLifeSeconds defined in * the element attributes? If so, remove it.</li> <li>Has the item exceeded IdleTime defined in * the element attributes? If so, remove it. If there are event listeners registered for the * cache element, they will be called.</li> * </ol> * TODO Change element event handling to use the queue, then move the queue to the region and * access via the Cache. */ protected void shrink() { if ( log.isDebugEnabled() ) { log.debug( "Shrinking memory cache for: " + this.cache.getCacheName() ); } IMemoryCache<K, V> memCache = cache.getMemoryCache(); try { Set<K> keys = memCache.getKeySet(); int size = keys.size(); if ( log.isDebugEnabled() ) { log.debug( "Keys size: " + size ); } ICacheElement<K, V> cacheElement; IElementAttributes attributes; int spoolCount = 0; for (K key : keys) { cacheElement = memCache.getQuiet( key ); if ( cacheElement == null ) { continue; } attributes = cacheElement.getElementAttributes(); boolean remove = false; long now = System.currentTimeMillis(); // If the element is not eternal, check if it should be // removed and remove it if so. if ( !cacheElement.getElementAttributes().getIsEternal() ) { remove = cache.isExpired( cacheElement, now, ElementEventType.EXCEEDED_MAXLIFE_BACKGROUND, ElementEventType.EXCEEDED_IDLETIME_BACKGROUND ); if ( remove ) { memCache.remove( cacheElement.getKey() ); } } // If the item is not removed, check is it has been idle // long enough to be spooled. if ( !remove && maxMemoryIdleTime != -1 ) { if ( !spoolLimit || spoolCount < this.maxSpoolPerRun ) { final long lastAccessTime = attributes.getLastAccessTime(); if ( lastAccessTime + maxMemoryIdleTime < now ) { if ( log.isDebugEnabled() ) { log.debug( "Exceeded memory idle time: " + cacheElement.getKey() ); } // Shouldn't we ensure that the element is // spooled before removing it from memory? // No the disk caches have a purgatory. If it fails // to spool that does not affect the // responsibilities of the memory cache. spoolCount++; memCache.remove( cacheElement.getKey() ); memCache.waterfal( cacheElement ); key = null; cacheElement = null; } } else { if ( log.isDebugEnabled() ) { log.debug( "spoolCount = '" + spoolCount + "'; " + "maxSpoolPerRun = '" + maxSpoolPerRun + "'" ); } // stop processing if limit has been reached. if ( spoolLimit && spoolCount >= this.maxSpoolPerRun ) { keys = null; return; } } } } } catch ( Throwable t ) { log.info( "Unexpected trouble in shrink cycle", t ); // concurrent modifications should no longer be a problem // It is up to the IMemoryCache to return an array of keys // stop for now return; } } }
apache-2.0
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/domain/KoubeiMarketingCampaignItemQueryModel.java
1800
package cn.felord.wepay.ali.sdk.api.domain; import cn.felord.wepay.ali.sdk.api.AlipayObject; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; /** * 商户商品券查询接口 * * @author auto create * @version $Id: $Id */ public class KoubeiMarketingCampaignItemQueryModel extends AlipayObject { private static final long serialVersionUID = 5519297885118683244L; /** * 商品id */ @ApiField("item_id") private String itemId; /** * 操作人id */ @ApiField("operator_id") private String operatorId; /** * 操作员类型,MER=商户 */ @ApiField("operator_type") private String operatorType; /** * <p>Getter for the field <code>itemId</code>.</p> * * @return a {@link java.lang.String} object. */ public String getItemId() { return this.itemId; } /** * <p>Setter for the field <code>itemId</code>.</p> * * @param itemId a {@link java.lang.String} object. */ public void setItemId(String itemId) { this.itemId = itemId; } /** * <p>Getter for the field <code>operatorId</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorId() { return this.operatorId; } /** * <p>Setter for the field <code>operatorId</code>.</p> * * @param operatorId a {@link java.lang.String} object. */ public void setOperatorId(String operatorId) { this.operatorId = operatorId; } /** * <p>Getter for the field <code>operatorType</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorType() { return this.operatorType; } /** * <p>Setter for the field <code>operatorType</code>.</p> * * @param operatorType a {@link java.lang.String} object. */ public void setOperatorType(String operatorType) { this.operatorType = operatorType; } }
apache-2.0
sdinot/hipparchus
hipparchus-core/src/main/java/org/hipparchus/linear/IterativeLinearSolverEvent.java
4669
/* * 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. */ /* * This is not the original file distributed by the Apache Software Foundation * It has been modified by the Hipparchus project */ package org.hipparchus.linear; import org.hipparchus.exception.LocalizedCoreFormats; import org.hipparchus.exception.MathRuntimeException; import org.hipparchus.util.IterationEvent; /** * This is the base class for all events occurring during the iterations of a * {@link IterativeLinearSolver}. * */ public abstract class IterativeLinearSolverEvent extends IterationEvent { /** Serialization identifier. */ private static final long serialVersionUID = 20120129L; /** * Creates a new instance of this class. * * @param source the iterative algorithm on which the event initially * occurred * @param iterations the number of iterations performed at the time * {@code this} event is created */ public IterativeLinearSolverEvent(final Object source, final int iterations) { super(source, iterations); } /** * Returns the current right-hand side of the linear system to be solved. * This method should return an unmodifiable view, or a deep copy of the * actual right-hand side vector, in order not to compromise subsequent * iterations of the source {@link IterativeLinearSolver}. * * @return the right-hand side vector, b */ public abstract RealVector getRightHandSideVector(); /** * Returns the norm of the residual. The returned value is not required to * be <em>exact</em>. Instead, the norm of the so-called <em>updated</em> * residual (if available) should be returned. For example, the * {@link ConjugateGradient conjugate gradient} method computes a sequence * of residuals, the norm of which is cheap to compute. However, due to * accumulation of round-off errors, this residual might differ from the * true residual after some iterations. See e.g. A. Greenbaum and * Z. Strakos, <em>Predicting the Behavior of Finite Precision Lanzos and * Conjugate Gradient Computations</em>, Technical Report 538, Department of * Computer Science, New York University, 1991 (available * <a href="http://www.archive.org/details/predictingbehavi00gree">here</a>). * * @return the norm of the residual, ||r|| */ public abstract double getNormOfResidual(); /** * <p> * Returns the residual. This is an optional operation, as all iterative * linear solvers do not provide cheap estimate of the updated residual * vector, in which case * </p> * <ul> * <li>this method should throw a * {@link MathRuntimeException},</li> * <li>{@link #providesResidual()} returns {@code false}.</li> * </ul> * <p> * The default implementation throws a * {@link MathRuntimeException}. If this method is overriden, * then {@link #providesResidual()} should be overriden as well. * </p> * * @return the updated residual, r */ public RealVector getResidual() { throw new MathRuntimeException(LocalizedCoreFormats.UNSUPPORTED_OPERATION); } /** * Returns the current estimate of the solution to the linear system to be * solved. This method should return an unmodifiable view, or a deep copy of * the actual current solution, in order not to compromise subsequent * iterations of the source {@link IterativeLinearSolver}. * * @return the solution, x */ public abstract RealVector getSolution(); /** * Returns {@code true} if {@link #getResidual()} is supported. The default * implementation returns {@code false}. * * @return {@code false} if {@link #getResidual()} throws a * {@link MathRuntimeException} */ public boolean providesResidual() { return false; } }
apache-2.0
axmadjon/AndroidSlidingMenu
app/src/main/java/uz/greenwhite/slidingmenu/support/v10/common/fragment/SupportDialog.java
1461
package uz.greenwhite.slidingmenu.support.v10.common.fragment; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.DialogFragment; import uz.greenwhite.slidingmenu.support.v10.error.AppError; import java.io.Serializable; public class SupportDialog extends DialogFragment { public static final String SUPPORT_ARG = "uz.greenwhite.slidingmenu.support.v10.dialog"; public static <T extends SupportDialog> T newInstance(Class<? extends SupportDialog> cls, Bundle arg) { SupportDialog fragment = null; try { fragment = cls.newInstance(); if (arg != null) { fragment.setArguments(arg); } } catch (Exception e) { throw AppError.Unsupported(); } return (T) fragment; } public static <T extends SupportDialog> T newInstance(Class<? extends SupportDialog> cls) { return newInstance(cls, (Bundle) null); } public static <T extends SupportDialog> T newInstance(Class<? extends SupportDialog> cls, Parcelable parcel) { Bundle arg = new Bundle(); arg.putParcelable(SUPPORT_ARG, parcel); return newInstance(cls, arg); } public static <T extends SupportDialog> T newInstance(Class<? extends SupportDialog> cls, Serializable serial) { Bundle arg = new Bundle(); arg.putSerializable(SUPPORT_ARG, serial); return newInstance(cls, arg); } }
apache-2.0
esripdx/terraformer-java
src/main/java/com/esri/terraformer/core/GeometryType.java
676
package com.esri.terraformer.core; public enum GeometryType { POINT("Point"), MULTIPOINT("MultiPoint"), LINESTRING("LineString"), MULTILINESTRING("MultiLineString"), POLYGON("Polygon"), MULTIPOLYGON("MultiPolygon"), GEOMETRYCOLLECTION("GeometryCollection"), FEATURE("Feature"), FEATURECOLLECTION("FeatureCollection"); private final String jsonValue; private GeometryType(String jsonValue) { this.jsonValue = jsonValue; } @Override public String toString() { return jsonValue; } public static GeometryType fromJson(String jsonValue) { return valueOf(jsonValue.toUpperCase()); } }
apache-2.0
TheTemportalist/CountryGamer_PlantsVsZombies
java/com/countrygamer/pvz/entities/mobs/zombies/EntityFlagZombie.java
1504
package com.countrygamer.pvz.entities.mobs.zombies; import net.minecraft.entity.monster.EntityZombie; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import com.countrygamer.pvz.PvZ; public class EntityFlagZombie extends EntityZombie { public EntityFlagZombie(World world) { super(world); this.setCurrentItemOrArmor(0, new ItemStack(PvZ.flag)); } /* public void onUpdate() { int minZombies = 1, maxZombies = 10; List list = this.worldObj.getEntitiesWithinAABB(EntityZombie.class, AxisAlignedBB.getBoundingBox(this.posX - 5, this.posY - 1, this.posY - 5, this.posX + 5, this.posY + 2, this.posZ + 5)); Random rand = new Random(); int randInt = rand.nextInt((maxZombies - minZombies) + 1) + minZombies; if (list.size() + randInt <= maxZombies) { int var = rand.nextInt(5); switch (var = 1) { case 0: for (int i = 0; i < randInt; i++) { EntityZombie ent = new EntityZombie(this.worldObj); ent.setPosition(this.posX, this.posY + 1.0D, this.posZ); if (!this.worldObj.isRemote) this.worldObj.spawnEntityInWorld(ent); } break; case 1: for (int i = 0; i < randInt; i++) { EntityFootballZombie ent = new EntityFootballZombie( this.worldObj); ent.setPosition(this.posX, this.posY + 1.0D, this.posZ); if (!this.worldObj.isRemote) this.worldObj.spawnEntityInWorld(ent); } break; case 2: break; case 3: break; case 4: break; } } } */ }
apache-2.0
Almighty-Alpaca/JDA-Butler
bot/src/main/java/com/kantenkugel/discordbot/versioncheck/JenkinsVersionSupplier.java
1662
package com.kantenkugel.discordbot.versioncheck; import com.kantenkugel.discordbot.jenkinsutil.JenkinsApi; import com.kantenkugel.discordbot.jenkinsutil.JenkinsBuild; import com.kantenkugel.discordbot.versioncheck.items.VersionedItem; import java.io.IOException; import java.io.UncheckedIOException; import java.util.function.Supplier; /** * Simple implementation aimed to be served to {@link VersionedItem#getCustomVersionSupplier()} * This uses a given JenkinsApi to get the version. * <br/>It first uses artifact names if available and falls back to build numbers if no artifact is available. */ public class JenkinsVersionSupplier implements Supplier<String> { private final JenkinsApi jenkins; private final boolean useBuildNumber; public JenkinsVersionSupplier(JenkinsApi jenkins) { this(jenkins, false); } public JenkinsVersionSupplier(JenkinsApi jenkins, boolean useBuildNumber) { this.jenkins = jenkins; this.useBuildNumber = useBuildNumber; } @Override public String get() { try { JenkinsBuild build = jenkins.fetchLastSuccessfulBuild(); if(build == null) //there is no successful build return null; if(!useBuildNumber && build.artifacts.size() > 0) { JenkinsBuild.Artifact firstArtifact = build.artifacts.values().iterator().next(); return firstArtifact.fileNameParts.get(1); } return Integer.toString(build.buildNum); } catch(IOException ex) { throw new UncheckedIOException(ex); } } }
apache-2.0
LionelOrange/androidstudioprojects
9GAG-master/9GAG-master/app/src/main/java/me/storm/ninegag/view/titanic/Titanic.java
3648
package me.storm.ninegag.view.titanic; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.os.Build; import android.view.animation.LinearInterpolator; /** * Titanic * User: romainpiel * Date: 14/03/2014 * Time: 09:34 */ public class Titanic { private AnimatorSet animatorSet; private Animator.AnimatorListener animatorListener; public Animator.AnimatorListener getAnimatorListener() { return animatorListener; } public void setAnimatorListener(Animator.AnimatorListener animatorListener) { this.animatorListener = animatorListener; } public void start(final TitanicTextView textView) { final Runnable animate = new Runnable() { @Override public void run() { textView.setSinking(true); // horizontal animation. 200 = wave.png width ObjectAnimator maskXAnimator = ObjectAnimator.ofFloat(textView, "maskX", 0, 200); maskXAnimator.setRepeatCount(ValueAnimator.INFINITE); maskXAnimator.setDuration(1000); maskXAnimator.setStartDelay(0); int h = textView.getHeight(); // vertical animation // maskY = 0 -> wave vertically centered // repeat mode REVERSE to go back and forth ObjectAnimator maskYAnimator = ObjectAnimator.ofFloat(textView, "maskY", h/2, - h/2); maskYAnimator.setRepeatCount(ValueAnimator.INFINITE); maskYAnimator.setRepeatMode(ValueAnimator.REVERSE); maskYAnimator.setDuration(10000); maskYAnimator.setStartDelay(0); // now play both animations together animatorSet = new AnimatorSet(); animatorSet.playTogether(maskXAnimator, maskYAnimator); animatorSet.setInterpolator(new LinearInterpolator()); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { textView.setSinking(false); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { textView.postInvalidate(); } else { textView.postInvalidateOnAnimation(); } animatorSet = null; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); if (animatorListener != null) { animatorSet.addListener(animatorListener); } animatorSet.start(); } }; if (!textView.isSetUp()) { textView.setAnimationSetupCallback(new TitanicTextView.AnimationSetupCallback() { @Override public void onSetupAnimation(final TitanicTextView target) { animate.run(); } }); } else { animate.run(); } } public void cancel() { if (animatorSet != null) { animatorSet.cancel(); } } }
apache-2.0
JNOSQL/artemis-extension
elasticsearch-extension/src/test/java/org/eclipse/jnosql/mapping/elasticsearch/document/DefaultElasticsearchTemplateTest.java
4312
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.eclipse.jnosql.mapping.elasticsearch.document; import jakarta.nosql.document.Document; import jakarta.nosql.document.DocumentEntity; import jakarta.nosql.mapping.Converters; import jakarta.nosql.mapping.document.DocumentEntityConverter; import jakarta.nosql.mapping.document.DocumentEventPersistManager; import jakarta.nosql.mapping.document.DocumentWorkflow; import org.eclipse.jnosql.mapping.reflection.ClassMappings; import org.eclipse.jnosql.mapping.test.CDIExtension; import org.eclipse.jnosql.communication.elasticsearch.document.ElasticsearchDocumentCollectionManager; import org.elasticsearch.index.query.QueryBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; @CDIExtension public class DefaultElasticsearchTemplateTest { @Inject private DocumentEntityConverter converter; @Inject private DocumentWorkflow flow; @Inject private DocumentEventPersistManager persistManager; @Inject private ClassMappings mappings; @Inject private Converters converters; private ElasticsearchDocumentCollectionManager manager; private DefaultElasticsearchTemplate template; @BeforeEach public void setup() { manager = Mockito.mock(ElasticsearchDocumentCollectionManager.class); Instance instance = Mockito.mock(Instance.class); when(instance.get()).thenReturn(manager); template = new DefaultElasticsearchTemplate(instance, converter, flow, persistManager, mappings, converters); DocumentEntity entity = DocumentEntity.of("Person"); entity.add(Document.of("name", "Ada")); entity.add(Document.of("age", 10)); when(manager.search(Mockito.any(QueryBuilder.class))) .thenReturn(Stream.of(entity)); } @Test public void shouldFindQuery() { QueryBuilder queryBuilder = boolQuery().filter(termQuery("name", "Ada")); List<Person> people = template.<Person>search(queryBuilder).collect(Collectors.toList()); assertThat(people, contains(new Person("Ada", 10))); Mockito.verify(manager).search(Mockito.eq(queryBuilder)); } @Test public void shouldGetConverter() { assertNotNull(template.getConverter()); assertEquals(converter, template.getConverter()); } @Test public void shouldGetManager() { assertNotNull(template.getManager()); assertEquals(manager, template.getManager()); } @Test public void shouldGetWorkflow() { assertNotNull(template.getWorkflow()); assertEquals(flow, template.getWorkflow()); } @Test public void shouldGetPersistManager() { assertNotNull(template.getPersistManager()); assertEquals(persistManager, template.getPersistManager()); } @Test public void shouldGetClassMappings() { assertNotNull(template.getClassMappings()); assertEquals(mappings, template.getClassMappings()); } @Test public void shouldGetConverters() { assertNotNull(template.getConverters()); assertEquals(converters, template.getConverters()); } }
apache-2.0
boneman1231/org.apache.felix
trunk/ipojo/tests/core/factories/src/main/java/org/apache/felix/ipojo/test/scenarios/factories/service/CheckService.java
1080
/* * 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.felix.ipojo.test.scenarios.factories.service; import java.util.Properties; public interface CheckService { public static final String foo = "foo"; public boolean check(); public Properties getProps(); }
apache-2.0
chamikaramj/MyDataflowJavaSDK
sdk/src/main/java/com/google/cloud/dataflow/sdk/values/TimestampedValue.java
4362
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.dataflow.sdk.values; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.InstantCoder; import com.google.cloud.dataflow.sdk.coders.StandardCoder; import com.google.cloud.dataflow.sdk.util.PropertyNames; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.Instant; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.List; /** * An immutable (value, timestamp) pair. * * <p> Used for assigning initial timestamps to values inserted into a pipeline * with {@link com.google.cloud.dataflow.sdk.transforms.Create#timestamped}. * * @param <V> the type of the value */ public class TimestampedValue<V> { /** * Returns a new {@code TimestampedValue} with the given value and timestamp. */ public static <V> TimestampedValue<V> of(V value, Instant timestamp) { return new TimestampedValue<>(value, timestamp); } public V getValue() { return value; } public Instant getTimestamp() { return timestamp; } ///////////////////////////////////////////////////////////////////////////// /** * Coder for {@code TimestampedValue}. */ @SuppressWarnings("serial") public static class TimestampedValueCoder<T> extends StandardCoder<TimestampedValue<T>> { private final Coder<T> valueCoder; public static <T> TimestampedValueCoder<T> of(Coder<T> valueCoder) { return new TimestampedValueCoder<>(valueCoder); } @JsonCreator public static TimestampedValueCoder<?> of( @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) List<Object> components) { checkArgument(components.size() == 1, "Expecting 1 component, got " + components.size()); return of((Coder<?>) components.get(0)); } @SuppressWarnings("unchecked") TimestampedValueCoder(Coder<T> valueCoder) { this.valueCoder = checkNotNull(valueCoder); } @Override public void encode(TimestampedValue<T> windowedElem, OutputStream outStream, Context context) throws IOException { valueCoder.encode(windowedElem.getValue(), outStream, context.nested()); InstantCoder.of().encode( windowedElem.getTimestamp(), outStream, context); } @Override public TimestampedValue<T> decode(InputStream inStream, Context context) throws IOException { T value = valueCoder.decode(inStream, context.nested()); Instant timestamp = InstantCoder.of().decode(inStream, context); return TimestampedValue.of(value, timestamp); } @Override @Deprecated public boolean isDeterministic() { return valueCoder.isDeterministic(); } @Override public void verifyDeterministic() throws NonDeterministicException { verifyDeterministic( "TimestampedValueCoder requires a deterministic valueCoder", valueCoder); } @Override public List<? extends Coder<?>> getCoderArguments() { return Arrays.<Coder<?>>asList(valueCoder); } public static <T> List<Object> getInstanceComponents(TimestampedValue<T> exampleValue) { return Arrays.<Object>asList(exampleValue.getValue()); } } ///////////////////////////////////////////////////////////////////////////// private final V value; private final Instant timestamp; protected TimestampedValue(V value, Instant timestamp) { this.value = value; this.timestamp = timestamp; } }
apache-2.0
stari4ek/ExoPlayer
library/extractor/src/main/java/com/google/android/exoplayer2/extractor/Id3Peeker.java
3046
/* * Copyright (C) 2018 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.google.android.exoplayer2.extractor; import androidx.annotation.Nullable; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.id3.Id3Decoder; import com.google.android.exoplayer2.util.ParsableByteArray; import java.io.EOFException; import java.io.IOException; /** * Peeks data from the beginning of an {@link ExtractorInput} to determine if there is any ID3 tag. */ public final class Id3Peeker { private final ParsableByteArray scratch; public Id3Peeker() { scratch = new ParsableByteArray(Id3Decoder.ID3_HEADER_LENGTH); } /** * Peeks ID3 data from the input and parses the first ID3 tag. * * @param input The {@link ExtractorInput} from which data should be peeked. * @param id3FramePredicate Determines which ID3 frames are decoded. May be null to decode all * frames. * @return The first ID3 tag decoded into a {@link Metadata} object. May be null if ID3 tag is not * present in the input. * @throws IOException If an error occurred peeking from the input. */ @Nullable public Metadata peekId3Data( ExtractorInput input, @Nullable Id3Decoder.FramePredicate id3FramePredicate) throws IOException { int peekedId3Bytes = 0; @Nullable Metadata metadata = null; while (true) { try { input.peekFully(scratch.data, /* offset= */ 0, Id3Decoder.ID3_HEADER_LENGTH); } catch (EOFException e) { // If input has less than ID3_HEADER_LENGTH, ignore the rest. break; } scratch.setPosition(0); if (scratch.readUnsignedInt24() != Id3Decoder.ID3_TAG) { // Not an ID3 tag. break; } scratch.skipBytes(3); // Skip major version, minor version and flags. int framesLength = scratch.readSynchSafeInt(); int tagLength = Id3Decoder.ID3_HEADER_LENGTH + framesLength; if (metadata == null) { byte[] id3Data = new byte[tagLength]; System.arraycopy(scratch.data, 0, id3Data, 0, Id3Decoder.ID3_HEADER_LENGTH); input.peekFully(id3Data, Id3Decoder.ID3_HEADER_LENGTH, framesLength); metadata = new Id3Decoder(id3FramePredicate).decode(id3Data, tagLength); } else { input.advancePeekPosition(framesLength); } peekedId3Bytes += tagLength; } input.resetPeekPosition(); input.advancePeekPosition(peekedId3Bytes); return metadata; } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/ActivateProductTemplates.java
932
package com.google.api.ads.dfp.jaxws.v201308; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * The action used for activating product templates. * * * <p>Java class for ActivateProductTemplates complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActivateProductTemplates"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201308}ProductTemplateAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivateProductTemplates") public class ActivateProductTemplates extends ProductTemplateAction { }
apache-2.0
vadmeste/minio-java
functional/FunctionalTest.java
144243
/* * MinIO Java SDK for Amazon S3 Compatible Cloud Storage, * (C) 2015-2019 MinIO, 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. */ import static java.nio.file.StandardOpenOption.*; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.minio.*; import io.minio.errors.*; import io.minio.messages.*; import java.io.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.security.*; import java.time.*; import java.util.*; import java.util.concurrent.TimeUnit; import javax.crypto.KeyGenerator; import javax.crypto.spec.SecretKeySpec; import okhttp3.HttpUrl; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; @SuppressFBWarnings( value = "REC", justification = "Allow catching super class Exception since it's tests") public class FunctionalTest { private static final String PASS = "PASS"; private static final String FAILED = "FAIL"; private static final String IGNORED = "NA"; private static final int KB = 1024; private static final int MB = 1024 * 1024; private static final Random random = new Random(new SecureRandom().nextLong()); private static final String customContentType = "application/javascript"; private static final String nullContentType = null; private static String bucketName = getRandomName(); private static boolean mintEnv = false; private static Path dataFile1Kb; private static Path dataFile6Mb; private static String endpoint; private static String accessKey; private static String secretKey; private static String region; private static MinioClient client = null; /** Do no-op. */ public static void ignore(Object... args) {} /** Create given sized file and returns its name. */ public static String createFile(int size) throws IOException { String filename = getRandomName(); try (OutputStream os = Files.newOutputStream(Paths.get(filename), CREATE, APPEND)) { int totalBytesWritten = 0; int bytesToWrite = 0; byte[] buf = new byte[1 * MB]; while (totalBytesWritten < size) { random.nextBytes(buf); bytesToWrite = size - totalBytesWritten; if (bytesToWrite > buf.length) { bytesToWrite = buf.length; } os.write(buf, 0, bytesToWrite); totalBytesWritten += bytesToWrite; } } return filename; } /** Create 1 KB temporary file. */ public static String createFile1Kb() throws IOException { if (mintEnv) { String filename = getRandomName(); Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile1Kb); return filename; } return createFile(1 * KB); } /** Create 6 MB temporary file. */ public static String createFile6Mb() throws IOException { if (mintEnv) { String filename = getRandomName(); Files.createSymbolicLink(Paths.get(filename).toAbsolutePath(), dataFile6Mb); return filename; } return createFile(6 * MB); } /** Generate random name. */ public static String getRandomName() { return "minio-java-test-" + new BigInteger(32, random).toString(32); } /** Returns byte array contains all data in given InputStream. */ public static byte[] readAllBytes(InputStream is) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } return buffer.toByteArray(); } /** Prints a success log entry in JSON format. */ public static void mintSuccessLog(String function, String args, long startTime) { if (mintEnv) { System.out.println( new MintLogger( function, args, System.currentTimeMillis() - startTime, PASS, null, null, null)); } } /** Prints a failure log entry in JSON format. */ public static void mintFailedLog( String function, String args, long startTime, String message, String error) { if (mintEnv) { System.out.println( new MintLogger( function, args, System.currentTimeMillis() - startTime, FAILED, null, message, error)); } } /** Prints a ignore log entry in JSON format. */ public static void mintIgnoredLog(String function, String args, long startTime) { if (mintEnv) { System.out.println( new MintLogger( function, args, System.currentTimeMillis() - startTime, IGNORED, null, null, null)); } } /** Read object content of the given url. */ public static byte[] readObject(String urlString) throws Exception { Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build(); OkHttpClient transport = new OkHttpClient() .newBuilder() .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); Response response = transport.newCall(request).execute(); if (response == null) { throw new Exception("empty response"); } if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new Scanner(response.body().charStream()); scanner.useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } scanner.close(); response.body().close(); throw new Exception( "failed to read object. Response: " + response + ", Response body: " + errorXml); } return readAllBytes(response.body().byteStream()); } /** Write data to given object url. */ public static void writeObject(String urlString, byte[] dataBytes) throws Exception { Request.Builder requestBuilder = new Request.Builder(); // Set header 'x-amz-acl' to 'bucket-owner-full-control', so objects created // anonymously, can be downloaded by bucket owner in AWS S3. Request request = requestBuilder .url(HttpUrl.parse(urlString)) .method("PUT", RequestBody.create(null, dataBytes)) .addHeader("x-amz-acl", "bucket-owner-full-control") .build(); OkHttpClient transport = new OkHttpClient() .newBuilder() .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); Response response = transport.newCall(request).execute(); if (response == null) { throw new Exception("empty response"); } if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new Scanner(response.body().charStream()); scanner.useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } scanner.close(); response.body().close(); throw new Exception( "failed to create object. Response: " + response + ", Response body: " + errorXml); } } /** Test: makeBucket(String bucketName). */ public static void makeBucket_test1() throws Exception { if (!mintEnv) { System.out.println("Test: makeBucket(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name); client.removeBucket(name); mintSuccessLog("makeBucket(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "makeBucket(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: makeBucket(String bucketName, String region). */ public static void makeBucketwithRegion_test() throws Exception { if (!mintEnv) { System.out.println("Test: makeBucket(String bucketName, String region)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name, "eu-west-1"); client.removeBucket(name); mintSuccessLog( "makeBucket(String bucketName, String region)", "region: eu-west-1", startTime); } catch (Exception e) { mintFailedLog( "makeBucket(String bucketName, String region)", "region: eu-west-1", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: makeBucket(String bucketName, String region) where bucketName has periods in its name. */ public static void makeBucketWithPeriod_test() throws Exception { if (!mintEnv) { System.out.println("Test: makeBucket(String bucketName, String region)"); } long startTime = System.currentTimeMillis(); String name = getRandomName() + ".withperiod"; try { client.makeBucket(name, "eu-central-1"); client.removeBucket(name); mintSuccessLog( "makeBucket(String bucketName, String region)", "name: " + name + ", region: eu-central-1", startTime); } catch (Exception e) { mintFailedLog( "makeBucket(String bucketName, String region)", "name: " + name + ", region: eu-central-1", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listBuckets(). */ public static void listBuckets_test() throws Exception { if (!mintEnv) { System.out.println("Test: listBuckets()"); } long startTime = System.currentTimeMillis(); try { long nowSeconds = ZonedDateTime.now().toEpochSecond(); String bucketName = getRandomName(); boolean found = false; client.makeBucket(bucketName); for (Bucket bucket : client.listBuckets()) { if (bucket.name().equals(bucketName)) { if (found) { throw new Exception( "[FAILED] duplicate entry " + bucketName + " found in list buckets"); } found = true; // excuse 15 minutes if ((bucket.creationDate().toEpochSecond() - nowSeconds) > (15 * 60)) { throw new Exception( "[FAILED] bucket creation time too apart in " + (bucket.creationDate().toEpochSecond() - nowSeconds) + " seconds"); } } } client.removeBucket(bucketName); if (!found) { throw new Exception("[FAILED] created bucket not found in list buckets"); } mintSuccessLog("listBuckets()", null, startTime); } catch (Exception e) { mintFailedLog( "listBuckets()", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: bucketExists(String bucketName). */ public static void bucketExists_test() throws Exception { if (!mintEnv) { System.out.println("Test: bucketExists(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name); if (!client.bucketExists(name)) { throw new Exception("[FAILED] bucket does not exist"); } client.removeBucket(name); mintSuccessLog("bucketExists(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "bucketExists(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: removeBucket(String bucketName). */ public static void removeBucket_test() throws Exception { if (!mintEnv) { System.out.println("Test: removeBucket(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String name = getRandomName(); client.makeBucket(name); client.removeBucket(name); mintSuccessLog("removeBucket(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "removeBucket(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Tear down test setup. */ public static void setup() throws Exception { client.makeBucket(bucketName); } /** Tear down test setup. */ public static void teardown() throws Exception { client.removeBucket(bucketName); } /** * Test: putObject(String bucketName, String objectName, String filename, PutObjectOptions * options) */ public static void putObject_test1() throws Exception { String methodName = "putObject(String bucketName, String objectName, String filename, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: " + methodName); } long startTime = System.currentTimeMillis(); try { String filename = createFile1Kb(); client.putObject(bucketName, filename, filename, null); Files.delete(Paths.get(filename)); client.removeObject(bucketName, filename); mintSuccessLog(methodName, "filename: 1KB", startTime); } catch (Exception e) { mintFailedLog( methodName, "filename: 1KB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: multipart: putObject(String bucketName, String objectName, String filename, * PutObjectOptions options) */ public static void putObject_test2() throws Exception { String methodName = "putObject(String bucketName, String objectName, String filename, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: multipart: " + methodName); } long startTime = System.currentTimeMillis(); try { String filename = createFile6Mb(); client.putObject(bucketName, filename, filename, new PutObjectOptions(6 * MB, 5 * MB)); Files.delete(Paths.get(filename)); client.removeObject(bucketName, filename); mintSuccessLog(methodName, "filename: 6MB", startTime); } catch (Exception e) { mintFailedLog( methodName, "filename: 6MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with content-type: putObject(String bucketName, String objectName, String filename, * PutObjectOptions options) */ public static void putObject_test3() throws Exception { String methodName = "putObject(String bucketName, String objectName, String filename, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with content-type: " + methodName); } long startTime = System.currentTimeMillis(); try { String filename = createFile1Kb(); PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setContentType(customContentType); client.putObject(bucketName, filename, filename, options); Files.delete(Paths.get(filename)); client.removeObject(bucketName, filename); mintSuccessLog(methodName, "contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog( methodName, "contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions * options) */ public static void putObject_test4() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setContentType(customContentType); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "size: 1 KB, objectName: " + customContentType, startTime); } catch (Exception e) { mintFailedLog( methodName, "size: 1 KB, objectName: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: object name with multiple path segments: putObject(String bucketName, String objectName, * InputStream stream, PutObjectOptions options) */ public static void putObject_test5() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: object name with path segments: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = "path/to/" + getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setContentType(customContentType); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "size: 1 KB, contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog( methodName, "size: 1 KB, contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: unknown size stream: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options) */ public static void putObject_test6() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: unknown size stream: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(3 * KB)) { PutObjectOptions options = new PutObjectOptions(is.available(), -1); options.setContentType(customContentType); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "size: -1, contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog( methodName, "size: -1, contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: multipart unknown size stream: putObject(String bucketName, String objectName, * InputStream stream, PutObjectOptions options) */ public static void putObject_test7() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: multipart unknown size stream: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(11 * MB)) { PutObjectOptions options = new PutObjectOptions(is.available(), -1); options.setContentType(customContentType); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "size: -1, contentType: " + customContentType, startTime); } catch (Exception e) { mintFailedLog( methodName, "size: -1, contentType: " + customContentType, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with user metadata: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options). */ public static void putObject_test8() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with user metadata: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("X-Amz-Meta-mykey", "myvalue"); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setHeaders(headerMap); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "X-Amz-Meta-mykey: myvalue", startTime); } catch (Exception e) { mintFailedLog( methodName, "X-Amz-Meta-mykey: myvalue", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with storage class REDUCED_REDUNDANCY: putObject(String bucketName, String objectName, * InputStream stream, PutObjectOptions options). */ public static void putObject_test9() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with storage class REDUCED_REDUNDANCY: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY"); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setHeaders(headerMap); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "X-Amz-Storage-Class: REDUCED_REDUNDANCY", startTime); } catch (Exception e) { mintFailedLog( methodName, "X-Amz-Storage-Class: REDUCED_REDUNDANCY", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with storage class STANDARD: putObject(String bucketName, String objectName, InputStream * stream, PutObjectOptions options). */ public static void putObject_test10() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with storage class STANDARD: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("X-Amz-Storage-Class", "STANDARD"); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setHeaders(headerMap); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "X-Amz-Storage-Class: STANDARD", startTime); } catch (Exception e) { mintFailedLog( methodName, "X-Amz-Storage-Class: STANDARD", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with storage class INVALID: putObject(String bucketName, String objectName, InputStream * stream, PutObjectOptions options). */ public static void putObject_test11() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with storage class INVALID: " + methodName); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("X-Amz-Storage-Class", "INVALID"); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setHeaders(headerMap); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.INVALID_STORAGE_CLASS) { mintFailedLog( methodName, "X-Amz-Storage-Class: INVALID", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } catch (Exception e) { mintFailedLog( methodName, "X-Amz-Storage-Class: INVALID", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } mintSuccessLog(methodName, "X-Amz-Storage-Class: INVALID", startTime); } /** * Test: with SSE_C: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options). */ public static void putObject_test12() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with SSE_C: " + methodName); } long startTime = System.currentTimeMillis(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey()); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "Server-side encryption: SSE_C", startTime); } catch (Exception e) { mintFailedLog( methodName, "Server-side encryption: SSE_C", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: multipart with SSE_C: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options). */ public static void putObject_test13() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: multipart with SSE_C: " + methodName); } long startTime = System.currentTimeMillis(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey()); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(11 * MB)) { PutObjectOptions options = new PutObjectOptions(-1, 5 * MB); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "Size: 11 MB, Server-side encryption: SSE_C", startTime); } catch (Exception e) { mintFailedLog( methodName, "Size: 11 MB, Server-side encryption: SSE_C", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with SSE_S3: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options). */ public static void putObject_test14() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with SSE_S3: " + methodName); } long startTime = System.currentTimeMillis(); ServerSideEncryption sse = ServerSideEncryption.atRest(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "Server-side encryption: SSE_S3", startTime); } catch (Exception e) { mintFailedLog( methodName, "Server-side encryption: SSE_S3", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: with SSE_KMS: putObject(String bucketName, String objectName, InputStream stream, * PutObjectOptions options). */ public static void putObject_test15() throws Exception { String methodName = "putObject(String bucketName, String objectName, InputStream stream, PutObjectOptions options)"; if (!mintEnv) { System.out.println("Test: with SSE_KMS: " + methodName); } long startTime = System.currentTimeMillis(); if (System.getenv("MINT_KEY_ID").equals("")) { mintIgnoredLog(methodName, "Server-side encryption: SSE_KMS", startTime); } Map<String, String> myContext = new HashMap<>(); myContext.put("key1", "value1"); ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } client.removeObject(bucketName, objectName); mintSuccessLog(methodName, "Server-side encryption: SSE_KMS", startTime); } catch (Exception e) { mintFailedLog( methodName, "Server-side encryption: SSE_KMS", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: statObject(String bucketName, String objectName). */ public static void statObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: statObject(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Type", customContentType); headerMap.put("my-custom-data", "foo"); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setHeaders(headerMap); options.setContentType(customContentType); client.putObject(bucketName, objectName, is, options); } ObjectStat objectStat = client.statObject(bucketName, objectName); if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1) && bucketName.equals(objectStat.bucketName()) && objectStat.contentType().equals(customContentType))) { throw new Exception("[FAILED] object stat differs"); } Map<String, List<String>> httpHeaders = objectStat.httpHeaders(); if (!httpHeaders.containsKey("x-amz-meta-my-custom-data")) { throw new Exception("[FAILED] metadata not found in object stat"); } List<String> values = httpHeaders.get("x-amz-meta-my-custom-data"); if (values.size() != 1) { throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size()); } if (!values.get(0).equals("foo")) { throw new Exception("[FAILED] wrong metadata value. expected: foo, got: " + values.get(0)); } client.removeObject(bucketName, objectName); mintSuccessLog("statObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "statObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: statObject(String bucketName, String objectName, ServerSideEncryption sse). To test * statObject using SSE_C. */ public static void statObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: statObject(String bucketName, String objectName, ServerSideEncryption sse)" + " using SSE_C."); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); // Generate a new 256 bit AES key - This key must be remembered by the client. KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey()); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } ObjectStat objectStat = client.statObject(bucketName, objectName, sse); if (!(objectName.equals(objectStat.name()) && (objectStat.length() == 1) && bucketName.equals(objectStat.bucketName()))) { throw new Exception("[FAILED] object stat differs"); } Map<String, List<String>> httpHeaders = objectStat.httpHeaders(); if (!httpHeaders.containsKey("X-Amz-Server-Side-Encryption-Customer-Algorithm")) { throw new Exception("[FAILED] metadata not found in object stat"); } List<String> values = httpHeaders.get("X-Amz-Server-Side-Encryption-Customer-Algorithm"); if (values.size() != 1) { throw new Exception("[FAILED] too many metadata value. expected: 1, got: " + values.size()); } if (!values.get(0).equals("AES256")) { throw new Exception( "[FAILED] wrong metadata value. expected: AES256, got: " + values.get(0)); } client.removeObject(bucketName, objectName); mintSuccessLog( "statObject(String bucketName, String objectName, ServerSideEncryption sse)" + " using SSE_C.", null, startTime); } catch (Exception e) { mintFailedLog( "statObject(String bucketName, String objectName, ServerSideEncryption sse)" + " using SSE_C.", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: statObject(String bucketName, "randomName/"). */ public static void statObject_test3() throws Exception { if (!mintEnv) { System.out.println("Test: statObject(String bucketName, \"randomName/\")"); } long startTime = System.currentTimeMillis(); try { client.statObject(bucketName, getRandomName() + "/"); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.NO_SUCH_KEY) { mintFailedLog( "statObject(String bucketName, \"randomName/\")", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } catch (Exception e) { mintFailedLog( "statObject(String bucketName, \"randomName/\")", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } finally { mintSuccessLog("statObject(String bucketName, \"randomName/\"`)", null, startTime); } } /** Test: getObject(String bucketName, String objectName). */ public static void getObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } client.getObject(bucketName, objectName).close(); client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getObject(String bucketName, String objectName, long offset). */ public static void getObject_test2() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName, long offset)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } client.getObject(bucketName, objectName, 1000L).close(); client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, long offset)", "offset: 1000", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getObject(String bucketName, String objectName, long offset, Long length). */ public static void getObject_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: getObject(String bucketName, String objectName, long offset, Long length)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(6 * MB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(6 * MB, -1)); } client.getObject(bucketName, objectName, 1000L, 64 * 1024L).close(); client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, long offset, Long length)", "offset: 1000, length: 64 KB", startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, long offset, Long length)", "offset: 1000, length: 64 KB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getObject(String bucketName, String objectName, String filename). */ public static void getObject_test4() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName, String filename)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } client.getObject(bucketName, objectName, objectName + ".downloaded"); Files.delete(Paths.get(objectName + ".downloaded")); client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, String filename)", null, startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, String filename)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: getObject(String bucketName, String objectName, String filename). where objectName has * multiple path segments. */ public static void getObject_test5() throws Exception { if (!mintEnv) { System.out.println( "Test: objectName with multiple path segments: " + "getObject(String bucketName, String objectName, String filename)"); } long startTime = System.currentTimeMillis(); String baseObjectName = getRandomName(); String objectName = "path/to/" + baseObjectName; try { try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } client.getObject(bucketName, objectName, baseObjectName + ".downloaded"); Files.delete(Paths.get(baseObjectName + ".downloaded")); client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, String filename)", "objectName: " + objectName, startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, String filename)", "objectName: " + objectName, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getObject(String bucketName, String objectName) zero size object. */ public static void getObject_test6() throws Exception { if (!mintEnv) { System.out.println("Test: getObject(String bucketName, String objectName) zero size object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(0)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(0, -1)); } client.getObject(bucketName, objectName).close(); client.removeObject(bucketName, objectName); mintSuccessLog("getObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: getObject(String bucketName, String objectName, ServerSideEncryption sse). To test * getObject when object is put using SSE_C. */ public static void getObject_test7() throws Exception { if (!mintEnv) { System.out.println( "Test: getObject(String bucketName, String objectName, ServerSideEncryption sse) using SSE_C"); } long startTime = System.currentTimeMillis(); // Generate a new 256 bit AES key - This key must be remembered by the client. KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey()); try { String objectName = getRandomName(); String putString; int bytes_read_put; try (final InputStream is = new ContentInputStream(1 * KB)) { PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); byte[] putbyteArray = new byte[is.available()]; bytes_read_put = is.read(putbyteArray); putString = new String(putbyteArray, StandardCharsets.UTF_8); } InputStream stream = client.getObject(bucketName, objectName, sse); byte[] getbyteArray = new byte[stream.available()]; int bytes_read_get = stream.read(getbyteArray); String getString = new String(getbyteArray, StandardCharsets.UTF_8); stream.close(); // Compare if contents received are same as the initial uploaded object. if ((!putString.equals(getString)) || (bytes_read_put != bytes_read_get)) { throw new Exception("Contents received from getObject doesn't match initial contents."); } client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, ServerSideEncryption sse)" + " using SSE_C.", null, startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, ServerSideEncryption sse)" + " using SSE_C.", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0. */ public static void getObject_test8() throws Exception { if (!mintEnv) { System.out.println( "Test: getObject(String bucketName, String objectName, long offset, Long length) with offset=0"); } final long startTime = System.currentTimeMillis(); final int fullLength = 1024; final int partialLength = 256; final long offset = 0L; final String objectName = getRandomName(); try { try (final InputStream is = new ContentInputStream(fullLength)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(fullLength, -1)); } try (final InputStream partialObjectStream = client.getObject(bucketName, objectName, offset, Long.valueOf(partialLength))) { byte[] result = new byte[fullLength]; final int read = partialObjectStream.read(result); result = Arrays.copyOf(result, read); if (result.length != partialLength) { throw new Exception( String.format( "Expecting only the first %d bytes from partial getObject request; received %d bytes instead.", partialLength, read)); } } client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, long offset, Long length) with offset=0", String.format("offset: %d, length: %d bytes", offset, partialLength), startTime); } catch (final Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, long offset, Long length) with offset=0", String.format("offset: %d, length: %d bytes", offset, partialLength), startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: getObject(String bucketName, String objectName, ServerSideEncryption sse, String * fileName). */ public static void getObject_test9() throws Exception { if (!mintEnv) { System.out.println( "Test: getObject(String bucketName, String objectName, ServerSideEncryption sse, String fileName)"); } long startTime = System.currentTimeMillis(); // Generate a new 256 bit AES key - This key must be remembered by the client. KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); ServerSideEncryption sse = ServerSideEncryption.withCustomerKey(keyGen.generateKey()); try { String objectName = getRandomName(); String filename = createFile1Kb(); PutObjectOptions options = new PutObjectOptions(1 * KB, -1); options.setSse(sse); client.putObject(bucketName, objectName, filename, options); client.getObject(bucketName, objectName, sse, objectName + ".downloaded"); Files.delete(Paths.get(objectName + ".downloaded")); client.removeObject(bucketName, objectName); mintSuccessLog( "getObject(String bucketName, String objectName, ServerSideEncryption sse, " + "String filename). To test SSE_C", "size: 1 KB", startTime); } catch (Exception e) { mintFailedLog( "getObject(String bucketName, String objectName, ServerSideEncryption sse, " + "String filename). To test SSE_C", "size: 1 KB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listObjects(final String bucketName). */ public static void listObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: listObjects(final String bucketName)"); } long startTime = System.currentTimeMillis(); try { String[] objectNames = new String[3]; int i = 0; for (i = 0; i < 3; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } i = 0; for (Result<?> r : client.listObjects(bucketName)) { ignore(i++, r.get()); if (i == 3) { break; } } for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog("listObjects(final String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listObjects(bucketName, final String prefix). */ public static void listObject_test2() throws Exception { if (!mintEnv) { System.out.println("Test: listObjects(final String bucketName, final String prefix)"); } long startTime = System.currentTimeMillis(); try { String[] objectNames = new String[3]; int i = 0; for (i = 0; i < 3; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } i = 0; for (Result<?> r : client.listObjects(bucketName, "minio")) { ignore(i++, r.get()); if (i == 3) { break; } } for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog( "listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName, final String prefix)", "prefix :minio", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listObjects(bucketName, final String prefix, final boolean recursive). */ public static void listObject_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: listObjects(final String bucketName, final String prefix, final boolean recursive)"); } long startTime = System.currentTimeMillis(); try { String[] objectNames = new String[3]; int i = 0; for (i = 0; i < 3; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } i = 0; for (Result<?> r : client.listObjects(bucketName, "minio", true)) { ignore(i++, r.get()); if (i == 3) { break; } } for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minio, recursive: true", startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minio, recursive: true", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listObjects(final string bucketName). */ public static void listObject_test4() throws Exception { if (!mintEnv) { System.out.println( "Test: empty bucket: listObjects(final String bucketName, final String prefix," + " final boolean recursive)"); } long startTime = System.currentTimeMillis(); try { int i = 0; for (Result<?> r : client.listObjects(bucketName, "minioemptybucket", true)) { ignore(i++, r.get()); if (i == 3) { break; } } mintSuccessLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minioemptybucket, recursive: true", startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minioemptybucket, recursive: true", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: recursive: listObjects(bucketName, final String prefix, final boolean recursive). */ public static void listObject_test5() throws Exception { if (!mintEnv) { System.out.println( "Test: recursive: listObjects(final String bucketName, final String prefix, " + "final boolean recursive)"); } long startTime = System.currentTimeMillis(); try { int objCount = 1050; String[] objectNames = new String[objCount]; int i = 0; for (i = 0; i < objCount; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } i = 0; for (Result<?> r : client.listObjects(bucketName, "minio", true)) { ignore(i++, r.get()); } // Check the number of uploaded objects if (i != objCount) { throw new Exception("item count differs, expected: " + objCount + ", got: " + i); } for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minio, recursive: true", startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName, final String prefix, final boolean recursive)", "prefix :minio, recursive: true", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: listObjects(bucketName, final String prefix, final boolean recursive, final boolean * useVersion1). */ public static void listObject_test6() throws Exception { if (!mintEnv) { System.out.println( "Test: listObjects(final String bucketName, final String prefix, final boolean recursive, " + "final boolean useVersion1)"); } long startTime = System.currentTimeMillis(); try { String[] objectNames = new String[3]; int i = 0; for (i = 0; i < 3; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } i = 0; for (Result<?> r : client.listObjects(bucketName, "minio", true, true)) { ignore(i++, r.get()); if (i == 3) { break; } } for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog( "listObjects(final String bucketName, final String prefix, " + "final boolean recursive, final boolean useVersion1)", "prefix :minio, recursive: true, useVersion1: true", startTime); } catch (Exception e) { mintFailedLog( "listObjects(final String bucketName, final String prefix, " + "final boolean recursive, final boolean useVersion1)", "prefix :minio, recursive: true, useVersion1: true", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: removeObject(String bucketName, String objectName). */ public static void removeObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: removeObject(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1, -1)); } client.removeObject(bucketName, objectName); mintSuccessLog("removeObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "removeObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: removeObjects(final String bucketName, final Iterable&lt;String&gt; objectNames). */ public static void removeObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: removeObjects(final String bucketName, final Iterable<String> objectNames)"); } long startTime = System.currentTimeMillis(); try { String[] objectNames = new String[4]; for (int i = 0; i < 3; i++) { objectNames[i] = getRandomName(); try (final InputStream is = new ContentInputStream(1)) { client.putObject(bucketName, objectNames[i], is, new PutObjectOptions(1, -1)); } } objectNames[3] = "nonexistent-object"; for (Result<?> r : client.removeObjects(bucketName, Arrays.asList(objectNames))) { ignore(r.get()); } mintSuccessLog( "removeObjects(final String bucketName, final Iterable<String> objectNames)", null, startTime); } catch (Exception e) { mintFailedLog( "removeObjects(final String bucketName, final Iterable<String> objectNames)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listIncompleteUploads(String bucketName). */ public static void listIncompleteUploads_test1() throws Exception { if (!mintEnv) { System.out.println("Test: listIncompleteUploads(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(6 * MB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(9 * MB, -1)); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.INCOMPLETE_BODY) { throw e; } } catch (InsufficientDataException e) { ignore(); } int i = 0; for (Result<Upload> r : client.listIncompleteUploads(bucketName)) { ignore(i++, r.get()); if (i == 10) { break; } } client.removeIncompleteUpload(bucketName, objectName); mintSuccessLog("listIncompleteUploads(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "listIncompleteUploads(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listIncompleteUploads(String bucketName, String prefix). */ public static void listIncompleteUploads_test2() throws Exception { if (!mintEnv) { System.out.println("Test: listIncompleteUploads(String bucketName, String prefix)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(6 * MB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(9 * MB, -1)); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.INCOMPLETE_BODY) { throw e; } } catch (InsufficientDataException e) { ignore(); } int i = 0; for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio")) { ignore(i++, r.get()); if (i == 10) { break; } } client.removeIncompleteUpload(bucketName, objectName); mintSuccessLog("listIncompleteUploads(String bucketName, String prefix)", null, startTime); } catch (Exception e) { mintFailedLog( "listIncompleteUploads(String bucketName, String prefix)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: listIncompleteUploads(final String bucketName, final String prefix, final boolean * recursive). */ public static void listIncompleteUploads_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: listIncompleteUploads(final String bucketName, final String prefix, " + "final boolean recursive)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(6 * MB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(9 * MB, -1)); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.INCOMPLETE_BODY) { throw e; } } catch (InsufficientDataException e) { ignore(); } int i = 0; for (Result<Upload> r : client.listIncompleteUploads(bucketName, "minio", true)) { ignore(i++, r.get()); if (i == 10) { break; } } client.removeIncompleteUpload(bucketName, objectName); mintSuccessLog( "listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)", "prefix: minio, recursive: true", startTime); } catch (Exception e) { mintFailedLog( "listIncompleteUploads(final String bucketName, final String prefix, final boolean recursive)", "prefix: minio, recursive: true", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: removeIncompleteUpload(String bucketName, String objectName). */ public static void removeIncompleteUploads_test() throws Exception { if (!mintEnv) { System.out.println("Test: removeIncompleteUpload(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(6 * MB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(9 * MB, -1)); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.INCOMPLETE_BODY) { throw e; } } catch (InsufficientDataException e) { ignore(); } int i = 0; for (Result<Upload> r : client.listIncompleteUploads(bucketName)) { ignore(i++, r.get()); if (i == 10) { break; } } client.removeIncompleteUpload(bucketName, objectName); mintSuccessLog( "removeIncompleteUpload(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "removeIncompleteUpload(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** public String presignedGetObject(String bucketName, String objectName). */ public static void presignedGetObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: presignedGetObject(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } byte[] inBytes; try (final InputStream is = new ContentInputStream(1 * KB)) { inBytes = readAllBytes(is); } String urlString = client.presignedGetObject(bucketName, objectName); byte[] outBytes = readObject(urlString); if (!Arrays.equals(inBytes, outBytes)) { throw new Exception("object content differs"); } client.removeObject(bucketName, objectName); mintSuccessLog("presignedGetObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedGetObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: presignedGetObject(String bucketName, String objectName, Integer expires). */ public static void presignedGetObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: presignedGetObject(String bucketName, String objectName, Integer expires)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } byte[] inBytes; try (final InputStream is = new ContentInputStream(1 * KB)) { inBytes = readAllBytes(is); } String urlString = client.presignedGetObject(bucketName, objectName, 3600); byte[] outBytes = readObject(urlString); if (!Arrays.equals(inBytes, outBytes)) { throw new Exception("object content differs"); } client.removeObject(bucketName, objectName); mintSuccessLog( "presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedGetObject(String bucketName, String objectName, Integer expires)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * public String presignedGetObject(String bucketName, String objectName, Integer expires, Map * reqParams). */ public static void presignedGetObject_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: presignedGetObject(String bucketName, String objectName, Integer expires, " + "Map<String, String> reqParams)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } byte[] inBytes; try (final InputStream is = new ContentInputStream(1 * KB)) { inBytes = readAllBytes(is); } Map<String, String> reqParams = new HashMap<>(); reqParams.put("response-content-type", "application/json"); String urlString = client.presignedGetObject(bucketName, objectName, 3600, reqParams); byte[] outBytes = readObject(urlString); if (!Arrays.equals(inBytes, outBytes)) { throw new Exception("object content differs"); } client.removeObject(bucketName, objectName); mintSuccessLog( "presignedGetObject(String bucketName, String objectName, Integer expires, Map<String," + " String> reqParams)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedGetObject(String bucketName, String objectName, Integer expires, Map<String," + " String> reqParams)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** public String presignedPutObject(String bucketName, String objectName). */ public static void presignedPutObject_test1() throws Exception { if (!mintEnv) { System.out.println("Test: presignedPutObject(String bucketName, String objectName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); String urlString = client.presignedPutObject(bucketName, objectName); byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8); writeObject(urlString, data); client.removeObject(bucketName, objectName); mintSuccessLog("presignedPutObject(String bucketName, String objectName)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedPutObject(String bucketName, String objectName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: presignedPutObject(String bucketName, String objectName, Integer expires). */ public static void presignedPutObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: presignedPutObject(String bucketName, String objectName, Integer expires)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); String urlString = client.presignedPutObject(bucketName, objectName, 3600); byte[] data = "hello, world".getBytes(StandardCharsets.UTF_8); writeObject(urlString, data); client.removeObject(bucketName, objectName); mintSuccessLog( "presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedPutObject(String bucketName, String objectName, Integer expires)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: presignedPostPolicy(PostPolicy policy). */ public static void presignedPostPolicy_test() throws Exception { if (!mintEnv) { System.out.println("Test: presignedPostPolicy(PostPolicy policy)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); PostPolicy policy = new PostPolicy(bucketName, objectName, ZonedDateTime.now().plusDays(7)); policy.setContentRange(1 * MB, 4 * MB); Map<String, String> formData = client.presignedPostPolicy(policy); MultipartBody.Builder multipartBuilder = new MultipartBody.Builder(); multipartBuilder.setType(MultipartBody.FORM); for (Map.Entry<String, String> entry : formData.entrySet()) { multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue()); } try (final InputStream is = new ContentInputStream(1 * MB)) { multipartBuilder.addFormDataPart( "file", objectName, RequestBody.create(null, readAllBytes(is))); } Request.Builder requestBuilder = new Request.Builder(); String urlString = client.getObjectUrl(bucketName, "x"); // remove last two characters to get clean url string of bucket. urlString = urlString.substring(0, urlString.length() - 2); Request request = requestBuilder.url(urlString).post(multipartBuilder.build()).build(); OkHttpClient transport = new OkHttpClient() .newBuilder() .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); Response response = transport.newCall(request).execute(); if (response == null) { throw new Exception("no response from server"); } if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new Scanner(response.body().charStream()); scanner.useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } scanner.close(); throw new Exception( "failed to upload object. Response: " + response + ", Error: " + errorXml); } client.removeObject(bucketName, objectName); mintSuccessLog("presignedPostPolicy(PostPolicy policy)", null, startTime); } catch (Exception e) { mintFailedLog( "presignedPostPolicy(PostPolicy policy)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: PutObject(): do put object using multi-threaded way in parallel. */ public static void threadedPutObject() throws Exception { if (!mintEnv) { System.out.println("Test: threadedPutObject"); } long startTime = System.currentTimeMillis(); try { Thread[] threads = new Thread[7]; for (int i = 0; i < 7; i++) { threads[i] = new Thread(new PutObjectRunnable(client, bucketName, createFile6Mb(), 6 * MB)); } for (int i = 0; i < 7; i++) { threads[i].start(); } // Waiting for threads to complete. for (int i = 0; i < 7; i++) { threads[i].join(); } // All threads are completed. mintSuccessLog( "putObject(String bucketName, String objectName, String filename)", "filename: threaded6MB", startTime); } catch (Exception e) { mintFailedLog( "putObject(String bucketName, String objectName, String filename)", "filename: threaded6MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: copyObject(String bucketName, String objectName, String destBucketName). */ public static void copyObject_test1() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); client.copyObject(destBucketName, objectName, null, null, bucketName, null, null, null); client.getObject(destBucketName, objectName).close(); client.removeObject(bucketName, objectName); client.removeObject(destBucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with ETag to match. */ public static void copyObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with Matching ETag (Negative Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); CopyConditions invalidETag = new CopyConditions(); invalidETag.setMatchETag("TestETag"); try { client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, invalidETag); } catch (ErrorResponseException e) { if (e.errorResponse().errorCode() != ErrorCode.PRECONDITION_FAILED) { throw e; } } client.removeObject(bucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName," + " CopyConditions copyConditions)", "CopyConditions: invalidETag", startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", "CopyConditions: invalidETag", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with ETag to match. */ public static void copyObject_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with Matching ETag (Positive Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); ObjectStat stat = client.statObject(bucketName, objectName); CopyConditions copyConditions = new CopyConditions(); copyConditions.setMatchETag(stat.etag()); // File should be copied as ETag set in copyConditions matches object's ETag. client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, copyConditions); client.getObject(destBucketName, objectName).close(); client.removeObject(bucketName, objectName); client.removeObject(destBucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName," + " CopyConditions copyConditions)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName," + " CopyConditions copyConditions)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with ETag to not match. */ public static void copyObject_test4() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with not matching ETag" + " (Positive Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); CopyConditions copyConditions = new CopyConditions(); copyConditions.setMatchETagNone("TestETag"); // File should be copied as ETag set in copyConditions doesn't match object's // ETag. client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, copyConditions); client.getObject(destBucketName, objectName).close(); client.removeObject(bucketName, objectName); client.removeObject(destBucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName," + " CopyConditions copyConditions)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with ETag to not match. */ public static void copyObject_test5() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with not matching ETag" + " (Negative Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); ObjectStat stat = client.statObject(bucketName, objectName); CopyConditions matchingETagNone = new CopyConditions(); matchingETagNone.setMatchETagNone(stat.etag()); try { client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, matchingETagNone); } catch (ErrorResponseException e) { // File should not be copied as ETag set in copyConditions matches object's // ETag. if (e.errorResponse().errorCode() != ErrorCode.PRECONDITION_FAILED) { throw e; } } client.removeObject(bucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with object modified after condition. */ public static void copyObject_test6() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with modified after " + "condition (Positive Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); CopyConditions modifiedDateCondition = new CopyConditions(); modifiedDateCondition.setModified(ZonedDateTime.of(2015, 05, 3, 3, 10, 10, 0, Time.UTC)); // File should be copied as object was modified after the set date. client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, modifiedDateCondition); client.getObject(destBucketName, objectName).close(); client.removeObject(bucketName, objectName); client.removeObject(destBucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", "CopyCondition: modifiedDateCondition", startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", "CopyCondition: modifiedDateCondition", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions) with object modified after condition. */ public static void copyObject_test7() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions) with modified after" + " condition (Negative Case)"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); CopyConditions invalidUnmodifiedCondition = new CopyConditions(); invalidUnmodifiedCondition.setUnmodified( ZonedDateTime.of(2015, 05, 3, 3, 10, 10, 0, Time.UTC)); try { client.copyObject( destBucketName, objectName, null, null, bucketName, null, null, invalidUnmodifiedCondition); } catch (ErrorResponseException e) { // File should not be copied as object was modified after date set in // copyConditions. if (e.errorResponse().errorCode() != ErrorCode.PRECONDITION_FAILED) { throw e; } } client.removeObject(bucketName, objectName); // Destination bucket is expected to be empty, otherwise it will trigger an // exception. client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", "CopyCondition: invalidUnmodifiedCondition", startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions)", "CopyCondition: invalidUnmodifiedCondition", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions, Map metadata) replace object metadata. */ public static void copyObject_test8() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions, Map<String, String> metadata)" + " replace object metadata"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); try (final InputStream is = new ContentInputStream(1 * KB)) { client.putObject(bucketName, objectName, is, new PutObjectOptions(1 * KB, -1)); } String destBucketName = getRandomName(); client.makeBucket(destBucketName); CopyConditions copyConditions = new CopyConditions(); copyConditions.setReplaceMetadataDirective(); Map<String, String> metadata = new HashMap<>(); metadata.put("Content-Type", customContentType); client.copyObject( destBucketName, objectName, metadata, null, bucketName, objectName, null, copyConditions); ObjectStat objectStat = client.statObject(destBucketName, objectName); if (!customContentType.equals(objectStat.contentType())) { throw new Exception( "content type differs. expected: " + customContentType + ", got: " + objectStat.contentType()); } client.removeObject(bucketName, objectName); client.removeObject(destBucketName, objectName); client.removeBucket(destBucketName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions, Map<String, String> metadata)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions, Map<String, String> metadata)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, String destBucketName, CopyConditions * copyConditions, Map metadata) remove object metadata. */ public static void copyObject_test9() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, String destBucketName," + "CopyConditions copyConditions, Map<String, String> metadata)" + " remove object metadata"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> headerMap = new HashMap<>(); headerMap.put("Test", "testValue"); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setHeaders(headerMap); client.putObject(bucketName, objectName, is, options); } // Attempt to remove the user-defined metadata from the object CopyConditions copyConditions = new CopyConditions(); copyConditions.setReplaceMetadataDirective(); client.copyObject( bucketName, objectName, new HashMap<String, String>(), null, bucketName, objectName, null, copyConditions); ObjectStat objectStat = client.statObject(bucketName, objectName); if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) { throw new Exception("expected user-defined metadata has been removed"); } client.removeObject(bucketName, objectName); mintSuccessLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions, Map<String, String> metadata)", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, String destBucketName, " + "CopyConditions copyConditions, Map<String, String> metadata)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String * destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget) To test using * SSE_C. */ public static void copyObject_test10() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_C. "); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); // Generate a new 256 bit AES key - This key must be remembered by the client. byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); ServerSideEncryption ssePut = ServerSideEncryption.withCustomerKey(secretKeySpec); ServerSideEncryption sseSource = ServerSideEncryption.withCustomerKey(secretKeySpec); byte[] keyTarget = "98765432100123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpecTarget = new SecretKeySpec(keyTarget, "AES"); ServerSideEncryption sseTarget = ServerSideEncryption.withCustomerKey(secretKeySpecTarget); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setSse(ssePut); client.putObject(bucketName, objectName, is, options); } // Attempt to remove the user-defined metadata from the object CopyConditions copyConditions = new CopyConditions(); copyConditions.setReplaceMetadataDirective(); client.copyObject( bucketName, objectName, null, sseTarget, bucketName, objectName, sseSource, copyConditions); client.statObject(bucketName, objectName, sseTarget); // Check for object existence. client.removeObject(bucketName, objectName); mintSuccessLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_C.", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_C.", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String * destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget) To test using * SSE_S3. */ public static void copyObject_test11() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_S3. "); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); ServerSideEncryption sse = ServerSideEncryption.atRest(); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } // Attempt to remove the user-defined metadata from the object CopyConditions copyConditions = new CopyConditions(); copyConditions.setReplaceMetadataDirective(); client.copyObject( bucketName, objectName, null, sse, bucketName, objectName, null, copyConditions); ObjectStat objectStat = client.statObject(bucketName, objectName); if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) { throw new Exception("expected user-defined metadata has been removed"); } client.removeObject(bucketName, objectName); mintSuccessLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_S3.", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_S3.", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, String * destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget) To test using * SSE_KMS. */ public static void copyObject_test12() throws Exception { if (!mintEnv) { System.out.println( "Test: copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_KMS. "); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); Map<String, String> myContext = new HashMap<>(); myContext.put("key1", "value1"); String keyId = ""; keyId = System.getenv("MINT_KEY_ID"); if (keyId.equals("")) { mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime); } ServerSideEncryption sse = ServerSideEncryption.withManagedKeys("keyId", myContext); try (final InputStream is = new ContentInputStream(1)) { PutObjectOptions options = new PutObjectOptions(1, -1); options.setSse(sse); client.putObject(bucketName, objectName, is, options); } // Attempt to remove the user-defined metadata from the object CopyConditions copyConditions = new CopyConditions(); copyConditions.setReplaceMetadataDirective(); client.copyObject( bucketName, objectName, null, sse, bucketName, objectName, null, copyConditions); ObjectStat objectStat = client.statObject(bucketName, objectName); if (objectStat.httpHeaders().containsKey("X-Amz-Meta-Test")) { throw new Exception("expected user-defined metadata has been removed"); } client.removeObject(bucketName, objectName); mintSuccessLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_KMS.", null, startTime); } catch (Exception e) { mintFailedLog( "copyObject(String bucketName, String objectName, ServerSideEncryption sseSource, " + "String destBucketName, CopyConditions copyConditions, ServerSideEncryption sseTarget)" + " using SSE_KMS.", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test1() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)."); } long startTime = System.currentTimeMillis(); try { String destinationObjectName = getRandomName(); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, null); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); client.composeObject(bucketName, destinationObjectName, listSourceObjects, null, null); Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, filename2); client.removeObject(bucketName, destinationObjectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "size: 6 MB & 6 MB ", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "size: 6 MB & 6 MB", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test2() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with offset and length."); } long startTime = System.currentTimeMillis(); try { String destinationObjectName = getRandomName(); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, 10L, 6291436L, null, null, null); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); client.composeObject(bucketName, destinationObjectName, listSourceObjects, null, null); Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, filename2); client.removeObject(bucketName, destinationObjectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with offset and length.", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)" + "with offset and length.", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with offset and length.", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test3() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with one source"); } long startTime = System.currentTimeMillis(); try { String destinationObjectName = getRandomName(); String filename1 = createFile6Mb(); client.putObject(bucketName, filename1, filename1, new PutObjectOptions(6 * MB, -1)); ComposeSource s1 = new ComposeSource(bucketName, filename1, 10L, 6291436L, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); client.composeObject(bucketName, destinationObjectName, listSourceObjects, null, null); Files.delete(Paths.get(filename1)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, destinationObjectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with one source.", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)" + "with one source.", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with one source.", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test4() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > userMetaData, ServerSideEncryption sseTarget) with SSE_C and SSE_C Target"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); // Generate a new 256 bit AES key - This key must be remembered by the client. byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); ServerSideEncryption ssePut = ServerSideEncryption.withCustomerKey(secretKeySpec); byte[] keyTarget = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpecTarget = new SecretKeySpec(keyTarget, "AES"); ServerSideEncryption sseTarget = ServerSideEncryption.withCustomerKey(secretKeySpecTarget); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); options.setSse(ssePut); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, ssePut); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, ssePut); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); client.composeObject(bucketName, objectName, listSourceObjects, null, sseTarget); Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, filename2); client.removeObject(bucketName, objectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with SSE_C and SSE_C Target", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with SSE_C and" + "SSE_C Target", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with SSE_C and ", "SSE_C Target", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test5() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > userMetaData, ServerSideEncryption sseTarget) with SSE_C on one source object"); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); // Generate a new 256 bit AES key - This key must be remembered by the client. byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); ServerSideEncryption ssePut = ServerSideEncryption.withCustomerKey(secretKeySpec); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); options.setSse(ssePut); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, new PutObjectOptions(6 * MB, -1)); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, ssePut); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); client.composeObject(bucketName, objectName, listSourceObjects, null, null); Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, filename2); client.removeObject(bucketName, objectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "with SSE_C on one source object ", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with SSE_C on and" + "one source object", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with SSE_C on ", "one source object", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** * Test: composeObject(String bucketName, String objectName, List&lt;ComposeSource&gt; * composeSources,Map &lt;String, String&gt; headerMap, ServerSideEncryption sseTarget). */ public static void composeObject_test6() throws Exception { if (!mintEnv) { System.out.println( "Test: composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > userMetaData, ServerSideEncryption sseTarget) with SSE_C Target only."); } long startTime = System.currentTimeMillis(); try { String objectName = getRandomName(); byte[] keyTarget = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpecTarget = new SecretKeySpec(keyTarget, "AES"); ServerSideEncryption sseTarget = ServerSideEncryption.withCustomerKey(secretKeySpecTarget); String filename1 = createFile6Mb(); String filename2 = createFile6Mb(); PutObjectOptions options = new PutObjectOptions(6 * MB, -1); client.putObject(bucketName, filename1, filename1, options); client.putObject(bucketName, filename2, filename2, options); ComposeSource s1 = new ComposeSource(bucketName, filename1, null, null, null, null, null); ComposeSource s2 = new ComposeSource(bucketName, filename2, null, null, null, null, null); List<ComposeSource> listSourceObjects = new ArrayList<ComposeSource>(); listSourceObjects.add(s1); listSourceObjects.add(s2); client.composeObject(bucketName, objectName, listSourceObjects, null, sseTarget); Files.delete(Paths.get(filename1)); Files.delete(Paths.get(filename2)); client.removeObject(bucketName, filename1); client.removeObject(bucketName, filename2); client.removeObject(bucketName, objectName); mintSuccessLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget)", "SSE_C Target only.", startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) with SSE_C only", null, startTime); } else { mintFailedLog( "composeObject(String bucketName, String objectName,List<ComposeSource> composeSources, " + "Map <String,String > headerMap, ServerSideEncryption sseTarget) SSE_C Target ", " only.", startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** Test: getBucketPolicy(String bucketName). */ public static void getBucketPolicy_test1() throws Exception { if (!mintEnv) { System.out.println("Test: getBucketPolicy(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetObject\"],\"Effect\":\"Allow\"," + "\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::" + bucketName + "/myobject*\"],\"Sid\":\"\"}]}"; client.setBucketPolicy(bucketName, policy); client.getBucketPolicy(bucketName); mintSuccessLog("getBucketPolicy(String bucketName)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog("getBucketPolicy(String bucketName)", null, startTime); } else { mintFailedLog( "getBucketPolicy(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** Test: setBucketPolicy(String bucketName, String policy). */ public static void setBucketPolicy_test1() throws Exception { if (!mintEnv) { System.out.println("Test: setBucketPolicy(String bucketName, String policy)"); } long startTime = System.currentTimeMillis(); try { String policy = "{\"Statement\":[{\"Action\":\"s3:GetObject\",\"Effect\":\"Allow\",\"Principal\":" + "\"*\",\"Resource\":\"arn:aws:s3:::" + bucketName + "/myobject*\"}],\"Version\": \"2012-10-17\"}"; client.setBucketPolicy(bucketName, policy); mintSuccessLog("setBucketPolicy(String bucketName, String policy)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } // Ignore NotImplemented error if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "setBucketPolicy(String bucketName, String objectPrefix, " + "PolicyType policyType)", null, startTime); } else { mintFailedLog( "setBucketPolicy(String bucketName, String objectPrefix, " + "PolicyType policyType)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } } /** Test: setBucketLifeCycle(String bucketName, String lifeCycle). */ public static void setBucketLifeCycle_test1() throws Exception { if (!mintEnv) { System.out.println("Test: setBucketLifeCycle(String bucketName, String lifeCycle)"); } long startTime = System.currentTimeMillis(); try { String lifeCycle = "<LifecycleConfiguration><Rule><ID>expire-bucket</ID><Prefix></Prefix>" + "<Status>Enabled</Status><Expiration><Days>365</Days></Expiration>" + "</Rule></LifecycleConfiguration>"; client.setBucketLifeCycle(bucketName, lifeCycle); mintSuccessLog("setBucketLifeCycle(String bucketName, String lifeCycle)", null, startTime); } catch (Exception e) { mintFailedLog( "setBucketLifeCycle(String bucketName, String lifeCycle) ", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: deleteBucketLifeCycle(String bucketName). */ public static void deleteBucketLifeCycle_test1() throws Exception { if (!mintEnv) { System.out.println("Test: deleteBucketLifeCycle(String bucketNam)"); } long startTime = System.currentTimeMillis(); try { client.deleteBucketLifeCycle(bucketName); mintSuccessLog("deleteBucketLifeCycle(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "deleteBucketLifeCycle(String bucketName) ", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getBucketLifeCycle(String bucketName). */ public static void getBucketLifeCycle_test1() throws Exception { if (!mintEnv) { System.out.println("Test: getBucketLifeCycle(String bucketName)"); } long startTime = System.currentTimeMillis(); try { client.getBucketLifeCycle(bucketName); mintSuccessLog("getBucketLifeCycle(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "getBucketLifeCycle(String bucketName) ", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** * Test: setBucketNotification(String bucketName, NotificationConfiguration * notificationConfiguration). */ public static void setBucketNotification_test1() throws Exception { // This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' // environment variables. String topic = System.getenv("MINIO_JAVA_TEST_TOPIC"); String region = System.getenv("MINIO_JAVA_TEST_REGION"); if (topic == null || topic.equals("") || region == null || region.equals("")) { // do not run functional test as required environment variables are missing. return; } if (!mintEnv) { System.out.println( "Test: setBucketNotification(String bucketName, " + "NotificationConfiguration notificationConfiguration)"); } long startTime = System.currentTimeMillis(); try { String destBucketName = getRandomName(); client.makeBucket(destBucketName, region); NotificationConfiguration notificationConfiguration = new NotificationConfiguration(); // Add a new topic configuration. List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic(topic); List<EventType> eventList = new LinkedList<>(); eventList.add(EventType.OBJECT_CREATED_PUT); eventList.add(EventType.OBJECT_CREATED_COPY); topicConfiguration.setEvents(eventList); topicConfiguration.setPrefixRule("images"); topicConfiguration.setSuffixRule("pg"); topicConfigurationList.add(topicConfiguration); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); client.setBucketNotification(destBucketName, notificationConfiguration); client.removeBucket(destBucketName); mintSuccessLog( "setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)", null, startTime); } catch (Exception e) { mintFailedLog( "setBucketNotification(String bucketName, NotificationConfiguration notificationConfiguration)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: getBucketNotification(String bucketName). */ public static void getBucketNotification_test1() throws Exception { // This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' // environment variables. String topic = System.getenv("MINIO_JAVA_TEST_TOPIC"); String region = System.getenv("MINIO_JAVA_TEST_REGION"); if (topic == null || topic.equals("") || region == null || region.equals("")) { // do not run functional test as required environment variables are missing. return; } if (!mintEnv) { System.out.println("Test: getBucketNotification(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String destBucketName = getRandomName(); client.makeBucket(destBucketName, region); NotificationConfiguration notificationConfiguration = new NotificationConfiguration(); // Add a new topic configuration. List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic(topic); List<EventType> eventList = new LinkedList<>(); eventList.add(EventType.OBJECT_CREATED_PUT); topicConfiguration.setEvents(eventList); topicConfigurationList.add(topicConfiguration); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); client.setBucketNotification(destBucketName, notificationConfiguration); String expectedResult = notificationConfiguration.toString(); notificationConfiguration = client.getBucketNotification(destBucketName); topicConfigurationList = notificationConfiguration.topicConfigurationList(); topicConfiguration = topicConfigurationList.get(0); topicConfiguration.setId(null); String result = notificationConfiguration.toString(); if (!result.equals(expectedResult)) { System.out.println("FAILED. expected: " + expectedResult + ", got: " + result); } client.removeBucket(destBucketName); mintSuccessLog("getBucketNotification(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "getBucketNotification(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: removeAllBucketNotification(String bucketName). */ public static void removeAllBucketNotification_test1() throws Exception { // This test requires 'MINIO_JAVA_TEST_TOPIC' and 'MINIO_JAVA_TEST_REGION' // environment variables. String topic = System.getenv("MINIO_JAVA_TEST_TOPIC"); String region = System.getenv("MINIO_JAVA_TEST_REGION"); if (topic == null || topic.equals("") || region == null || region.equals("")) { // do not run functional test as required environment variables are missing. return; } if (!mintEnv) { System.out.println("Test: removeAllBucketNotification(String bucketName)"); } long startTime = System.currentTimeMillis(); try { String destBucketName = getRandomName(); client.makeBucket(destBucketName, region); NotificationConfiguration notificationConfiguration = new NotificationConfiguration(); // Add a new topic configuration. List<TopicConfiguration> topicConfigurationList = notificationConfiguration.topicConfigurationList(); TopicConfiguration topicConfiguration = new TopicConfiguration(); topicConfiguration.setTopic(topic); List<EventType> eventList = new LinkedList<>(); eventList.add(EventType.OBJECT_CREATED_PUT); eventList.add(EventType.OBJECT_CREATED_COPY); topicConfiguration.setEvents(eventList); topicConfiguration.setPrefixRule("images"); topicConfiguration.setSuffixRule("pg"); topicConfigurationList.add(topicConfiguration); notificationConfiguration.setTopicConfigurationList(topicConfigurationList); client.setBucketNotification(destBucketName, notificationConfiguration); notificationConfiguration = new NotificationConfiguration(); String expectedResult = notificationConfiguration.toString(); client.removeAllBucketNotification(destBucketName); notificationConfiguration = client.getBucketNotification(destBucketName); String result = notificationConfiguration.toString(); if (!result.equals(expectedResult)) { throw new Exception("[FAILED] Expected: " + expectedResult + ", Got: " + result); } client.removeBucket(destBucketName); mintSuccessLog("removeAllBucketNotification(String bucketName)", null, startTime); } catch (Exception e) { mintFailedLog( "removeAllBucketNotification(String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } /** Test: listenBucketNotification(String bucketName). */ public static void listenBucketNotification_test1() throws Exception { if (!mintEnv) { System.out.println( "Test: listenBucketNotification(String bucketName, String prefix, " + "String suffix, String[] events)"); } long startTime = System.currentTimeMillis(); String file = createFile1Kb(); String bucketName = getRandomName(); CloseableIterator<Result<NotificationRecords>> ci = null; try { client.makeBucket(bucketName, region); String[] events = {"s3:ObjectCreated:*", "s3:ObjectAccessed:*"}; ci = client.listenBucketNotification(bucketName, "prefix", "suffix", events); client.putObject(bucketName, "prefix-random-suffix", file, new PutObjectOptions(1 * KB, -1)); while (ci.hasNext()) { NotificationRecords records = ci.next().get(); if (records.events().size() == 0) { continue; } boolean found = false; for (Event event : records.events()) { if (event.objectName().equals("prefix-random-suffix")) { found = true; break; } } if (found) { break; } } mintSuccessLog( "listenBucketNotification(String bucketName, String prefix, " + "String suffix, String[] events)", null, startTime); } catch (Exception e) { if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; ErrorResponse errorResponse = exp.errorResponse(); if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog( "listenBucketNotification(String bucketName, String prefix, " + "String suffix, String[] events)", null, startTime); return; } } mintFailedLog( "listenBucketNotification(String bucketName, String prefix, " + "String suffix, String[] events)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } finally { if (ci != null) { ci.close(); } Files.delete(Paths.get(file)); client.removeObject(bucketName, "prefix-random-suffix"); client.removeBucket(bucketName); } } /** * Test: selectObjectContent(String bucketName, String objectName, String sqlExpression, * InputSerialization is, OutputSerialization os, boolean requestProgress, Long scanStartRange, * Long scanEndRange, ServerSideEncryption sse). */ public static void selectObjectContent_test1() throws Exception { String testName = "selectObjectContent(String bucketName, String objectName, String sqlExpression," + " InputSerialization is, OutputSerialization os, boolean requestProgress," + " Long scanStartRange, Long scanEndRange, ServerSideEncryption sse)"; if (!mintEnv) { System.out.println("Test: " + testName); } long startTime = System.currentTimeMillis(); String objectName = getRandomName(); SelectResponseStream responseStream = null; try { String expectedResult = "1997,Ford,E350,\"ac, abs, moon\",3000.00\n" + "1999,Chevy,\"Venture \"\"Extended Edition\"\"\",,4900.00\n" + "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\"\",,5000.00\n" + "1996,Jeep,Grand Cherokee,\"MUST SELL!\n" + "air, moon roof, loaded\",4799.00\n"; byte[] data = ("Year,Make,Model,Description,Price\n" + expectedResult).getBytes(StandardCharsets.UTF_8); ByteArrayInputStream bais = new ByteArrayInputStream(data); client.putObject(bucketName, objectName, bais, new PutObjectOptions(data.length, -1)); String sqlExpression = "select * from S3Object"; InputSerialization is = new InputSerialization(null, false, null, null, FileHeaderInfo.USE, null, null, null); OutputSerialization os = new OutputSerialization(null, null, null, QuoteFields.ASNEEDED, null); responseStream = client.selectObjectContent( bucketName, objectName, sqlExpression, is, os, true, null, null, null); String result = new String(readAllBytes(responseStream), StandardCharsets.UTF_8); if (!result.equals(expectedResult)) { throw new Exception("result mismatch; expected: " + expectedResult + ", got: " + result); } Stats stats = responseStream.stats(); if (stats == null) { throw new Exception("stats is null"); } if (stats.bytesScanned() != 256) { throw new Exception( "stats.bytesScanned mismatch; expected: 258, got: " + stats.bytesScanned()); } if (stats.bytesProcessed() != 256) { throw new Exception( "stats.bytesProcessed mismatch; expected: 258, got: " + stats.bytesProcessed()); } if (stats.bytesReturned() != 222) { throw new Exception( "stats.bytesReturned mismatch; expected: 222, got: " + stats.bytesReturned()); } mintSuccessLog(testName, null, startTime); } catch (Exception e) { mintFailedLog( testName, null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } finally { if (responseStream != null) { responseStream.close(); } client.removeObject(bucketName, objectName); } } /** runTests: runs as much as possible of test combinations. */ public static void runTests() throws Exception { makeBucket_test1(); if (endpoint.toLowerCase(Locale.US).contains("s3")) { makeBucketwithRegion_test(); makeBucketWithPeriod_test(); } listBuckets_test(); bucketExists_test(); removeBucket_test(); setup(); putObject_test1(); putObject_test2(); putObject_test3(); putObject_test4(); putObject_test5(); putObject_test6(); putObject_test7(); putObject_test8(); putObject_test9(); putObject_test10(); putObject_test11(); statObject_test1(); getObject_test1(); getObject_test2(); getObject_test3(); getObject_test4(); getObject_test5(); getObject_test6(); getObject_test8(); listObject_test1(); listObject_test2(); listObject_test3(); listObject_test4(); listObject_test5(); listObject_test6(); removeObject_test1(); removeObject_test2(); listIncompleteUploads_test1(); listIncompleteUploads_test2(); listIncompleteUploads_test3(); removeIncompleteUploads_test(); presignedGetObject_test1(); presignedGetObject_test2(); presignedGetObject_test3(); presignedPutObject_test1(); presignedPutObject_test2(); presignedPostPolicy_test(); copyObject_test1(); copyObject_test2(); copyObject_test3(); copyObject_test4(); copyObject_test5(); copyObject_test6(); copyObject_test7(); copyObject_test8(); copyObject_test9(); composeObject_test1(); composeObject_test2(); composeObject_test3(); selectObjectContent_test1(); // SSE_C tests will only work over TLS connection Locale locale = Locale.ENGLISH; boolean tlsEnabled = endpoint.toLowerCase(locale).contains("https://"); if (tlsEnabled) { statObject_test2(); getObject_test7(); getObject_test9(); putObject_test12(); putObject_test13(); copyObject_test10(); composeObject_test4(); composeObject_test5(); composeObject_test6(); } statObject_test3(); // SSE_S3 and SSE_KMS only work with endpoint="s3.amazonaws.com" String requestUrl = endpoint; if (requestUrl.equals("s3.amazonaws.com")) { putObject_test14(); putObject_test15(); copyObject_test11(); copyObject_test12(); setBucketLifeCycle_test1(); getBucketLifeCycle_test1(); deleteBucketLifeCycle_test1(); } getBucketPolicy_test1(); setBucketPolicy_test1(); listenBucketNotification_test1(); threadedPutObject(); teardown(); // notification tests requires 'MINIO_JAVA_TEST_TOPIC' and // 'MINIO_JAVA_TEST_REGION' environment variables // to be set appropriately. setBucketNotification_test1(); getBucketNotification_test1(); removeAllBucketNotification_test1(); } /** runQuickTests: runs tests those completely quicker. */ public static void runQuickTests() throws Exception { makeBucket_test1(); listBuckets_test(); bucketExists_test(); removeBucket_test(); setup(); putObject_test1(); statObject_test1(); getObject_test1(); listObject_test1(); removeObject_test1(); listIncompleteUploads_test1(); removeIncompleteUploads_test(); presignedGetObject_test1(); presignedPutObject_test1(); presignedPostPolicy_test(); copyObject_test1(); getBucketPolicy_test1(); setBucketPolicy_test1(); selectObjectContent_test1(); listenBucketNotification_test1(); teardown(); } /** main(). */ public static void main(String[] args) { if (args.length != 4) { System.out.println("usage: FunctionalTest <ENDPOINT> <ACCESSKEY> <SECRETKEY> <REGION>"); System.exit(-1); } String dataDir = System.getenv("MINT_DATA_DIR"); if (dataDir != null && !dataDir.equals("")) { mintEnv = true; dataFile1Kb = Paths.get(dataDir, "datafile-1-kB"); dataFile6Mb = Paths.get(dataDir, "datafile-6-MB"); } String mintMode = null; if (mintEnv) { mintMode = System.getenv("MINT_MODE"); } endpoint = args[0]; accessKey = args[1]; secretKey = args[2]; region = args[3]; try { client = new MinioClient(endpoint, accessKey, secretKey); // Enable trace for debugging. // client.traceOn(System.out); // For mint environment, run tests based on mint mode if (mintEnv) { if (mintMode != null && mintMode.equals("full")) { FunctionalTest.runTests(); } else { FunctionalTest.runQuickTests(); } } else { FunctionalTest.runTests(); // Get new bucket name to avoid minio azure gateway failure. bucketName = getRandomName(); // Quick tests with passed region. client = new MinioClient(endpoint, accessKey, secretKey, region); FunctionalTest.runQuickTests(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } }
apache-2.0
kelemen/JTrim
subprojects/jtrim-executor/src/test/java/org/jtrim2/executor/TaskExecutorsTest.java
9195
package org.jtrim2.executor; import org.jtrim2.cancel.Cancellation; import org.jtrim2.cancel.CancellationToken; import org.jtrim2.testutils.TestUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; public class TaskExecutorsTest { @Test public void testUtilityClass() { TestUtils.testUtilityClass(TaskExecutors.class); } /** * Test of asUnstoppableExecutor method, of class TaskExecutors. */ @Test public void testAsUnstoppableExecutor() { TaskExecutorService subExecutor = mock(TaskExecutorService.class); TaskExecutorService executor = TaskExecutors.asUnstoppableExecutor(subExecutor); assertTrue(executor instanceof UnstoppableTaskExecutor); // just test if it really delegates its calls to subExecutor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verify(subExecutor).execute(any(CancellationToken.class), any(CancelableTask.class)); verifyNoMoreInteractions(subExecutor); } /** * Test of asUnstoppableExecutor method, of class TaskExecutors. */ @Test public void testAsUnstoppableExecutorForUnstoppable() { // For UnstoppableTaskExecutor we can return the same executor. TaskExecutorService subExecutor = new UnstoppableTaskExecutor(mock(TaskExecutorService.class)); TaskExecutorService executor = TaskExecutors.asUnstoppableExecutor(subExecutor); assertSame(subExecutor, executor); } @Test public void testInOrderExecutor() throws Exception { ManualTaskExecutor subExecutor = new ManualTaskExecutor(true); TaskExecutor executor = TaskExecutors.inOrderExecutor(subExecutor); assertTrue(executor instanceof InOrderTaskExecutor); // just test if it really delegates its calls to subExecutor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verifyZeroInteractions(task); subExecutor.executeCurrentlySubmitted(); verify(task).execute(any(CancellationToken.class)); } @Test public void testInOrderSimpleExecutor() throws Exception { ManualTaskExecutor subExecutor = new ManualTaskExecutor(true); TaskExecutor executor = TaskExecutors.inOrderSimpleExecutor(subExecutor); assertTrue(executor instanceof InOrderTaskExecutor); // just test if it really delegates its calls to subExecutor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verifyZeroInteractions(task); subExecutor.executeCurrentlySubmitted(); verify(task).execute(any(CancellationToken.class)); } @Test public void testInOrderExecutorAlreadyFifo1() { SingleThreadedExecutor executor = new SingleThreadedExecutor("TEST-POOL"); executor.dontNeedShutdown(); assertSame(executor, TaskExecutors.inOrderExecutor(executor)); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testInOrderExecutorAlreadyFifo2() { InOrderTaskExecutor executor = new InOrderTaskExecutor(SyncTaskExecutor.getSimpleExecutor()); assertSame(executor, TaskExecutors.inOrderExecutor(executor)); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testInOrderExecutorAlreadyFifo3() { SimpleThreadPoolTaskExecutor executor = new SimpleThreadPoolTaskExecutor("TEST-POOL", 1, 1, Thread::new); executor.dontNeedShutdown(); assertSame(executor, TaskExecutors.inOrderExecutor(executor)); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testSimpleThreadPoolTaskExecutorNotFifoWithMoreThreads() { SimpleThreadPoolTaskExecutor executor = new SimpleThreadPoolTaskExecutor("TEST-POOL", 2, 1, Thread::new); executor.dontNeedShutdown(); assertFalse("fifo", FifoExecutor.isFifoExecutor(executor)); } @Test public void testInOrderSimpleExecutorAlreadyFifo1() { SingleThreadedExecutor deepExecutor = new SingleThreadedExecutor("TEST-POOL"); deepExecutor.dontNeedShutdown(); TaskExecutor executor = TaskExecutors.asUnstoppableExecutor(deepExecutor); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testInOrderSimpleExecutorAlreadyFifo2() { SingleThreadedExecutor deepExecutor = new SingleThreadedExecutor("TEST-POOL"); deepExecutor.dontNeedShutdown(); TaskExecutor executor = new InOrderTaskExecutor(deepExecutor); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testInOrderSimpleExecutorAlreadyFifo3() { SimpleThreadPoolTaskExecutor deepExecutor = new SimpleThreadPoolTaskExecutor( "TEST-POOL", 1, 1, Thread::new ); deepExecutor.dontNeedShutdown(); TaskExecutor executor = new InOrderTaskExecutor(deepExecutor); assertSame(executor, TaskExecutors.inOrderSimpleExecutor(executor)); } @Test public void testInOrderSyncExecutor() throws Exception { TaskExecutor executor = TaskExecutors.inOrderSyncExecutor(); assertTrue(executor instanceof InOrderTaskExecutor); // just test if it really delegates its calls to a sync executor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verify(task).execute(any(CancellationToken.class)); } private static void checkSubmitDelegates( TaskExecutorService executor, ManualTaskExecutor wrapped) throws Exception { CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verifyZeroInteractions(task); wrapped.executeCurrentlySubmitted(); verify(task).execute(any(CancellationToken.class)); } @Test public void testUpgradeToStoppable() throws Exception { ManualTaskExecutor subExecutor = new ManualTaskExecutor(true); TaskExecutorService executor = TaskExecutors.upgradeToStoppable(subExecutor); assertTrue(executor instanceof UpgradedTaskExecutor); checkSubmitDelegates(executor, subExecutor); } @Test public void testUpgradeToUnstoppable() throws Exception { ManualTaskExecutor subExecutor = new ManualTaskExecutor(true); TaskExecutorService executor = TaskExecutors.upgradeToUnstoppable(subExecutor); assertTrue(executor instanceof UnstoppableTaskExecutor); checkSubmitDelegates(executor, subExecutor); } @Test public void testUpgradeToUnstoppableForUnstoppable() { // For UnstoppableTaskExecutor we can return the same executor. TaskExecutorService subExecutor = new UnstoppableTaskExecutor(mock(TaskExecutorService.class)); TaskExecutorService executor = TaskExecutors.upgradeToUnstoppable(subExecutor); assertSame(subExecutor, executor); } @Test public void testContextAwareIfNecessary() { TaskExecutor wrapped = mock(TaskExecutor.class); ContextAwareTaskExecutor executor = TaskExecutors.contextAwareIfNecessary(wrapped); assertTrue(executor instanceof ContextAwareWrapper); } @Test public void testContextAwareIfNecessaryOfContextAware() { ContextAwareTaskExecutor wrapped = mock(ContextAwareTaskExecutor.class); ContextAwareTaskExecutor executor = TaskExecutors.contextAwareIfNecessary(wrapped); assertSame(wrapped, executor); } @Test public void testDebugExecutorService() { TaskExecutorService subExecutor = mock(TaskExecutorService.class); TaskExecutor executor = TaskExecutors.debugExecutorService(subExecutor); assertTrue(executor instanceof DebugTaskExecutorService); // just test if it really delegates its calls to subExecutor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verify(subExecutor).execute( any(CancellationToken.class), any(CancelableTask.class)); verifyNoMoreInteractions(subExecutor); } @Test public void testDebugExecutor() { TaskExecutor subExecutor = mock(TaskExecutor.class); TaskExecutor executor = TaskExecutors.debugExecutor(subExecutor); assertTrue(executor instanceof DebugTaskExecutor); // just test if it really delegates its calls to subExecutor CancelableTask task = mock(CancelableTask.class); executor.execute(Cancellation.UNCANCELABLE_TOKEN, task); verify(subExecutor).execute( any(CancellationToken.class), any(CancelableTask.class)); verifyNoMoreInteractions(subExecutor); } }
apache-2.0
qafedev/qafe-platform
qafe-core/src/main/java/com/qualogy/qafe/bind/presentation/component/PasswordTextField.java
1104
/** * Copyright 2008-2017 Qualogy Solutions 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.qualogy.qafe.bind.presentation.component; /** * @author rjankie */ public class PasswordTextField extends TextField{ /** * */ private static final long serialVersionUID = 1364273197572324327L; /** * */ protected String passwordMask; /** * @return */ public String getPasswordMask() { return passwordMask; } /** * @param passwordMask */ public void setPasswordMask(String passwordMask) { this.passwordMask = passwordMask; } }
apache-2.0
sendy943/jfinal-wxmall
wxmall-service-provider/src/main/java/com/dbumama/market/service/provider/PalletElement.java
2394
package com.dbumama.market.service.provider; import java.io.IOException; import java.io.Serializable; import org.apache.commons.codec.binary.Base64; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; @SuppressWarnings("serial") public class PalletElement implements Serializable{ String label; //显示文本 String key; //JSON数据 key值 String type; //类型 分table span div img等 String text; //显示文本 String imgSrc; //当type为img的时候有值 String url; //加载数据的url public PalletElement(String label, String key) { this(label, key, ""); } public PalletElement(String label, String key, String text) { this(label, key, "", text, ""); } public PalletElement(String label, String key, String type, String url) { this(label, key, type, "", url); } public PalletElement(String label, String key, String type, String text, String url) { super(); this.label = label; this.key = key; this.type = type; this.text = text; this.url = url; if("img".equals(this.type)){ OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder(). url(getUrl()) .addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116Safari/537.36") .build(); try { Response okResponse = okHttpClient.newCall(request).execute(); Base64 base64 = new Base64(); final String result = "data:image/jpg;base64," + base64.encodeAsString(okResponse.body().bytes()); setImgSrc(result); } catch (IOException e) { e.printStackTrace(); setImgSrc(""); } } } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getImgSrc() { return imgSrc; } public void setImgSrc(String imgSrc) { this.imgSrc = imgSrc; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
apache-2.0
TatsianaKasiankova/pentaho-kettle
engine/src/test/java/org/pentaho/di/www/RunTransServletTest.java
7289
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2017-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.www; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LoggingObjectType; import org.pentaho.di.core.logging.SimpleLoggingObject; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryDirectoryInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMetaDataCombi; import org.pentaho.di.trans.step.StepMetaInterface; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import static org.mockito.Mockito.mock; @RunWith( MockitoJUnitRunner.class ) public class RunTransServletTest { @Mock TransMeta transMeta; @Mock Trans trans; List<StepMetaDataCombi> stepList; ByteArrayOutputStream outData; PrintWriter out; String lineSeparator = System.getProperty( "line.separator" ); String transId = "testId"; String expectedOutputIfNoServletOutputSteps = "<webresult>" + lineSeparator + " <result>OK</result>" + lineSeparator + " <message>Transformation started</message>" + lineSeparator + " <id>testId</id>" + lineSeparator + "</webresult>" + lineSeparator + lineSeparator; RunTransServlet runTransServlet; @Before public void setup() throws Exception { runTransServlet = new RunTransServlet(); outData = new ByteArrayOutputStream(); out = new PrintWriter( outData ); stepList = new ArrayList<>(); for ( int i = 0; i < 5; i++ ) { StepMetaDataCombi stepMetaDataCombi = new StepMetaDataCombi(); StepMetaInterface stepMeta = mock( StepMetaInterface.class ); when( stepMeta.passDataToServletOutput() ).thenReturn( false ); stepMetaDataCombi.meta = stepMeta; stepList.add( stepMetaDataCombi ); } when( trans.getSteps() ).thenReturn( stepList ); when( trans.getContainerObjectId() ).thenReturn( transId ); } @Test public void testFinishProcessingTransWithoutServletOutputSteps() throws Exception { runTransServlet.finishProcessing( trans, out ); assertEquals( expectedOutputIfNoServletOutputSteps, outData.toString() ); } @Test public void testFinishProcessingTransWithServletOutputSteps() throws Exception { StepMetaDataCombi stepMetaDataCombi = new StepMetaDataCombi(); StepMetaInterface stepMeta = mock( StepMetaInterface.class ); when( stepMeta.passDataToServletOutput() ).thenReturn( true ); stepMetaDataCombi.meta = stepMeta; stepList.add( stepMetaDataCombi ); doAnswer( new Answer<Void>() { @Override public Void answer( InvocationOnMock invocation ) throws Throwable { Thread.currentThread().sleep( 2000 ); return null; } } ).when( trans ).waitUntilFinished(); runTransServlet.finishProcessing( trans, out ); assertTrue( outData.toString().isEmpty() ); } @Test public void testRunTransServletCheckParameter() throws Exception { HttpServletRequest request = Mockito.mock( HttpServletRequest.class ); HttpServletResponse response = Mockito.mock( HttpServletResponse.class ); Mockito.when( request.getParameter( "trans" ) ).thenReturn( "home/test.rtr" ); StringWriter out = new StringWriter(); PrintWriter printWriter = new PrintWriter( out ); Mockito.when( request.getContextPath() ).thenReturn( RunTransServlet.CONTEXT_PATH ); Mockito.when( response.getWriter() ).thenReturn( printWriter ); TransformationMap mockTransformationMap = Mockito.mock( TransformationMap.class ); SlaveServerConfig slaveServerConfig = Mockito.mock( SlaveServerConfig.class ); Mockito.when( mockTransformationMap.getSlaveServerConfig() ).thenReturn( slaveServerConfig ); Repository repository = Mockito.mock( Repository.class ); Mockito.when( slaveServerConfig.getRepository() ).thenReturn( repository ); RepositoryDirectoryInterface repositoryDirectoryInterface = Mockito.mock( RepositoryDirectoryInterface.class ); Mockito.when( repository.loadRepositoryDirectoryTree() ).thenReturn( repositoryDirectoryInterface ); Mockito.when( repositoryDirectoryInterface.findDirectory( Mockito.anyString() ) ) .thenReturn( repositoryDirectoryInterface ); TransMeta transMeta = Mockito.mock( TransMeta.class ); Mockito.when( repository.loadTransformation( Mockito.any(), Mockito.any() ) ).thenReturn( transMeta ); String testParameter = "testParameter"; Mockito.when( transMeta.listVariables() ).thenReturn( new String[] { testParameter } ); Mockito.when( transMeta.getVariable( Mockito.anyString() ) ).thenReturn( "default value" ); Mockito.when( transMeta.listParameters() ).thenReturn( new String[] { testParameter } ); Mockito.when( request.getParameterNames() ).thenReturn( new StringTokenizer( testParameter ) ); String testValue = "testValue"; Mockito.when( request.getParameterValues( testParameter ) ).thenReturn( new String[] { testValue } ); RunTransServlet runTransServlet = Mockito.mock( RunTransServlet.class ); Mockito.doCallRealMethod().when( runTransServlet ).doGet( Mockito.anyObject(), Mockito.anyObject() ); Trans trans = new Trans( transMeta, new SimpleLoggingObject( RunTransServlet.CONTEXT_PATH, LoggingObjectType.CARTE, null ) ); Mockito.when( runTransServlet.createTrans( Mockito.anyObject(), Mockito.anyObject() ) ).thenReturn( trans ); Mockito.when( transMeta.getParameterValue( Mockito.eq( testParameter ) ) ).thenReturn( testValue ); runTransServlet.log = new LogChannel( "RunTransServlet" ); runTransServlet.transformationMap = mockTransformationMap; runTransServlet.doGet( request, response ); Assert.assertEquals( testValue, trans.getParameterValue( testParameter ) ); } }
apache-2.0
terrancesnyder/solr-analytics
solr/core/src/java/org/apache/solr/schema/TextField.java
11677
/* * 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.solr.schema; import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute; import org.apache.lucene.search.*; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.CachingTokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.util.BytesRef; import org.apache.solr.common.SolrException; import org.apache.solr.response.TextResponseWriter; import org.apache.solr.search.QParser; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.io.IOException; import java.io.StringReader; /** <code>TextField</code> is the basic type for configurable text analysis. * Analyzers for field types using this implementation should be defined in the schema. * */ public class TextField extends FieldType { protected boolean autoGeneratePhraseQueries; /** * Analyzer set by schema for text types to use when searching fields * of this type, subclasses can set analyzer themselves or override * getAnalyzer() * This analyzer is used to process wildcard, prefix, regex and other multiterm queries. It * assembles a list of tokenizer +filters that "make sense" for this, primarily accent folding and * lowercasing filters, and charfilters. * * @see #getMultiTermAnalyzer * @see #setMultiTermAnalyzer */ protected Analyzer multiTermAnalyzer=null; @Override protected void init(IndexSchema schema, Map<String,String> args) { properties |= TOKENIZED; if (schema.getVersion()> 1.1f) properties &= ~OMIT_TF_POSITIONS; if (schema.getVersion() > 1.3f) { autoGeneratePhraseQueries = false; } else { autoGeneratePhraseQueries = true; } String autoGeneratePhraseQueriesStr = args.remove("autoGeneratePhraseQueries"); if (autoGeneratePhraseQueriesStr != null) autoGeneratePhraseQueries = Boolean.parseBoolean(autoGeneratePhraseQueriesStr); super.init(schema, args); } /** * Returns the Analyzer to be used when searching fields of this type when mult-term queries are specified. * <p> * This method may be called many times, at any time. * </p> * @see #getAnalyzer */ public Analyzer getMultiTermAnalyzer() { return multiTermAnalyzer; } public void setMultiTermAnalyzer(Analyzer analyzer) { this.multiTermAnalyzer = analyzer; } public boolean getAutoGeneratePhraseQueries() { return autoGeneratePhraseQueries; } @Override public SortField getSortField(SchemaField field, boolean reverse) { /* :TODO: maybe warn if isTokenized(), but doesn't use LimitTokenCountFilter in it's chain? */ return getStringSort(field, reverse); } @Override public void write(TextResponseWriter writer, String name, IndexableField f) throws IOException { writer.writeStr(name, f.stringValue(), true); } @Override public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) { return parseFieldQuery(parser, getQueryAnalyzer(), field.getName(), externalVal); } @Override public Object toObject(SchemaField sf, BytesRef term) { return term.utf8ToString(); } @Override public void setAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; } @Override public void setQueryAnalyzer(Analyzer analyzer) { this.queryAnalyzer = analyzer; } @Override public Query getRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) { Analyzer multiAnalyzer = getMultiTermAnalyzer(); BytesRef lower = analyzeMultiTerm(field.getName(), part1, multiAnalyzer); BytesRef upper = analyzeMultiTerm(field.getName(), part2, multiAnalyzer); return new TermRangeQuery(field.getName(), lower, upper, minInclusive, maxInclusive); } public static BytesRef analyzeMultiTerm(String field, String part, Analyzer analyzerIn) { if (part == null) return null; TokenStream source; try { source = analyzerIn.tokenStream(field, new StringReader(part)); source.reset(); } catch (IOException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unable to initialize TokenStream to analyze multiTerm term: " + part, e); } TermToBytesRefAttribute termAtt = source.getAttribute(TermToBytesRefAttribute.class); BytesRef bytes = termAtt.getBytesRef(); try { if (!source.incrementToken()) throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"analyzer returned no terms for multiTerm term: " + part); termAtt.fillBytesRef(); if (source.incrementToken()) throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"analyzer returned too many terms for multiTerm term: " + part); } catch (IOException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"error analyzing range part: " + part, e); } try { source.end(); source.close(); } catch (IOException e) { throw new RuntimeException("Unable to end & close TokenStream after analyzing multiTerm term: " + part, e); } return BytesRef.deepCopyOf(bytes); } static Query parseFieldQuery(QParser parser, Analyzer analyzer, String field, String queryText) { int phraseSlop = 0; // most of the following code is taken from the Lucene QueryParser // Use the analyzer to get all the tokens, and then build a TermQuery, // PhraseQuery, or nothing based on the term count TokenStream source; try { source = analyzer.tokenStream(field, new StringReader(queryText)); source.reset(); } catch (IOException e) { throw new RuntimeException("Unable to initialize TokenStream to analyze query text", e); } CachingTokenFilter buffer = new CachingTokenFilter(source); CharTermAttribute termAtt = null; PositionIncrementAttribute posIncrAtt = null; int numTokens = 0; buffer.reset(); if (buffer.hasAttribute(CharTermAttribute.class)) { termAtt = buffer.getAttribute(CharTermAttribute.class); } if (buffer.hasAttribute(PositionIncrementAttribute.class)) { posIncrAtt = buffer.getAttribute(PositionIncrementAttribute.class); } int positionCount = 0; boolean severalTokensAtSamePosition = false; boolean hasMoreTokens = false; if (termAtt != null) { try { hasMoreTokens = buffer.incrementToken(); while (hasMoreTokens) { numTokens++; int positionIncrement = (posIncrAtt != null) ? posIncrAtt.getPositionIncrement() : 1; if (positionIncrement != 0) { positionCount += positionIncrement; } else { severalTokensAtSamePosition = true; } hasMoreTokens = buffer.incrementToken(); } } catch (IOException e) { // ignore } } try { // rewind the buffer stream buffer.reset(); // close original stream - all tokens buffered source.close(); } catch (IOException e) { // ignore } if (numTokens == 0) return null; else if (numTokens == 1) { String term = null; try { boolean hasNext = buffer.incrementToken(); assert hasNext == true; term = termAtt.toString(); } catch (IOException e) { // safe to ignore, because we know the number of tokens } // return newTermQuery(new Term(field, term)); return new TermQuery(new Term(field, term)); } else { if (severalTokensAtSamePosition) { if (positionCount == 1) { // no phrase query: // BooleanQuery q = newBooleanQuery(true); BooleanQuery q = new BooleanQuery(true); for (int i = 0; i < numTokens; i++) { String term = null; try { boolean hasNext = buffer.incrementToken(); assert hasNext == true; term = termAtt.toString(); } catch (IOException e) { // safe to ignore, because we know the number of tokens } // Query currentQuery = newTermQuery(new Term(field, term)); Query currentQuery = new TermQuery(new Term(field, term)); q.add(currentQuery, BooleanClause.Occur.SHOULD); } return q; } else { // phrase query: // MultiPhraseQuery mpq = newMultiPhraseQuery(); MultiPhraseQuery mpq = new MultiPhraseQuery(); mpq.setSlop(phraseSlop); List multiTerms = new ArrayList(); int position = -1; for (int i = 0; i < numTokens; i++) { String term = null; int positionIncrement = 1; try { boolean hasNext = buffer.incrementToken(); assert hasNext == true; term = termAtt.toString(); if (posIncrAtt != null) { positionIncrement = posIncrAtt.getPositionIncrement(); } } catch (IOException e) { // safe to ignore, because we know the number of tokens } if (positionIncrement > 0 && multiTerms.size() > 0) { mpq.add((Term[])multiTerms.toArray(new Term[multiTerms.size()]),position); multiTerms.clear(); } position += positionIncrement; multiTerms.add(new Term(field, term)); } mpq.add((Term[])multiTerms.toArray(new Term[multiTerms.size()]),position); return mpq; } } else { // PhraseQuery pq = newPhraseQuery(); PhraseQuery pq = new PhraseQuery(); pq.setSlop(phraseSlop); int position = -1; for (int i = 0; i < numTokens; i++) { String term = null; int positionIncrement = 1; try { boolean hasNext = buffer.incrementToken(); assert hasNext == true; term = termAtt.toString(); if (posIncrAtt != null) { positionIncrement = posIncrAtt.getPositionIncrement(); } } catch (IOException e) { // safe to ignore, because we know the number of tokens } position += positionIncrement; pq.add(new Term(field, term),position); } return pq; } } } }
apache-2.0
mpakhomov/algorithms-data-structures
src/test/java/com/mpakhomov/tree/RedBlackTreeTest.java
22092
package com.mpakhomov.tree; import org.junit.*; import java.util.*; import java.util.stream.Collectors; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; /** * @author: mpakhomov */ public class RedBlackTreeTest { /** * tree from the MIT algorithms book by * Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein * aka CLRS book Before Insertion 11:B / \ / \ / \ / \ 2:R 14:B / \ \ / \ \ 1:B 7:B 15:R / \ 5:R 8:R After insertion: 7:B / \ / \ / \ / \ 2:R 11:R / \ / \ / \ / \ 1:B 5:B 8:B 14:B / \ 4:R 15:R */ private RedBlackTree<Integer> treeFromTheBook; private List<List<String>> treeFromTheBookLol; @Before public void setUp() { buildRbtFromClrsBook(); buildTree2(); buildTree3(); } private void buildRbtFromClrsBook() { treeFromTheBook = new RedBlackTree<>(); treeFromTheBook.put(11); treeFromTheBook.put(14); treeFromTheBook.put(2); treeFromTheBook.put(1); treeFromTheBook.put(7); treeFromTheBook.put(5); treeFromTheBook.put(8); treeFromTheBook.put(15); treeFromTheBookLol = new ArrayList<>(); treeFromTheBookLol.add(Arrays.asList("7:B")); treeFromTheBookLol.add(Arrays.asList("2:R", "11:R")); treeFromTheBookLol.add(Arrays.asList("1:B", "5:B", "8:B", "14:B")); treeFromTheBookLol.add(Arrays.asList("4:R", "15:R")); } /** * tree2 before insertion * 7:B / \ / \ / \ / \ 3:B 18:R / \ / \ 10:B 22:B / \ \ 8:R 11:R 26:R After insertion 10:B / \ / \ / \ / \ 7:R 18:R / \ / \ / \ / \ 3:B 8:B 11:B 22:B \ \ 15:R 26:R */ private RedBlackTree<Integer> tree2; private List<List<String>> tree2Lol; private void buildTree2() { tree2 = new RedBlackTree(); tree2.put(7); tree2.put(3); tree2.put(18); tree2.put(10); tree2.put(22); tree2.put(8); tree2.put(11); tree2.put(26); // tree2.put(15); tree2Lol = new ArrayList<>(); tree2Lol.add(Arrays.asList("10:B")); tree2Lol.add(Arrays.asList("7:R", "18:R")); tree2Lol.add(Arrays.asList("3:B", "8:B", "11:B", "22:B")); tree2Lol.add(Arrays.asList("15:R", "26:R")); } /** * * tree 3 before insertion. 2:B / \ / \ / \ / \ 1:B 4:R / \ / \ 3:B 6:B / \ 5:R 7:R tree3 after insertion. 4:B / \ / \ / \ / \ 2:R 6:R / \ / \ / \ / \ 1:B 3:B 5:B 7:B \ 8:R */ private RedBlackTree<Integer> tree3; private List<List<String>> tree3Lol; private void buildTree3() { tree3 = new RedBlackTree<>(); tree3.put(1); tree3.put(2); tree3.put(3); tree3.put(4); tree3.put(5); tree3.put(6); tree3.put(7); // tree3.put(8); tree3Lol = new ArrayList<>(); tree3Lol.add(Arrays.asList("4:B")); tree3Lol.add(Arrays.asList("2:R", "6:R")); tree3Lol.add(Arrays.asList("1:B", "3:B", "5:B", "7:B")); tree3Lol.add(Arrays.asList("8:R")); } @Test public void testInsertionTreeFromTheBook() { treeFromTheBook.put(4); assertThat(treeFromTheBook.getSize(), equalTo(9)); List<Integer> actual = BinarySearchTree.traverseInOrderIterative(treeFromTheBook.getRoot()); assertThat(actual, contains(1, 2, 4, 5, 7, 8, 11, 14, 15)); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(treeFromTheBook.getRoot()); assertThat(levels, contains(treeFromTheBookLol.toArray())); } @Test public void testInsertionTree2() { tree2.put(15); assertThat(tree2.getSize(), equalTo(9)); List<Integer> actual = BinarySearchTree.traverseInOrderIterative(tree2.getRoot()); assertThat(actual, contains(3, 7, 8, 10, 11, 15, 18, 22, 26)); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree2.getRoot()); assertThat(levels, contains(tree2Lol.toArray())); } @Test public void testInsertionTree3() { tree3.put(8); assertThat(tree3.getSize(), equalTo(8)); List<Integer> actual = BinarySearchTree.traverseInOrderIterative(tree3.getRoot()); assertThat(actual, contains(1, 2, 3, 4, 5, 6, 7, 8)); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree3.getRoot()); assertThat(levels, contains(tree3Lol.toArray())); } /** * Node z (6) has 2 children (5, 15). z's successor y (11) is not a direct child of z. * y is a grandson of z. x = null. * 4:B / \ / \ / \ / \ 2:R 6:R / \ / \ / \ / \ 1:B 3:B 5:B 15:B / \ 11:R 40:R */ @Test public void deleteANodeWith2ChildrenXisNullRed() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(1); tree.put(2); tree.put(3); tree.put(4); tree.put(6); tree.put(5); tree.put(15); tree.put(40); tree.put(11); tree.rbtDelete(6); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("2:R", "11:R")); treeLol.add(Arrays.asList("1:B", "3:B", "5:B", "15:B")); treeLol.add(Arrays.asList("40:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(8)); } /** * Node z (6) has only one child (40) and the child is on the right. y = 6, x = 40 * 6 will be replaced with 40 and recolored to BLACK * * 4:B / \ / \ 2:B 6:B / \ \ 1:R 3:R 40:R */ @Test public void deleteANodeWithOnlyOneChildRedReplacementRecoloring() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(4); tree.put(2); tree.put(6); tree.put(1); tree.put(3); tree.put(40); tree.rbtDelete(6); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("2:B", "40:B")); treeLol.add(Arrays.asList("1:R", "3:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(5)); } /** * Node z (4) has 2 children (2, 6) and the child is on the right. y = 6, x = null * 4:B / \ / \ 2:B 6:B / \ 1:R 3:R */ @Test public void deleteANodeXisNullCase4() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(4); tree.put(2); tree.put(6); tree.put(1); tree.put(3); tree.rbtDelete(4); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("2:B")); treeLol.add(Arrays.asList("1:B", "6:B")); treeLol.add(Arrays.asList("3:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(4)); } /** * Node z (15) has 2 children (11, 40). z's successor y (40) is z's direct child. x = null * 4:B / \ / \ / \ / \ 2:R 6:R / \ / \ / \ / \ 1:B 3:B 5:B 15:B / \ 11:R 40:R */ @Test public void deleteANodeWith2ChildrenAndSuccessorIsDirectChild() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(1); tree.put(2); tree.put(3); tree.put(4); tree.put(6); tree.put(5); tree.put(15); tree.put(40); tree.put(11); tree.rbtDelete(15); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("2:R", "6:R")); treeLol.add(Arrays.asList("1:B", "3:B", "5:B", "40:B")); treeLol.add(Arrays.asList("11:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(8)); } /** * Node z (2) has 2 children (1, 3). z's successor y (3) is z's direct child. x = null * 4:B / \ / \ / \ / \ 2:R 6:R / \ / \ / \ / \ 1:B 3:B 5:B 15:B / \ 11:R 40:R */ @Test public void deletionYnotNullXIsNullCase2() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(1); tree.put(2); tree.put(3); tree.put(4); tree.put(6); tree.put(5); tree.put(15); tree.put(40); tree.put(11); tree.rbtDelete(2); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("3:B", "6:R")); treeLol.add(Arrays.asList("1:R", "5:B", "15:B")); treeLol.add(Arrays.asList("11:R", "40:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(8)); } /** * Node z (4) has 2 children (2, 7). z's successor y (5) is z's grandson. * x (6) is not null. * 4:B / \ / \ / \ / \ 2:B 7:R / \ / \ / \ / \ 1:R 3:R 5:B 10:B \ \ 6:R 20:R * * */ @Test public void deleteANodeWith2ChildrenAndSuccessorIsNotDirectChildAndXIsNotNull() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(4); tree.put(2); tree.put(10); tree.put(1); tree.put(3); tree.put(5); tree.put(7); tree.put(20); tree.put(6); tree.rbtDelete(4); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("5:B")); treeLol.add(Arrays.asList("2:B", "7:R")); treeLol.add(Arrays.asList("1:R", "3:R", "6:B", "10:B")); treeLol.add(Arrays.asList("20:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(8)); } /** * Node z (7) has 2 children (5, 10). z's successor y (10) and it's a direct child of z (z = y.p) * x (20) is not null * 4:B / \ / \ / \ / \ 2:B 7:R / \ / \ / \ / \ 1:R 3:R 5:B 10:B \ \ 6:R 20:R * * */ @Test public void deleteANodeWith2ChildrenAndSuccessorIsDirectChildAndXIsNotNull() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(4); tree.put(2); tree.put(10); tree.put(1); tree.put(3); tree.put(5); tree.put(7); tree.put(20); tree.put(6); tree.rbtDelete(7); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("2:B", "10:R")); treeLol.add(Arrays.asList("1:R", "3:R", "5:B", "20:B")); treeLol.add(Arrays.asList("6:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(8)); } /** * z = 5, z has 2 children (2, 8), y = 8. y is a son of z. x = null * 5:B / \ / \ / \ / \ 2:R 8:B / \ / \ 1:B 4:B / 3:R */ @Test public void deleteRootElementCase1Case4() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(5); tree.put(2); tree.put(8); tree.put(1); tree.put(4); tree.put(3); tree.rbtDelete(5); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("2:B")); treeLol.add(Arrays.asList("1:B", "4:R")); treeLol.add(Arrays.asList("3:B", "8:B")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(5)); } /** * z = 2, z has 2 children (1, 3), y = 3. y is a son of z. x = null * 4:B / \ / \ / \ / \ 2:R 6:R / \ / \ / \ / \ 1:B 3:B 5:B 7:B \ 8:R */ @Test public void delete2ChildXisNullCase2() { tree3.put(8); tree3.rbtDelete(2); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("3:B", "6:R")); treeLol.add(Arrays.asList("1:R", "5:B", "7:B")); treeLol.add(Arrays.asList("8:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree3.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree3.getSize(), equalTo(7)); } /** * z = 18, 2 children (10, 22). y = 22, direct child. x = 26. x is red * 7:B / \ / \ / \ / \ 3:B 18:R / \ / \ 10:B 22:B / \ \ 8:R 11:R 26:R */ @Test public void delete2ChildXIsNotNullXRed() { tree2.rbtDelete(18); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("7:B")); treeLol.add(Arrays.asList("3:B", "22:R")); treeLol.add(Arrays.asList("10:B", "26:B")); treeLol.add(Arrays.asList("8:R", "11:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree2.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree2.getSize(), equalTo(7)); } @Test public void deletionFromTreeWithOneElement() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(1); tree.rbtDelete(1); assertThat(tree.getSize(), equalTo(0)); assertThat(tree.getRoot(), is(nullValue())); } /** * z = 1, y = null, x= 1 * * 2:B * / * 1:B */ @Test public void deletionFromTreeWithTwoElements() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(1); tree.put(2); boolean result = tree.rbtDelete(1); assertThat(result, is(true)); assertThat(tree.getSize(), equalTo(1)); RbtNode<Integer> root = (RbtNode<Integer>)tree.getRoot(); assertThat(root.left, is(nullValue())); assertThat(root.right, is(nullValue())); assertThat(root.parent, is(nullValue())); assertThat(root.key, equalTo(2)); } /** * z = 2, y = null, x = 1. In rbDeleteFixUp x is recolored to BLACK * * 4:B / \ / \ 2:B 7:B / / \ 1:R 5:R 10:R * */ @Test public void deleteReplaceWithLeftChildAndRecoloring() { RedBlackTree<Integer> tree = new RedBlackTree<>(); tree.put(4); tree.put(2); tree.put(10); tree.put(1); tree.put(5); tree.put(7); tree.rbtDelete(2); List<List<String>> treeLol = new ArrayList<>(); treeLol.add(Arrays.asList("4:B")); treeLol.add(Arrays.asList("1:B", "7:B")); treeLol.add(Arrays.asList("5:R", "10:R")); List<List<String>> levels = BinarySearchTree.traverseByLevelsAsString(tree.getRoot()); assertThat(levels, contains(treeLol.toArray())); assertThat(tree.getSize(), equalTo(5)); } @Test public void tree0to19Delete() { RedBlackTree tree = new RedBlackTree(); for (int i = 0; i < 20; i++) { tree.put(i); } // BTreePrinter.printNode(tree.getRoot()); tree.rbtDelete(4); tree.rbtDelete(7); tree.rbtDelete(6); tree.rbtDelete(14); tree.rbtDelete(8); tree.rbtDelete(19); tree.rbtDelete(0); tree.rbtDelete(1); tree.rbtDelete(13); tree.rbtDelete(5); tree.rbtDelete(2); tree.rbtDelete(18); tree.rbtDelete(17); tree.rbtDelete(9); tree.rbtDelete(15); tree.rbtDelete(16); tree.rbtDelete(11); // BTreePrinter.printNode(tree.getRoot()); verifyRbtOf3Nodes(tree); } @Test public void randomTreeDelete() { Random random = new Random(); final int size = 1000; List<Integer> randomIntegers = new ArrayList<>(size); RedBlackTree tree = new RedBlackTree(); for (int i = 0; i < size; i++) { int randomInt = random.nextInt(10_000); randomIntegers.add(randomInt); tree.put(randomInt); } // System.out.println("Random numbers: " + // randomIntegers.stream() // .map(String::valueOf) // .collect(Collectors.joining(" "))); Collections.shuffle(randomIntegers); ArrayDeque<Integer> queue = new ArrayDeque<>(size); queue.addAll(randomIntegers); // BTreePrinter.printNode(tree.getRoot()); while (queue.size() >= 4) { int randomElement = queue.poll(); // System.out.println("delete " + randomElement); tree.rbtDelete(randomElement); } // BTreePrinter.printNode(tree.getRoot()); verifyRbtOf3Nodes(tree); } @Test public void testDeleteFromEmptyTree() { RedBlackTree<Integer> tree = new RedBlackTree<>(); boolean result = tree.rbtDelete(1); assertThat(result, is(false)); } @Test(expected = NullPointerException.class) public void testDeleteNullFromTree() { Integer nullInteger = null; tree2.rbtDelete(nullInteger); } private void verifyRbtOf3Nodes(RedBlackTree<Integer> tree) { RbtNode<Integer> root = (RbtNode<Integer>)tree.getRoot(); assertThat(tree.getSize(), equalTo(3)); assertThat(root.color, equalTo(RedBlackTree.BLACK)); RbtNode<Integer> left = (RbtNode<Integer>)root.left; RbtNode<Integer> right = (RbtNode<Integer>)root.right; assertThat(left, is(notNullValue())); assertThat(left.parent, equalTo(root)); assertThat(right, is(notNullValue())); assertThat(right.parent, equalTo(root)); assertThat(left.left, is(nullValue())); assertThat(left.right, is(nullValue())); assertThat(right.left, is(nullValue())); assertThat(right.right, is(nullValue())); // check color. should be the same boolean leafColor = left.color; assertThat(right.color, equalTo(leafColor)); } }
apache-2.0
torrances/swtk-commons
commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/instance/g/o/t/WordnetNounIndexNameInstanceGOT.java
2639
package org.swtk.commons.dict.wordnet.indexbyname.instance.g.o.t; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexNameInstanceGOT { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("{\"term\":\"gota canal\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"03453758\"]}"); add("{\"term\":\"goteborg\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08784500\"]}"); add("{\"term\":\"goth\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"10159294\", \"10430560\"]}"); add("{\"term\":\"gothenburg\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08784500\"]}"); add("{\"term\":\"gothic\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05850914\", \"06839639\", \"06968446\"]}"); add("{\"term\":\"gothic arch\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"03453900\"]}"); add("{\"term\":\"gothic architecture\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05850914\"]}"); add("{\"term\":\"gothic romance\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06381028\"]}"); add("{\"term\":\"gothic romancer\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"10159464\"]}"); add("{\"term\":\"gothite\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"14701475\"]}"); add("{\"term\":\"gotterdammerung\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06384548\"]}"); add("{\"term\":\"gottfried wilhelm leibnitz\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11145183\"]}"); add("{\"term\":\"gottfried wilhelm leibniz\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11145183\"]}"); add("{\"term\":\"gotthold ephraim lessing\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"11149655\"]}"); add("{\"term\":\"gottlieb daimler\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"10940761\"]}"); } private static void add(final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(indexNoun.getTerm())) ? map.get(indexNoun.getTerm()) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(indexNoun.getTerm(), list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> terms() { return map.keySet(); } }
apache-2.0
QuincySx/ListDataStatusLayout
app/src/main/java/com/quincysx/sample/view/ErrorView.java
852
package com.quincysx.sample.view; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.quincysx.sample.R; import com.quincysx.statuslayout.StatusView; /** * Created by quincysx on 2017/10/4. */ public class ErrorView extends StatusView { public ErrorView() { } @Override protected View initContentView() { View inflate = View.inflate(getContext(), R.layout.commonlayout, null); TextView textView = inflate.findViewById(R.id.common_hint); textView.setText("出现了错误"); ImageView imageView = inflate.findViewById(R.id.common_image); Glide.with(getContext()).load(R.drawable.ic_data_status_error).into(imageView); return inflate; } @Override protected void onFeedback() { } }
apache-2.0
neykov/incubator-brooklyn
software/base/src/main/java/brooklyn/entity/basic/VanillaSoftwareProcess.java
3139
/* * 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 brooklyn.entity.basic; import brooklyn.config.ConfigKey; import brooklyn.entity.proxying.ImplementedBy; import brooklyn.event.basic.BasicAttributeSensorAndConfigKey; /** * downloads and unpacks the archive indicated (optionally), * then runs the management commands (scripts) indicated * (relative to the root of the archive if supplied, otherwise in a tmp working dir) to manage * <p> * uses config keys to identify the files / commands to use * <p> * in simplest mode, simply provide either: * <li> an archive in {@link #DOWNLOAD_URL} containing a <code>./start.sh</code> * <li> a start command to invoke in {@link #LAUNCH_COMMAND} * <p> * the only constraint is that the start command must write the PID into the file pointed to by the injected environment variable PID_FILE, * unless one of the options below is supported. * <p> * the start command can be a complex bash command, downloading and unpacking files, and/or handling the PID_FILE requirement * (e.g. <code>export MY_PID_FILE=$PID_FILE ; ./my_start.sh</code> or <code>nohup ./start.sh & ; echo $! > $PID_FILE ; sleep 5</code>), * and of course you can supply both {@link #DOWNLOAD_URL} and {@link #LAUNCH_COMMAND}. * <p> * by default the PID is used to stop the process (kill followed by kill -9 if needed) and restart (process stop followed by process start), * but it is possible to override this behavior through config keys: * <li> a custom {@link #CHECK_RUNNING_COMMAND} * <li> a custom {@link #STOP_COMMAND} * <li> specify which {@link SoftwareProcess#PID_FILE} to use */ @ImplementedBy(VanillaSoftwareProcessImpl.class) public interface VanillaSoftwareProcess extends SoftwareProcess { BasicAttributeSensorAndConfigKey<String> DOWNLOAD_URL = SoftwareProcess.DOWNLOAD_URL; ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.0.0"); ConfigKey<String> LAUNCH_COMMAND = ConfigKeys.newStringConfigKey("launch.command", "command to run to launch the process", "./start.sh"); ConfigKey<String> CHECK_RUNNING_COMMAND = ConfigKeys.newStringConfigKey("checkRunning.command", "command to determine whether the process is running"); ConfigKey<String> STOP_COMMAND = ConfigKeys.newStringConfigKey("stop.command", "command to run to stop the process"); }
apache-2.0
Maylinne/ElMo
app/src/main/java/com/example/android/elmo/FightButtonFragment.java
1393
package com.example.android.elmo; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; /** * A simple {@link Fragment} subclass. */ public class FightButtonFragment extends Fragment { public FightButtonFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View fbView = inflater.inflate(R.layout.fragment_fight_button, container, false); // Fight button ImageButton fight_btn = (ImageButton) fbView.findViewById(R.id.fight); fight_btn.setImageResource(R.drawable.fight_btn); // What does the fight button fight_btn.setOnClickListener(new View.OnClickListener() { // The code in this method will be executed when the fight button View is clicked on. @Override public void onClick(View view) { Intent mainIntent = new Intent(view.getContext(), FightActivity.class); startActivityForResult(mainIntent, 1); } }); // endregion return fbView; } }
apache-2.0
shivpun/spring-framework
spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java
6726
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.client; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.Arrays; import java.util.Locale; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.StreamingHttpOutputMessage; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; import static org.junit.Assert.*; /** * @author Arjen Poutsma */ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractJettyServerTestCase { protected ClientHttpRequestFactory factory; @Before public final void createFactory() throws Exception { factory = createRequestFactory(); if (factory instanceof InitializingBean) { ((InitializingBean) factory).afterPropertiesSet(); } } @After public final void destroyFactory() throws Exception { if (factory instanceof DisposableBean) { ((DisposableBean) factory).destroy(); } } protected abstract ClientHttpRequestFactory createRequestFactory(); @Test public void status() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); assertEquals("Invalid HTTP URI", uri, request.getURI()); ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode()); } finally { response.close(); } } @Test public void echo() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); String headerValue2 = "value2"; request.getHeaders().add(headerName, headerValue2); final byte[] body = "Hello World".getBytes("UTF-8"); request.getHeaders().setContentLength(body.length); if (request instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request; streamingRequest.setBody(new StreamingHttpOutputMessage.Body() { @Override public void writeTo(OutputStream outputStream) throws IOException { StreamUtils.copy(body, outputStream); } }); } else { StreamUtils.copy(body, request.getBody()); } ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertTrue("Header not found", response.getHeaders().containsKey(headerName)); assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), response.getHeaders().get(headerName)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); } finally { response.close(); } } @Test(expected = IllegalStateException.class) public void multipleWrites() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes("UTF-8"); if (request instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request; streamingRequest.setBody(new StreamingHttpOutputMessage.Body() { @Override public void writeTo(OutputStream outputStream) throws IOException { StreamUtils.copy(body, outputStream); } }); } else { StreamUtils.copy(body, request.getBody()); } ClientHttpResponse response = request.execute(); try { FileCopyUtils.copy(body, request.getBody()); } finally { response.close(); } } @Test(expected = UnsupportedOperationException.class) public void headersAfterExecute() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); request.getHeaders().add("MyHeader", "value"); byte[] body = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { request.getHeaders().add("MyHeader", "value"); } finally { response.close(); } } @Test public void httpMethods() throws Exception { assertHttpMethod("get", HttpMethod.GET); assertHttpMethod("head", HttpMethod.HEAD); assertHttpMethod("post", HttpMethod.POST); assertHttpMethod("put", HttpMethod.PUT); assertHttpMethod("options", HttpMethod.OPTIONS); assertHttpMethod("delete", HttpMethod.DELETE); } protected void assertHttpMethod(String path, HttpMethod method) throws Exception { ClientHttpResponse response = null; try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method); if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { // requires a body try { request.getBody().write(32); } catch (UnsupportedOperationException ex) { // probably a streaming request - let's simply ignore it } } response = request.execute(); assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); assertEquals("Invalid method", path.toUpperCase(Locale.ENGLISH), request.getMethod().name()); } finally { if (response != null) { response.close(); } } } @Test public void queryParameters() throws Exception { URI uri = new URI(baseUrl + "/params?param1=value&param2=value1&param2=value2"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); ClientHttpResponse response = request.execute(); try { assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); } finally { response.close(); } } }
apache-2.0
aitusoftware/transport
src/main/java/com/aitusoftware/transport/net/TopicToChannelMapper.java
1667
/* * Copyright 2017 - 2018 Aitu Software Limited. * * 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.aitusoftware.transport.net; import com.aitusoftware.transport.threads.SingleThreaded; import org.agrona.collections.Int2ObjectHashMap; import java.nio.channels.GatheringByteChannel; import java.nio.channels.SocketChannel; import java.util.function.IntFunction; @SingleThreaded public final class TopicToChannelMapper { private final IntFunction<SocketChannel> connector; private final Int2ObjectHashMap<SocketChannel> openChannels = new Int2ObjectHashMap<>(); public TopicToChannelMapper(final IntFunction<SocketChannel> connector) { this.connector = connector; } GatheringByteChannel forTopic(final int topicId) { SocketChannel channel = openChannels.get(topicId); if (channel != null) { return channel; } final SocketChannel connected = connector.apply(topicId); openChannels.put(topicId, connected); return connected; } void reconnectChannel(final int topicId) { openChannels.remove(topicId); } }
apache-2.0
masreis/e-commerce-hibernate-search
src/main/java/net/marcoreis/ecommerce/controlador/BaseBean.java
1432
package net.marcoreis.ecommerce.controlador; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.apache.log4j.Logger; import net.marcoreis.ecommerce.entidades.Cliente; public class BaseBean implements Serializable { private static final long serialVersionUID = -5895396595360064610L; protected static final Logger logger = Logger.getLogger(BaseBean.class); protected static final String MENSAGEM_SUCESSO_GRAVACAO = "Dados gravados com sucesso"; protected Cliente cliente; protected void infoMsg(String message) { FacesMessage msg = new FacesMessage(message); FacesContext.getCurrentInstance().addMessage(null, msg); } protected void errorMsg(Throwable t) { logger.error(t); FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, t.getMessage(), "Erro"); FacesContext.getCurrentInstance().addMessage(null, msg); } protected void errorMsg(String message) { FacesMessage msg = new FacesMessage( FacesMessage.SEVERITY_ERROR, message, "Erro"); FacesContext.getCurrentInstance().addMessage(null, msg); } public String getParametro(String parametro) { return FacesContext.getCurrentInstance() .getExternalContext().getRequestParameterMap() .get(parametro); } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Cliente getCliente() { return cliente; } }
apache-2.0
cli/bean
java/src/main/java/java/io/FileOutputStream.java
1390
/* * Bean Java VM * Copyright (C) 2005-2015 Christian Lins <christian@lins.me> * * 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 java.io; /** * * @author Christian Lins */ public class FileOutputStream extends OutputStream { private boolean useStdOut = false; public FileOutputStream(FileDescriptor fd) { if(FileDescriptor.out.equals(fd)) { this.useStdOut = true; } } /** This method is redirected to stdout by Bean JVM */ private native void writeToStdout(byte[] buf, int off, int len); public void write(int i) throws IOException { if(this.useStdOut) { writeToStdout(new byte[] {(byte)(0x000000FF & i)}, 0, 1); } } public void write(byte[] buf, int off, int len) throws IOException { writeToStdout(buf, off, len); } }
apache-2.0
DALDEI/byte-buddy
byte-buddy-dep/src/test/java/net/bytebuddy/pool/TypePoolDefaultWithLazyResolutionTypeDescriptionTest.java
13512
package net.bytebuddy.pool; import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.type.AbstractTypeDescriptionTest; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.scaffold.InstrumentedType; import net.bytebuddy.dynamic.scaffold.MethodGraph; import net.bytebuddy.dynamic.scaffold.TypeValidation; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; import static net.bytebuddy.matcher.ElementMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class TypePoolDefaultWithLazyResolutionTypeDescriptionTest extends AbstractTypeDescriptionTest { protected TypeDescription describe(Class<?> type) { return describe(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader()), TypePool.CacheProvider.NoOp.INSTANCE); } private static TypeDescription describe(Class<?> type, ClassFileLocator classFileLocator, TypePool.CacheProvider cacheProvider) { return new TypePool.Default.WithLazyResolution(cacheProvider, classFileLocator, TypePool.Default.ReaderMode.EXTENDED).describe(type.getName()).resolve(); } protected TypeDescription.Generic describeType(Field field) { return describe(field.getDeclaringClass()).getDeclaredFields().filter(is(field)).getOnly().getType(); } protected TypeDescription.Generic describeReturnType(Method method) { return describe(method.getDeclaringClass()).getDeclaredMethods().filter(is(method)).getOnly().getReturnType(); } protected TypeDescription.Generic describeParameterType(Method method, int index) { return describe(method.getDeclaringClass()).getDeclaredMethods().filter(is(method)).getOnly().getParameters().get(index).getType(); } protected TypeDescription.Generic describeExceptionType(Method method, int index) { return describe(method.getDeclaringClass()).getDeclaredMethods().filter(is(method)).getOnly().getExceptionTypes().get(index); } protected TypeDescription.Generic describeSuperClass(Class<?> type) { return describe(type).getSuperClass(); } protected TypeDescription.Generic describeInterfaceType(Class<?> type, int index) { return describe(type).getInterfaces().get(index); } @Test public void testTypeIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); TypePool typePool = TypePool.Default.WithLazyResolution.of(classFileLocator); TypePool.Resolution resolution = typePool.describe(Object.class.getName()); assertThat(resolution.resolve().getName(), CoreMatchers.is(TypeDescription.OBJECT.getName())); verifyZeroInteractions(classFileLocator); } @Test public void testReferencedTypeIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); TypePool typePool = TypePool.Default.WithLazyResolution.of(classFileLocator); TypePool.Resolution resolution = typePool.describe(String.class.getName()); assertThat(resolution.resolve().getName(), CoreMatchers.is(TypeDescription.STRING.getName())); assertThat(resolution.resolve().getSuperClass().asErasure().getName(), CoreMatchers.is(TypeDescription.OBJECT.getName())); verify(classFileLocator).locate(String.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testTypeIsCached() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); TypePool typePool = TypePool.Default.WithLazyResolution.of(classFileLocator); TypePool.Resolution resolution = typePool.describe(Object.class.getName()); assertThat(resolution.resolve().getModifiers(), CoreMatchers.is(TypeDescription.OBJECT.getModifiers())); assertThat(resolution.resolve().getInterfaces(), CoreMatchers.is(TypeDescription.OBJECT.getInterfaces())); assertThat(typePool.describe(Object.class.getName()).resolve(), CoreMatchers.is(resolution.resolve())); verify(classFileLocator).locate(Object.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testReferencedTypeIsCached() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); TypePool typePool = TypePool.Default.WithLazyResolution.of(classFileLocator); TypePool.Resolution resolution = typePool.describe(String.class.getName()); assertThat(resolution.resolve().getModifiers(), CoreMatchers.is(TypeDescription.STRING.getModifiers())); TypeDescription superClass = resolution.resolve().getSuperClass().asErasure(); assertThat(superClass, CoreMatchers.is(TypeDescription.OBJECT)); assertThat(superClass.getModifiers(), CoreMatchers.is(TypeDescription.OBJECT.getModifiers())); assertThat(superClass.getInterfaces(), CoreMatchers.is(TypeDescription.OBJECT.getInterfaces())); assertThat(typePool.describe(String.class.getName()).resolve(), CoreMatchers.is(resolution.resolve())); verify(classFileLocator).locate(String.class.getName()); verify(classFileLocator).locate(Object.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericResolutionIsLazyForSimpleCreationNonFrozen() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); new ByteBuddy() .with(TypeValidation.DISABLED) .with(MethodGraph.Empty.INSTANCE) .with(InstrumentedType.Factory.Default.MODIFIABLE) .redefine(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator) .make(); verify(classFileLocator, times(2)).locate(NonGenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericResolutionIsLazyForSimpleCreation() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); new ByteBuddy() .with(TypeValidation.DISABLED) .with(MethodGraph.Empty.INSTANCE) .with(InstrumentedType.Factory.Default.FROZEN) .redefine(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator) .make(); verify(classFileLocator, times(2)).locate(NonGenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testGenericResolutionIsLazyForSimpleCreation() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); new ByteBuddy() .with(TypeValidation.DISABLED) .with(MethodGraph.Empty.INSTANCE) .with(InstrumentedType.Factory.Default.FROZEN) .redefine(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()), classFileLocator) .make(); verify(classFileLocator, times(2)).locate(GenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericSuperClassHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SampleClass.class))); verify(classFileLocator).locate(NonGenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericSuperClassNavigatedHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().getSuperClass().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperClass.class))); verify(classFileLocator).locate(NonGenericType.class.getName()); verify(classFileLocator).locate(SampleClass.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericSuperInterfaceHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getInterfaces().getOnly().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SampleInterface.class))); verify(classFileLocator).locate(NonGenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testNonGenericSuperInterfaceNavigatedHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getInterfaces().getOnly() .getInterfaces().getOnly().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperInterface.class))); verify(classFileLocator).locate(NonGenericType.class.getName()); verify(classFileLocator).locate(SampleInterface.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testGenericSuperClassHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SampleGenericClass.class))); verify(classFileLocator).locate(GenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testGenericSuperClassNavigatedHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().getSuperClass().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperClass.class))); verify(classFileLocator).locate(GenericType.class.getName()); verify(classFileLocator).locate(SampleGenericClass.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testGenericSuperInterfaceHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getInterfaces().getOnly().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SampleGenericInterface.class))); verify(classFileLocator).locate(GenericType.class.getName()); verifyNoMoreInteractions(classFileLocator); } @Test public void testGenericSuperInterfaceNavigatedHierarchyResolutionIsLazy() throws Exception { ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader()); assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getInterfaces().getOnly() .getInterfaces().getOnly().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperInterface.class))); verify(classFileLocator).locate(GenericType.class.getName()); verify(classFileLocator).locate(SampleGenericInterface.class.getName()); verifyNoMoreInteractions(classFileLocator); } private static class SuperClass { /* empty */ } private interface SuperInterface { /* empty */ } private static class SampleClass extends SuperClass { /* empty */ } private interface SampleInterface extends SuperInterface { /* empty */ } private static class NonGenericType extends SampleClass implements SampleInterface { Object foo; Object foo(Object argument) throws Exception { return argument; } } private static class SampleGenericClass<T> extends SuperClass { /* empty */ } private interface SampleGenericInterface<T> extends SuperInterface { /* empty */ } private static class GenericType<T extends Exception> extends SampleGenericClass<T> implements SampleGenericInterface<T> { T foo; T foo(T argument) throws T { return argument; } } }
apache-2.0
kbss/web-db-manager
db-manager-services-api/src/main/java/org/kbss/webdb/services/exceptions/UnauthorizedException.java
490
package org.kbss.webdb.services.exceptions; /** * @author Serhii Kryvtsov * @since 10/14/2015. */ public class UnauthorizedException extends ClientException { private static final int STATUS = 401; private static final String MESSAGE = "Unauthorized"; public UnauthorizedException() { super(MESSAGE); } public UnauthorizedException(String message) { super(message); } @Override public int getStatus() { return STATUS; } }
apache-2.0
adligo/fabricate.adligo.org
src/org/adligo/fabricate/xml/io_v1/common_v1_0/RoutineType.java
2058
// // 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: 2015.03.31 at 05:31:18 PM CDT // package org.adligo.fabricate.xml.io_v1.common_v1_0; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for routine_type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="routine_type"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://www.adligo.org/fabricate/xml/io_v1/common_v1_0.xsd}routine_params_type"&gt; * &lt;attribute name="class" type="{http://www.adligo.org/fabricate/xml/io_v1/common_v1_0.xsd}class_type" /&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "routine_type") @XmlSeeAlso({ RoutineParentType.class }) public class RoutineType extends RoutineParamsType { @XmlAttribute(name = "class") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String clazz; /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } }
apache-2.0
wingjay/jayAndroid
app/src/main/java/com/wingjay/jayandroid/MainActivity.java
7687
package com.wingjay.jayandroid; import android.content.Intent; import android.os.Bundle; import android.view.View; import butterknife.OnClick; import com.wingjay.jayandroid.abot.ABotActivity; import com.wingjay.jayandroid.animation.searchbar.LottieActivity; import com.wingjay.jayandroid.animation.searchbar.TransitionAnimationFromActivity; import com.wingjay.jayandroid.bitmap.BitmapTestingActivity; import com.wingjay.jayandroid.contentprovider.ContentResolverActivity; import com.wingjay.jayandroid.curve.CurveActivity; import com.wingjay.jayandroid.customizeview.CustomizeViewActivity; import com.wingjay.jayandroid.daggerForGlow.fakeApp.DaggerForGlowAppActivity; import com.wingjay.jayandroid.drag.DragChooseActivity; import com.wingjay.jayandroid.drawable.DrawableActivity; import com.wingjay.jayandroid.eveanimation.EveCycleViewActivity; import com.wingjay.jayandroid.eventdispatch.EventDispatchActivity; import com.wingjay.jayandroid.fab.FabActivity; import com.wingjay.jayandroid.fastblur.FastBlurActivity; import com.wingjay.jayandroid.fragmentstudy.HolderActivity; import com.wingjay.jayandroid.fulltextview.FullTextViewActivity; import com.wingjay.jayandroid.gesture.GestureActivity; import com.wingjay.jayandroid.livedata.LiveDataActivity; import com.wingjay.jayandroid.lowpoly.LowPolyActivity; import com.wingjay.jayandroid.ndkdev.NdkActivity; import com.wingjay.jayandroid.perisope.PerisopeActivity; import com.wingjay.jayandroid.qqitem.DragableActivity; import com.wingjay.jayandroid.realm.RealmIntroActivity; import com.wingjay.jayandroid.retrofitOkhttpUpgrade.RetrofitOkhttpUpgradeActivity; import com.wingjay.jayandroid.richlist.v5.RichListActivity; import com.wingjay.jayandroid.rxjava.RxJavaActivity; import com.wingjay.jayandroid.autolifecycle.AutoLifecycleActivity; import com.wingjay.jayandroid.skin.AndroidSkinLoaderDemoActivity; import com.wingjay.jayandroid.skin.JaySkinLoaderDemoActivity; import com.wingjay.jayandroid.skin.SkinActivity; import com.wingjay.jayandroid.statusbar.StatusBarActivity; import com.wingjay.jayandroid.tiktok.TikTokActivity; import com.wingjay.jayandroid.tracker.TrackerActivity; import com.wingjay.jayandroid.webview.WebViewActivity; import com.wingjay.jayandroid.weex.HelloWeexActivity; import com.wingjay.jayandroid.xiami.XiamiActivity; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.contentProvider).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ContentResolverActivity.class)); } }); findViewById(R.id.gesture).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GestureActivity.class)); } }); // Log.i(TAG, FastBlurJni.test()); } @OnClick(R.id.tik_tok) void tiktok() { startMyActivity(TikTokActivity.class); } @OnClick(R.id.tracker) void tracker() { startMyActivity(TrackerActivity.class); } @OnClick(R.id.auto_lifecycle) void autoLifecycle() { startMyActivity(AutoLifecycleActivity.class); } @OnClick(R.id.livedata) void lifecycle() { startMyActivity(LiveDataActivity.class); } @OnClick(R.id.rich_test) void richTest() { startMyActivity(RichListActivity.class); } @OnClick(R.id.xiami) void xiami() { startMyActivity(XiamiActivity.class); } @OnClick(R.id.jay_android_skin_loader) void jaySkinLoaderDemo() { startMyActivity(JaySkinLoaderDemoActivity.class); } @OnClick(R.id.android_skin_loader) void skinLoaderDemo() { startMyActivity(AndroidSkinLoaderDemoActivity.class); } @OnClick(R.id.skin) void skin() { startMyActivity(SkinActivity.class); } @OnClick(R.id.for_test) void test() { startMyActivity(ForTestActivity.class); } @OnClick(R.id.weex) void weex() { startMyActivity(HelloWeexActivity.class); } @OnClick(R.id.lottie) void lottie() { startMyActivity(LottieActivity.class); } @OnClick(R.id.eve_home_animation) void eveHomeAnimation() { startMyActivity(EveCycleViewActivity.class); // TaskStackBuilder.create(getApplicationContext()) // .addNextIntent(new Intent(this, EveCycleViewActivity.class)) // .addNextIntentWithParentStack(new Intent(this, EveHomeActivity.class)) // .startActivities(); } @OnClick(R.id.webview) void webview() { startMyActivity(WebViewActivity.class); } @OnClick(R.id.a_bot) void abot() { startMyActivity(ABotActivity.class); } @OnClick(R.id.realm) void realm() { startMyActivity(RealmIntroActivity.class); } @OnClick(R.id.fragment_holder) void holder() { startMyActivity(HolderActivity.class); } @OnClick(R.id.ndk_dev) void ndkDev() { startActivity(new Intent(MainActivity.this, NdkActivity.class)); } @OnClick(R.id.low_poly) void lowPoly() { startActivity(new Intent(MainActivity.this, LowPolyActivity.class)); } @OnClick(R.id.retrofit_upgrade) void retrofitUpgrade() { startActivity(new Intent(MainActivity.this, RetrofitOkhttpUpgradeActivity.class)); } @OnClick(R.id.bitmap_test) void bitmapTest() { startActivity(new Intent(MainActivity.this, BitmapTestingActivity.class)); } @OnClick(R.id.dagger) void dagger() { startActivity(new Intent(MainActivity.this, DaggerForGlowAppActivity.class)); } @OnClick(R.id.activity_transition) void activityTransition() { startActivity(new Intent(MainActivity.this, TransitionAnimationFromActivity.class)); } @OnClick(R.id.rxJava) void rxJava() { startActivity(new Intent(MainActivity.this, RxJavaActivity.class)); } @OnClick(R.id.drag_helper) void drag(View view) { startActivity(new Intent(MainActivity.this, DragChooseActivity.class)); } @OnClick(R.id.drag_able) void dragAble() { startActivity(new Intent(MainActivity.this, DragableActivity.class)); } @OnClick(R.id.event_dispatch) void eventDispatch() { startActivity(new Intent(MainActivity.this, EventDispatchActivity.class)); } @OnClick(R.id.full_text) void fullText() { startActivity(new Intent(MainActivity.this, FullTextViewActivity.class)); } @OnClick(R.id.drawable) void drawable() { startActivity(new Intent(MainActivity.this, DrawableActivity.class)); } @OnClick(R.id.customize_view) void customizeView() { startActivity(new Intent(MainActivity.this, CustomizeViewActivity.class)); } @OnClick(R.id.perisope_view) void perisipeView() { startActivity(new Intent(MainActivity.this, PerisopeActivity.class)); } @OnClick(R.id.curve_view) void curveView() { startActivity(new Intent(MainActivity.this, CurveActivity.class)); } @OnClick(R.id.fast_blur) void fastBlur() { startActivity(new Intent(MainActivity.this, FastBlurActivity.class)); } @OnClick(R.id.status_bar) void statusBar() { startMyActivity(StatusBarActivity.class); } @OnClick(R.id.fabMenu) void fabMenu() { startMyActivity(FabActivity.class); } private void startMyActivity(Class clz) { startActivity(new Intent(MainActivity.this, clz)); } }
apache-2.0
Iguanod/Iguanod-library
src/es/iguanod/util/tuples/BackedTuple.java
1254
/* * -------------------- DO NOT REMOVE OR MODIFY THIS HEADER -------------------- * * Copyright (C) 2014 The Iguanod Authors * * 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 should have been provided along with this file, usually * under the name "LICENSE.txt". If that is not the case 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 es.iguanod.util.tuples; /** * Interface used internally to convert tuples from one size to another. * * @author <a href="mailto:rubiof.david@gmail.com">David Rubio Fernández</a> * @since 1.0.1 * @version 1.0.1 */ interface BackedTuple{ /** * Returns the ith element of the tuple. * * @param i the number of element to be returned * * @return the requested element */ public Object get(int i); }
apache-2.0
itachi1706/DroidEggs
app/src/main/java/com/itachi1706/droideggs/REgg/EasterEgg/neko/PrefState.java
3158
/* * Copyright (C) 2020 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.itachi1706.droideggs.REgg.EasterEgg.neko; import android.content.Context; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PrefState implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String FILE_NAME = "mPrefs"; private static final String FOOD_STATE = "food"; private static final String WATER_STATE = "water"; private static final String CAT_KEY_PREFIX = "cat:"; private final Context mContext; private final SharedPreferences mPrefs; private PrefsListener mListener; public PrefState(Context context) { mContext = context; mPrefs = mContext.getSharedPreferences(FILE_NAME, 0); } // Can also be used for renaming. public void addCat(Cat cat) { mPrefs.edit() .putString(CAT_KEY_PREFIX + String.valueOf(cat.getSeed()), cat.getName()) .apply(); } public void removeCat(Cat cat) { mPrefs.edit().remove(CAT_KEY_PREFIX + String.valueOf(cat.getSeed())).apply(); } public List<Cat> getCats() { ArrayList<Cat> cats = new ArrayList<>(); Map<String, ?> map = mPrefs.getAll(); for (String key : map.keySet()) { if (key.startsWith(CAT_KEY_PREFIX)) { long seed = Long.parseLong(key.substring(CAT_KEY_PREFIX.length())); Cat cat = new Cat(mContext, seed); cat.setName(String.valueOf(map.get(key))); cats.add(cat); } } return cats; } public int getFoodState() { return mPrefs.getInt(FOOD_STATE, 0); } public void setFoodState(int foodState) { mPrefs.edit().putInt(FOOD_STATE, foodState).apply(); } public float getWaterState() { return mPrefs.getFloat(WATER_STATE, 0f); } public void setWaterState(float waterState) { mPrefs.edit().putFloat(WATER_STATE, waterState).apply(); } public void setListener(PrefsListener listener) { mListener = listener; if (mListener != null) { mPrefs.registerOnSharedPreferenceChangeListener(this); } else { mPrefs.unregisterOnSharedPreferenceChangeListener(this); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { mListener.onPrefsChanged(); } public interface PrefsListener { void onPrefsChanged(); } }
apache-2.0
qafedev/qafe-platform
qafe-business/src/test/java/test/com/qualogy/qafe/business/integration/java/spring/testclasses/MyBean2.java
930
/** * Copyright 2008-2017 Qualogy Solutions 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 test.com.qualogy.qafe.business.integration.java.spring.testclasses; public class MyBean2 { public String sayGreetings() { return saySomething("Greetings"); } public void doSomethingFunny() { System.out.println("Executing doSomethingFunny"); } public String saySomething(String s) { return s; } }
apache-2.0
lgoldstein/communitychest
apps/common/src/test/java/net/community/apps/common/test/table/TestTable.java
780
/* * */ package net.community.apps.common.test.table; import net.community.chest.ui.helpers.table.EnumColumnTypedTable; /** * <P>Copyright GPLv2</P> * * @author Lyor G. * @since Mar 22, 2009 8:44:35 AM */ public class TestTable extends EnumColumnTypedTable<TestTableColumnType,TestTableRowData> { /** * */ private static final long serialVersionUID = 6436942345036710208L; public TestTable (TestTableModel m) { super(m); } public TestTable () { this(new TestTableModel()); } /* * @see net.community.chest.ui.helpers.table.EnumColumnTypedTable#getTypedModel() */ @Override public TestTableModel getTypedModel () { return TestTableModel.class.cast(super.getTypedModel()); } }
apache-2.0
AfricaRegex/SjcProduct
SjcProject/src/com/sjc/cc/cloud/cluster/action/ClusterAction.java
3580
package com.sjc.cc.cloud.cluster.action; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; import com.sjc.cc.base.action.BaseBusinessAction; import com.sjc.cc.cloud.cluster.service.ClusterMgtService; import com.sjc.cc.cloud.pod.service.PodMgtService; import com.sjc.cc.cloud.zone.service.ZoneMgtService; import com.sjc.cc.pf.util.JsonResponseUtil; public class ClusterAction extends BaseBusinessAction { ClusterMgtService clusterMgtService; ZoneMgtService zoneMgtService; PodMgtService podMgtService; public PodMgtService getPodMgtService() { return podMgtService; } public void setPodMgtService(PodMgtService podMgtService) { this.podMgtService = podMgtService; } public ZoneMgtService getZoneMgtService() { return zoneMgtService; } public void setZoneMgtService(ZoneMgtService zoneMgtService) { this.zoneMgtService = zoneMgtService; } public ClusterMgtService getClusterMgtService() { return clusterMgtService; } public void setClusterMgtService(ClusterMgtService clusterMgtService) { this.clusterMgtService = clusterMgtService; } public String pageonload() throws Exception { return "pageonload"; } public void listCluster() { // List<ClusterVo> list = clusterMgtService.listClusters(); // JSONArray jsonArray = JSONArray.fromObject(list); // JsonResponseUtil.writeJsonArray(jsonArray); } public void deleteCluster() { // HttpServletRequest request = ServletActionContext.getRequest(); // String id = request.getParameter("id"); // SimpleRespVo obj = null; // try { // obj = clusterMgtService.deleteCluster(id); // } catch (Exception e) { // e.printStackTrace(); // } // Map<String,String> map = new HashMap<String,String>(); // if(obj != null){ // map.put("flag", obj.getSuccess()); // } // JSONObject jsonObj = JSONObject.fromObject(map); // JsonResponseUtil.writeJsonObject(jsonObj); } public void listZones() { // List<ZoneVo> list = zoneMgtService.listZones(); // JSONArray jsonArray = JSONArray.fromObject(list); // JsonResponseUtil.writeJsonArray(jsonArray); } public void listPods() { // List<PodVo> list = podMgtService.listPods(); // JSONArray jsonArray = JSONArray.fromObject(list); // JsonResponseUtil.writeJsonArray(jsonArray); } public void addCluster() { // HttpServletRequest request = ServletActionContext.getRequest(); // String zoneid = request.getParameter("zoneid"); // String hypervisor = request.getParameter("hypervisor"); // String clustername = request.getParameter("clustername"); // String podid = request.getParameter("podid"); // String vsmipaddress = request.getParameter("vsmipaddress"); // ClusterVo obj = null; // try { // obj = clusterMgtService.addCluster(zoneid, hypervisor, clustername, // podid, vsmipaddress); // } catch (Exception e) { // e.printStackTrace(); // } // JSONObject jsonObj = JSONObject.fromObject(obj); // JsonResponseUtil.writeJsonObject(jsonObj); } }
apache-2.0
schnurlei/jdynameta
jdy/jdy.model.persistence/src/main/java/de/jdynameta/application/WorkflowException.java
1064
/** * * Copyright 2011 (C) Rainer Schneider,Roggenburg <schnurlei@googlemail.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 de.jdynameta.application; @SuppressWarnings("serial") public class WorkflowException extends Exception { public WorkflowException(String message, Throwable cause) { super(message, cause); } public WorkflowException(String message) { super(message); } public WorkflowException(Throwable cause) { super(cause); } }
apache-2.0
spring-projects/spring-framework
spring-web/src/main/java/org/springframework/web/util/UriComponents.java
11055
/* * Copyright 2002-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.web.util; import java.io.Serializable; import java.net.URI; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MultiValueMap; /** * Represents an immutable collection of URI components, mapping component type to * String values. Contains convenience getters for all components. Effectively similar * to {@link java.net.URI}, but with more powerful encoding options and support for * URI template variables. * * @author Arjen Poutsma * @author Juergen Hoeller * @author Rossen Stoyanchev * @since 3.1 * @see UriComponentsBuilder */ @SuppressWarnings("serial") public abstract class UriComponents implements Serializable { /** Captures URI template variable names. */ private static final Pattern NAMES_PATTERN = Pattern.compile("\\{([^/]+?)\\}"); @Nullable private final String scheme; @Nullable private final String fragment; protected UriComponents(@Nullable String scheme, @Nullable String fragment) { this.scheme = scheme; this.fragment = fragment; } // Component getters /** * Return the scheme. Can be {@code null}. */ @Nullable public final String getScheme() { return this.scheme; } /** * Return the fragment. Can be {@code null}. */ @Nullable public final String getFragment() { return this.fragment; } /** * Return the scheme specific part. Can be {@code null}. */ @Nullable public abstract String getSchemeSpecificPart(); /** * Return the user info. Can be {@code null}. */ @Nullable public abstract String getUserInfo(); /** * Return the host. Can be {@code null}. */ @Nullable public abstract String getHost(); /** * Return the port. {@code -1} if no port has been set. */ public abstract int getPort(); /** * Return the path. Can be {@code null}. */ @Nullable public abstract String getPath(); /** * Return the list of path segments. Empty if no path has been set. */ public abstract List<String> getPathSegments(); /** * Return the query. Can be {@code null}. */ @Nullable public abstract String getQuery(); /** * Return the map of query parameters. Empty if no query has been set. */ public abstract MultiValueMap<String, String> getQueryParams(); /** * Invoke this <em>after</em> expanding URI variables to encode the * resulting URI component values. * <p>In comparison to {@link UriComponentsBuilder#encode()}, this method * <em>only</em> replaces non-ASCII and illegal (within a given URI * component type) characters, but not characters with reserved meaning. * For most cases, {@link UriComponentsBuilder#encode()} is more likely * to give the expected result. * @see UriComponentsBuilder#encode() */ public final UriComponents encode() { return encode(StandardCharsets.UTF_8); } /** * A variant of {@link #encode()} with a charset other than "UTF-8". * @param charset the charset to use for encoding * @see UriComponentsBuilder#encode(Charset) */ public abstract UriComponents encode(Charset charset); /** * Replace all URI template variables with the values from a given map. * <p>The given map keys represent variable names; the corresponding values * represent variable values. The order of variables is not significant. * @param uriVariables the map of URI variables * @return the expanded URI components */ public final UriComponents expand(Map<String, ?> uriVariables) { Assert.notNull(uriVariables, "'uriVariables' must not be null"); return expandInternal(new MapTemplateVariables(uriVariables)); } /** * Replace all URI template variables with the values from a given array. * <p>The given array represents variable values. The order of variables is significant. * @param uriVariableValues the URI variable values * @return the expanded URI components */ public final UriComponents expand(Object... uriVariableValues) { Assert.notNull(uriVariableValues, "'uriVariableValues' must not be null"); return expandInternal(new VarArgsTemplateVariables(uriVariableValues)); } /** * Replace all URI template variables with the values from the given * {@link UriTemplateVariables}. * @param uriVariables the URI template values * @return the expanded URI components */ public final UriComponents expand(UriTemplateVariables uriVariables) { Assert.notNull(uriVariables, "'uriVariables' must not be null"); return expandInternal(uriVariables); } /** * Replace all URI template variables with the values from the given {@link * UriTemplateVariables}. * @param uriVariables the URI template values * @return the expanded URI components */ abstract UriComponents expandInternal(UriTemplateVariables uriVariables); /** * Normalize the path removing sequences like "path/..". Note that * normalization is applied to the full path, and not to individual path * segments. * @see org.springframework.util.StringUtils#cleanPath(String) */ public abstract UriComponents normalize(); /** * Concatenate all URI components to return the fully formed URI String. * <p>This method amounts to simple String concatenation of the current * URI component values and as such the result may contain illegal URI * characters, for example if URI variables have not been expanded or if * encoding has not been applied via {@link UriComponentsBuilder#encode()} * or {@link #encode()}. */ public abstract String toUriString(); /** * Create a {@link URI} from this instance as follows: * <p>If the current instance is {@link #encode() encoded}, form the full * URI String via {@link #toUriString()}, and then pass it to the single * argument {@link URI} constructor which preserves percent encoding. * <p>If not yet encoded, pass individual URI component values to the * multi-argument {@link URI} constructor which quotes illegal characters * that cannot appear in their respective URI component. */ public abstract URI toUri(); /** * A simple pass-through to {@link #toUriString()}. */ @Override public final String toString() { return toUriString(); } /** * Set all components of the given UriComponentsBuilder. * @since 4.2 */ protected abstract void copyToUriComponentsBuilder(UriComponentsBuilder builder); // Static expansion helpers @Nullable static String expandUriComponent(@Nullable String source, UriTemplateVariables uriVariables) { return expandUriComponent(source, uriVariables, null); } @Nullable static String expandUriComponent(@Nullable String source, UriTemplateVariables uriVariables, @Nullable UnaryOperator<String> encoder) { if (source == null) { return null; } if (source.indexOf('{') == -1) { return source; } if (source.indexOf(':') != -1) { source = sanitizeSource(source); } Matcher matcher = NAMES_PATTERN.matcher(source); StringBuilder sb = new StringBuilder(); while (matcher.find()) { String match = matcher.group(1); String varName = getVariableName(match); Object varValue = uriVariables.getValue(varName); if (UriTemplateVariables.SKIP_VALUE.equals(varValue)) { continue; } String formatted = getVariableValueAsString(varValue); formatted = encoder != null ? encoder.apply(formatted) : Matcher.quoteReplacement(formatted); matcher.appendReplacement(sb, formatted); } matcher.appendTail(sb); return sb.toString(); } /** * Remove nested "{}" such as in URI vars with regular expressions. */ private static String sanitizeSource(String source) { int level = 0; int lastCharIndex = 0; char[] chars = new char[source.length()]; for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); if (c == '{') { level++; } if (c == '}') { level--; } if (level > 1 || (level == 1 && c == '}')) { continue; } chars[lastCharIndex++] = c; } return new String(chars, 0, lastCharIndex); } private static String getVariableName(String match) { int colonIdx = match.indexOf(':'); return (colonIdx != -1 ? match.substring(0, colonIdx) : match); } private static String getVariableValueAsString(@Nullable Object variableValue) { return (variableValue != null ? variableValue.toString() : ""); } /** * Defines the contract for URI Template variables. * @see HierarchicalUriComponents#expand */ public interface UriTemplateVariables { /** * Constant for a value that indicates a URI variable name should be * ignored and left as is. This is useful for partial expanding of some * but not all URI variables. */ Object SKIP_VALUE = UriTemplateVariables.class; /** * Get the value for the given URI variable name. * If the value is {@code null}, an empty String is expanded. * If the value is {@link #SKIP_VALUE}, the URI variable is not expanded. * @param name the variable name * @return the variable value, possibly {@code null} or {@link #SKIP_VALUE} */ @Nullable Object getValue(@Nullable String name); } /** * URI template variables backed by a map. */ private static class MapTemplateVariables implements UriTemplateVariables { private final Map<String, ?> uriVariables; public MapTemplateVariables(Map<String, ?> uriVariables) { this.uriVariables = uriVariables; } @Override @Nullable public Object getValue(@Nullable String name) { if (!this.uriVariables.containsKey(name)) { throw new IllegalArgumentException("Map has no value for '" + name + "'"); } return this.uriVariables.get(name); } } /** * URI template variables backed by a variable argument array. */ private static class VarArgsTemplateVariables implements UriTemplateVariables { private final Iterator<Object> valueIterator; public VarArgsTemplateVariables(Object... uriVariableValues) { this.valueIterator = Arrays.asList(uriVariableValues).iterator(); } @Override @Nullable public Object getValue(@Nullable String name) { if (!this.valueIterator.hasNext()) { throw new IllegalArgumentException("Not enough variable values available to expand '" + name + "'"); } return this.valueIterator.next(); } } }
apache-2.0
kantega/Security-api-implementation
ldap/src/main/java/no/kantega/security/api/impl/ldap/CloseableLdapConnection.java
692
package no.kantega.security.api.impl.ldap; import com.novell.ldap.LDAPConnection; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPSocketFactory; import java.io.Closeable; import java.io.IOException; public class CloseableLdapConnection extends LDAPConnection implements Closeable { public CloseableLdapConnection() { super(); } public CloseableLdapConnection(LDAPSocketFactory ldapSocketFactory) { super(ldapSocketFactory); } @Override public void close() throws IOException { try { disconnect(); } catch (LDAPException e) { throw new RuntimeException(e.getMessage(), e); } } }
apache-2.0
grasscrm/gdesigner
editor/server/src/de/hpi/bpel4chor/model/activities/FoldedTask.java
1053
package de.hpi.bpel4chor.model.activities; import de.hpi.bpel4chor.model.Container; import org.w3c.dom.Element; import de.hpi.bpel4chor.util.Output; /** * A folded task is generated during the transformation and * replaces a pattern in the sequence flow. The task holds * the bpel mapping of the pattern. */ public class FoldedTask extends Task { private Element bpelElement; /** * Constructor. Initializes the event with the bpel mapping and generates * a unique id * * @param element The element that holds the bpel mapping * represented by this task. * @param parentContainer The process or sub-process the task is located in. * @param output The output to print errors to. */ public FoldedTask(Element element, Container parentContainer, Output output) { super(true, output); this.bpelElement = element; setParentContainer(parentContainer); } /** * @return The bpel element that holds the bpel * mapping represented by this task. */ public Element getBPELElement() { return this.bpelElement; } }
apache-2.0
AfricaRegex/SjcProduct
SjcProject/src/com/sjc/cc/back/home/vo/TaskStatistics.java
1613
package com.sjc.cc.back.home.vo; /** * 创建于 2013-6-14 * <p> * 标题: 开发测试云_[系统管理]_[后台首页] * </p> * <p> * 描述: [任务统计VO类] * </p> * <p> * 公司: 上海圣荷塞信息技术有限公司 * </p> * <p> * 部门: 云计算开发部 * </p> * * @author 辛石磊 stone.xin@sjcloud.cn * @version 1.0 */ public class TaskStatistics { /** 今日新增任务 */ private int todayNewTask; /** 未处理任务 */ private int unprocessedTask; /** 已完成任务 */ private int completedTask; /** 退回的任务 */ private int returnedTask; /** 总任务 */ private int totalTask; public int getTodayNewTask() { return todayNewTask; } public void setTodayNewTask(int todayNewTask) { this.todayNewTask = todayNewTask; } public int getUnprocessedTask() { return unprocessedTask; } public void setUnprocessedTask(int unprocessedTask) { this.unprocessedTask = unprocessedTask; } public int getCompletedTask() { return completedTask; } public void setCompletedTask(int completedTask) { this.completedTask = completedTask; } public int getReturnedTask() { return returnedTask; } public void setReturnedTask(int returnedTask) { this.returnedTask = returnedTask; } public int getTotalTask() { return totalTask; } public void setTotalTask(int totalTask) { this.totalTask = totalTask; } }
apache-2.0
covito/legend-shop
src/main/java/com/legendshop/core/helper/PropertiesUtil.java
7473
package com.legendshop.core.helper; import com.legendshop.core.constant.ConfigPropertiesEnum; import com.legendshop.core.constant.SysParameterEnum; import com.legendshop.core.constant.SysParameterTypeEnum; import com.legendshop.model.entity.SystemParameter; import com.legendshop.util.AppUtils; import com.legendshop.util.EnvironmentConfig; import com.legendshop.util.SystemUtil; import com.legendshop.util.TimerUtil; import com.legendshop.util.converter.ByteConverter; import com.legendshop.util.des.DES2; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PropertiesUtil extends SystemUtil { private static Map<String, Object> configMap = new HashMap<String, Object>(); public static String getSmallFilesAbsolutePath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.SMALL_PIC_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "smallImage"; return str; } public static String getBigFilesAbsolutePath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.BIG_PIC_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "bigImage"; return str; } public static String getBackupFilesAbsolutePath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.BACKUP_PIC_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "backupImage"; return str; } public static String getHtmlPath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.HTML_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "html/"; return str; } public static String getSmallImagePathPrefix() { return EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", "IMAGES_PATH_PREFIX"); } public static String getPhotoPathPrefix() { return EnvironmentConfig.getInstance().getPropertyValue( "fckeditor.properties", "connector.userFilesPath"); } public static String getDomainName() { return EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", "DOMAIN_NAME"); } public static String getDownloadFilePath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.DOWNLOAD_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "WEB-INF/download"; return str; } public static String getLucenePath() { String str = EnvironmentConfig.getInstance().getPropertyValue( "config/common.properties", ConfigPropertiesEnum.LUCENE_PATH.name()); if (AppUtils.isBlank(str)) str = getSystemRealPath() + "WEB-INF/luceneIndex"; return str; } public static String getProperties(String paramString1, String paramString2) { return EnvironmentConfig.getInstance().getPropertyValue(paramString1, paramString2); } public static String getGlobalProperties(String paramString) { return EnvironmentConfig.getInstance().getPropertyValue( "config/global.properties", paramString); } public static boolean isSystemInstalled() { return "INSTALLED".equals(getProperties("config/common.properties", ConfigPropertiesEnum.INSTALLED.name())); } public static boolean isSystemInDebugMode() { return "true".equals(getProperties("config/global.properties", ConfigPropertiesEnum.SQL_DEBUG_MODE.name())); } public static String getCurrencyPattern() { return EnvironmentConfig.getInstance().getPropertyValue( "config/global.properties", ConfigPropertiesEnum.CURRENCY_PATTERN.name()); } public static void writeProperties(String paramString, Map<String, String> paramMap) { EnvironmentConfig.getInstance().writeProperties(paramString, paramMap); } public static <T> T getObject(SysParameterEnum paramSysParameterEnum, Class<T> paramClass) { return (T)configMap.get(paramSysParameterEnum.name()); } public static Boolean getBooleanObject(String paramString) { return ((Boolean) configMap.get(paramString)); } public static void setObject(SysParameterEnum paramSysParameterEnum, Object paramObject) { if (paramObject.getClass() != paramSysParameterEnum.getClazz()) throw new RuntimeException("Required Type = " + paramSysParameterEnum.getClazz() + ", but Actual Type = " + paramObject.getClass()); configMap.put(paramSysParameterEnum.name(), paramObject); } public static void setParameter(SystemParameter parameter) { String str1 = parameter.getType(); if (SysParameterTypeEnum.Integer.name().equalsIgnoreCase(str1)) { try { configMap.put(parameter.getName(), Integer.valueOf(parameter.getValue())); } catch (Exception localException1) { configMap.put(parameter.getName(), Integer.valueOf(parameter.getOptional())); } } else if (SysParameterTypeEnum.Boolean.name().equalsIgnoreCase(str1)) { configMap.put(parameter.getName(), Boolean.valueOf(parameter.getValue())); } else if (SysParameterTypeEnum.Long.name().equalsIgnoreCase(str1)) { try { configMap.put(parameter.getName(), Long.valueOf(parameter.getValue())); } catch (Exception localException2) { configMap.put(parameter.getName(), Integer.valueOf(parameter.getOptional())); } } else if (SysParameterTypeEnum.List.name().equalsIgnoreCase(str1)) { ArrayList localArrayList = new ArrayList(); if (AppUtils.isNotBlank(parameter.getValue())) { String[] arrayOfString1 = parameter.getValue() .split(","); String[] arrayOfString2 = arrayOfString1; int i = arrayOfString2.length; for (int j = 0; j < i; ++j) { String str2 = arrayOfString2[j]; localArrayList.add(str2); } } configMap.put(parameter.getName(), localArrayList); } else { configMap.put(parameter.getName(), parameter.getValue()); } } public static String getDefaultShopName() { return ((String) getObject(SysParameterEnum.DEFAULT_SHOP, String.class)); } public static boolean isDefaultShopName(String paramString) { return ((String) getObject(SysParameterEnum.DEFAULT_SHOP, String.class)) .equals(paramString); } public static boolean isInDefaultShop(String paramString) { return ((String) getObject(SysParameterEnum.DEFAULT_SHOP, String.class)) .equals(paramString); } public static String getLegendShopSystemId() { return getProperties("config/common.properties", ConfigPropertiesEnum.LEGENDSHOP_SYSTEM_ID.name()); } public static void changeLegendShopSystemId() { DES2 localDES2 = new DES2(); HashMap localHashMap = new HashMap(); String str1 = TimerUtil.getStrDate(); String str2 = ByteConverter.encode(localDES2.byteToString(localDES2 .createEncryptor(str1))); localHashMap .put(ConfigPropertiesEnum.LEGENDSHOP_SYSTEM_ID.name(), str2); String str3 = getSystemRealPath() + "WEB-INF/classes/config/common.properties"; writeProperties(str3, localHashMap); } public static boolean sendMail() { return ((Boolean) getObject(SysParameterEnum.SEND_MAIL, Boolean.class)) .booleanValue(); } }
apache-2.0
flowing/flowing-retail-concept-java
src/main/java/io/flowing/retail/concept/domain/Shop.java
542
package io.flowing.retail.concept.domain; import java.util.UUID; import org.camunda.bpm.engine.variable.Variables; import io.flowing.retail.concept.infrastructure.Bus; import io.flowing.retail.concept.infrastructure.Event; public class Shop { public static void init() { } public void checkout(boolean vip) { String orderId = UUID.randomUUID().toString(); System.out.println("place order " + orderId); Bus.send( new Event("OrderPlaced", Variables.putValue("orderId", orderId).putValue("vip", vip))); } }
apache-2.0
chrisdennis/terracotta-platform
management/management-registry/src/main/java/org/terracotta/management/registry/AbstractManagementProvider.java
6753
/* * Copyright Terracotta, 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 org.terracotta.management.registry; import org.terracotta.management.model.call.Parameter; import org.terracotta.management.model.capabilities.Capability; import org.terracotta.management.model.capabilities.DefaultCapability; import org.terracotta.management.model.capabilities.context.CapabilityContext; import org.terracotta.management.model.capabilities.descriptors.Descriptor; import org.terracotta.management.model.capabilities.descriptors.StatisticDescriptor; import org.terracotta.management.model.context.Context; import org.terracotta.management.model.stats.Statistic; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; /** * @author Mathieu Carbou */ public abstract class AbstractManagementProvider<T> implements ManagementProvider<T> { protected static final Comparator<StatisticDescriptor> STATISTIC_DESCRIPTOR_COMPARATOR = new Comparator<StatisticDescriptor>() { @Override public int compare(StatisticDescriptor o1, StatisticDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }; private final Queue<ExposedObject<T>> exposedObjects = new ConcurrentLinkedQueue<ExposedObject<T>>(); private final String capabilityName; private final Class<? extends T> managedType; private final CapabilityContext capabilityContext; public AbstractManagementProvider(Class<? extends T> managedType) { this.managedType = managedType; this.capabilityName = buildCapabilityName(); this.capabilityContext = buildCapabilityContext(); } @Override public Class<? extends T> getManagedType() { return managedType; } @Override public String getCapabilityName() { return capabilityName; } @Override public CapabilityContext getCapabilityContext() { return capabilityContext; } @Override public Capability getCapability() { return new DefaultCapability(getCapabilityName(), getCapabilityContext(), getDescriptors()); } @Override public void register(T managedObject) { ExposedObject<T> exposedObject = wrap(managedObject); this.exposedObjects.add(exposedObject); } @Override public void unregister(T managedObject) { for (ExposedObject<T> exposedObject : exposedObjects) { if (exposedObject.getTarget().equals(managedObject)) { if (this.exposedObjects.remove(exposedObject)) { dispose(exposedObject); return; } } } } @Override public void close() { while (!exposedObjects.isEmpty()) { dispose(exposedObjects.poll()); } } @Override public boolean supports(Context context) { return findExposedObject(context) != null; } @Override public Map<String, Statistic<? extends Serializable>> collectStatistics(Context context, Collection<String> statisticNames, long since) { throw new UnsupportedOperationException("Not a statistics provider : " + getCapabilityName()); } @Override public void callAction(Context context, String methodName, Parameter... parameters) throws ExecutionException { callAction(context, methodName, Object.class, parameters); } @Override public <V> V callAction(Context context, String methodName, Class<V> returnType, Parameter... parameters) throws ExecutionException { throw new UnsupportedOperationException("Not an action provider : " + getCapabilityName()); } @SuppressWarnings("unchecked") @Override public Collection<? extends Descriptor> getDescriptors() { // LinkedHashSet to keep ordering because these objects end up in an immutable // topology so this is easier for testing to compare with json payloads Collection<Descriptor> capabilities = new LinkedHashSet<Descriptor>(); for (ExposedObject<?> o : exposedObjects) { capabilities.addAll(((ExposedObject<T>) o).getDescriptors()); } return capabilities; } protected String buildCapabilityName() { Named named = getClass().getAnnotation(Named.class); return named == null ? getClass().getSimpleName() : named.value(); } // first try to find annotation on managedType, which might not be there, in this case tries to find from this subclass protected CapabilityContext buildCapabilityContext() { Collection<CapabilityContext.Attribute> attrs = new ArrayList<CapabilityContext.Attribute>(); RequiredContext requiredContext = getManagedType().getAnnotation(RequiredContext.class); if (requiredContext == null) { requiredContext = getClass().getAnnotation(RequiredContext.class); } if (requiredContext == null) { throw new IllegalStateException("@RequiredContext not found on " + getManagedType().getName() + " or " + getClass().getName()); } for (Named n : requiredContext.value()) { attrs.add(new CapabilityContext.Attribute(n.value(), true)); } return new CapabilityContext(attrs); } protected void dispose(ExposedObject<T> exposedObject) { } @Override public Collection<ExposedObject<T>> getExposedObjects() { return exposedObjects; } protected abstract ExposedObject<T> wrap(T managedObject); protected ExposedObject<T> findExposedObject(Context context) { if (!contextValid(context)) { return null; } for (ExposedObject<T> exposedObject : exposedObjects) { if (context.contains(exposedObject.getContext())) { return exposedObject; } } return null; } @Override public ExposedObject<T> findExposedObject(T managedObject) { for (ExposedObject<T> exposed : exposedObjects) { if (exposed.getTarget().equals(managedObject)) { return exposed; } } return null; } private boolean contextValid(Context context) { if (context == null) { return false; } for (CapabilityContext.Attribute attribute : getCapabilityContext().getAttributes()) { if (context.get(attribute.getName()) == null) { return false; } } return true; } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201311/ActivatePlacements.java
904
package com.google.api.ads.dfp.jaxws.v201311; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * The action used for activating {@link Placement} objects. * * * <p>Java class for ActivatePlacements complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActivatePlacements"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201311}PlacementAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivatePlacements") public class ActivatePlacements extends PlacementAction { }
apache-2.0
mdanielwork/intellij-community
plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ByteCodeViewerManager.java
8077
/* * Copyright 2000-2016 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.byteCodeViewer; import com.intellij.codeInsight.documentation.DockablePopupManager; import com.intellij.openapi.compiler.ex.CompilerPathsEx; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.presentation.java.SymbolPresentationUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.content.Content; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.org.objectweb.asm.ClassReader; import org.jetbrains.org.objectweb.asm.util.Textifier; import org.jetbrains.org.objectweb.asm.util.TraceClassVisitor; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * @author anna */ public class ByteCodeViewerManager extends DockablePopupManager<ByteCodeViewerComponent> { private static final ExtensionPointName<ClassSearcher> CLASS_SEARCHER_EP = ExtensionPointName.create("ByteCodeViewer.classSearcher"); private static final Logger LOG = Logger.getInstance(ByteCodeViewerManager.class); private static final String TOOLWINDOW_ID = "Byte Code Viewer"; private static final String SHOW_BYTECODE_IN_TOOL_WINDOW = "BYTE_CODE_TOOL_WINDOW"; private static final String BYTECODE_AUTO_UPDATE_ENABLED = "BYTE_CODE_AUTO_UPDATE_ENABLED"; public static ByteCodeViewerManager getInstance(Project project) { return ServiceManager.getService(project, ByteCodeViewerManager.class); } public ByteCodeViewerManager(Project project) { super(project); } @Override public String getShowInToolWindowProperty() { return SHOW_BYTECODE_IN_TOOL_WINDOW; } @Override public String getAutoUpdateEnabledProperty() { return BYTECODE_AUTO_UPDATE_ENABLED; } @Override protected String getToolwindowId() { return TOOLWINDOW_ID; } @Override protected String getAutoUpdateTitle() { return "Auto Show Bytecode for Selected Element"; } @Override protected String getAutoUpdateDescription() { return "Show bytecode for current element automatically"; } @Override protected String getRestorePopupDescription() { return "Restore bytecode popup behavior"; } @Override protected ByteCodeViewerComponent createComponent() { return new ByteCodeViewerComponent(myProject); } @Override @Nullable protected String getTitle(PsiElement element) { PsiClass aClass = getContainingClass(element); if (aClass == null) return null; return SymbolPresentationUtil.getSymbolPresentableText(aClass); } private void updateByteCode(PsiElement element, ByteCodeViewerComponent component, Content content) { updateByteCode(element, component, content, getByteCode(element)); } public void updateByteCode(PsiElement element, ByteCodeViewerComponent component, Content content, final String byteCode) { if (!StringUtil.isEmpty(byteCode)) { component.setText(byteCode, element); } else { PsiElement presentableElement = getContainingClass(element); if (presentableElement == null) { presentableElement = element.getContainingFile(); if (presentableElement == null && element instanceof PsiNamedElement) { presentableElement = element; } if (presentableElement == null) { component.setText("No bytecode found"); return; } } component.setText("No bytecode found for " + SymbolPresentationUtil.getSymbolPresentableText(presentableElement)); } content.setDisplayName(getTitle(element)); } @Override protected void doUpdateComponent(PsiElement element, PsiElement originalElement, ByteCodeViewerComponent component) { final Content content = myToolWindow.getContentManager().getSelectedContent(); if (content != null && element != null) { updateByteCode(element, component, content); } } @Override protected void doUpdateComponent(Editor editor, PsiFile psiFile) { final Content content = myToolWindow.getContentManager().getSelectedContent(); if (content != null) { final ByteCodeViewerComponent component = (ByteCodeViewerComponent)content.getComponent(); PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (element != null) { updateByteCode(element, component, content); } } } @Override protected void doUpdateComponent(@NotNull PsiElement element) { doUpdateComponent(element, getByteCode(element)); } protected void doUpdateComponent(@NotNull PsiElement element, final String newText) { final Content content = myToolWindow.getContentManager().getSelectedContent(); if (content != null) { updateByteCode(element, (ByteCodeViewerComponent)content.getComponent(), content, newText); } } @Nullable public static String getByteCode(@NotNull PsiElement psiElement) { PsiClass containingClass = getContainingClass(psiElement); //todo show popup if (containingClass == null) return null; CompilerPathsEx.ClassFileDescriptor file = CompilerPathsEx.findClassFileInOutput(containingClass); if (file != null) { try { return processClassFile(file.loadFileBytes()); } catch (IOException e) { LOG.error(e); } } return null; } private static String processClassFile(byte[] bytes) { final ClassReader classReader = new ClassReader(bytes); final StringWriter writer = new StringWriter(); final PrintWriter printWriter = new PrintWriter(writer); try { classReader.accept(new TraceClassVisitor(null, new Textifier(), printWriter), 0); } finally { printWriter.close(); } return writer.toString(); } public static PsiClass getContainingClass(PsiElement psiElement) { for (ClassSearcher searcher : CLASS_SEARCHER_EP.getExtensions()) { PsiClass aClass = searcher.findClass(psiElement); if (aClass != null) { return aClass; } } return findClass(psiElement); } public static PsiClass findClass(@NotNull PsiElement psiElement) { PsiClass containingClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class, false); while (containingClass instanceof PsiTypeParameter) { containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class); } if (containingClass == null) { PsiFile containingFile = psiElement.getContainingFile(); if (containingFile instanceof PsiClassOwner) { PsiClass[] classes = ((PsiClassOwner)containingFile).getClasses(); if (classes.length == 1) return classes[0]; TextRange textRange = psiElement.getTextRange(); if (textRange != null) { for (PsiClass aClass : classes) { PsiElement navigationElement = aClass.getNavigationElement(); TextRange classRange = navigationElement != null ? navigationElement.getTextRange() : null; if (classRange != null && classRange.contains(textRange)) return aClass; } } } return null; } return containingClass; } }
apache-2.0
skoulouzis/lobcder
lobcder-master/src/main/java/nl/uva/cs/lobcder/webDav/resources/WebDataResource.java
51325
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder.webDav.resources; import io.milton.common.Path; import io.milton.http.*; import static io.milton.http.Request.Method.GET; import static io.milton.http.Request.Method.POST; import static io.milton.http.Request.Method.PUT; import io.milton.http.exceptions.BadRequestException; import io.milton.http.exceptions.LockedException; import io.milton.http.exceptions.NotAuthorizedException; import io.milton.http.exceptions.PreConditionFailedException; import io.milton.http.values.HrefList; import io.milton.principal.DavPrincipals; import io.milton.principal.Principal; import io.milton.property.PropertySource; import io.milton.resource.*; import nl.uva.cs.lobcder.auth.AuthI; import nl.uva.cs.lobcder.auth.MyPrincipal; import nl.uva.cs.lobcder.auth.Permissions; import nl.uva.cs.lobcder.catalogue.JDBCatalogue; import nl.uva.cs.lobcder.resources.*; import nl.uva.cs.lobcder.util.Constants; import nl.uva.cs.lobcder.util.DesEncrypter; import javax.annotation.Nonnull; import javax.xml.namespace.QName; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.*; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import nl.uva.cs.lobcder.replication.policy.ReplicationPolicy; import nl.uva.cs.lobcder.util.PropertiesHelper; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; /** * @author S. Koulouzis */ public class WebDataResource implements PropFindableResource, Resource, AccessControlledResource, MultiNamespaceCustomPropertyResource, LockableResource { private final LogicalData logicalData; private final JDBCatalogue catalogue; private final Path path; protected final List<AuthI> authList; // protected final AuthI auth2; private static final ThreadLocal<MyPrincipal> principalHolder = new ThreadLocal<>(); protected String fromAddress; protected Map<String, String> mimeTypeMap = new HashMap<>(); private static boolean redirectPosts = false; public WebDataResource(@Nonnull LogicalData logicalData, Path path, @Nonnull JDBCatalogue catalogue, @Nonnull List<AuthI> authList) { this.authList = authList; // this.auth2 = auth2; this.logicalData = logicalData; this.catalogue = catalogue; this.path = path; mimeTypeMap.put("mp4", "video/mp4"); mimeTypeMap.put("pdf", "application/pdf"); mimeTypeMap.put("tex", "application/x-tex"); mimeTypeMap.put("log", "text/plain"); mimeTypeMap.put("png", "image/png"); mimeTypeMap.put("aux", "text/plain"); mimeTypeMap.put("bbl", "text/plain"); mimeTypeMap.put("blg", "text/plain"); try { redirectPosts = PropertiesHelper.doRedirectPosts(); } catch (IOException ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); } } @Override public Date getCreateDate() { return new Date(getLogicalData().getCreateDate()); } @Override public String getUniqueId() { return String.valueOf(getLogicalData().getUid()); } @Override public String getName() { return getLogicalData().getName(); } @Override public Object authenticate(String user, String password) { String token = password; MyPrincipal principal = null; for (AuthI a : authList) { principal = a.checkToken(user, token); if (principal != null) { break; } } // if (auth2 != null) { // principal = auth2.checkToken(token); // } // if (principal == null) { // principal = auth1.checkToken(token); // } if (principal != null) { principalHolder.set(principal); // Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "getUserId: {0}", principal.getUserId()); // Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "getRolesStr: {0}", principal.getRolesStr()); String msg = "From: " + fromAddress + " user: " + principal.getUserId() + " password: XXXX"; Logger.getLogger(WebDataResource.class.getName()).log(Level.INFO, msg); } try { getCatalogue().updateAccessTime(getLogicalData().getUid()); } catch (SQLException ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); } return principal; } MyPrincipal getPrincipal() { return principalHolder.get(); } protected Permissions getPermissions() throws SQLException { return getCatalogue().getPermissions(getLogicalData().getUid(), getLogicalData().getOwner()); } @Override public boolean authorise(Request request, Request.Method method, Auth auth) { try { if (auth == null) { return false; } fromAddress = request.getFromAddress(); String msg = "From: " + fromAddress + " User: " + getPrincipal().getUserId() + " Method: " + method; Logger.getLogger(WebDataResource.class.getName()).log(Level.INFO, msg); LogicalData parentLD; Permissions p; switch (method) { case ACL: return getPrincipal().canWrite(getPermissions()); case HEAD: return true; case PROPFIND: return getPrincipal().canRead(getPermissions()); case PROPPATCH: return getPrincipal().canWrite(getPermissions()); case MKCALENDAR: return false; case COPY: return getPrincipal().canRead(getPermissions()); case MOVE: return true; case LOCK: return getPrincipal().canWrite(getPermissions()); case UNLOCK: return getPrincipal().canWrite(getPermissions()); case DELETE: parentLD = getCatalogue().getLogicalDataByUid(getLogicalData().getParentRef()); p = getCatalogue().getPermissions(parentLD.getUid(), parentLD.getOwner()); return getPrincipal().canWrite(p); case GET: return getPrincipal().canRead(getPermissions()); case OPTIONS: return getPrincipal().canRead(getPermissions()); case POST: return getPrincipal().canWrite(getPermissions()); case PUT: return getPrincipal().canWrite(getPermissions()); case TRACE: return false; case CONNECT: return false; case REPORT: return false; default: return true; } } catch (Throwable th) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, "Exception in authorize for a resource " + getPath(), th); return false; } // return false; } @Override public String getRealm() { return "realm"; } @Override public Date getModifiedDate() { return new Date(getLogicalData().getModifiedDate()); } String getUserlUrlPrefix() { return "http://lobcder.net/user/"; } String getRoleUrlPrefix() { return "http://lobcder.net/role/"; } @Override public String getPrincipalURL() { String principalURL = getUserlUrlPrefix() + getPrincipal().getUserId(); Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "getPrincipalURL for {0}: {1}", new Object[]{getPath(), principalURL}); return principalURL; } @Override public List<Priviledge> getPriviledges(Auth auth) { final MyPrincipal currentPrincipal = getPrincipal(); List<Priviledge> perm = new ArrayList<>(); if (currentPrincipal.getUserId().equals(getLogicalData().getOwner())) { perm.add(Priviledge.ALL); return perm; } Set<String> currentRoles = currentPrincipal.getRoles(); //We are supposed to get permissions for this resource for the current user Permissions p; try { p = getPermissions(); } catch (SQLException e) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, "Could not get Permissions for resource " + getPath(), e); return perm; } Set<String> readRoles = p.getRead(); Set<String> writeRoles = p.getWrite(); readRoles.retainAll(currentRoles); if (!readRoles.isEmpty()) { perm.add(Priviledge.READ); perm.add(Priviledge.READ_ACL); perm.add(Priviledge.READ_CONTENT); perm.add(Priviledge.READ_CURRENT_USER_PRIVILEDGE); perm.add(Priviledge.READ_PROPERTIES); } writeRoles.retainAll(currentRoles); if (!writeRoles.isEmpty()) { perm.add(Priviledge.WRITE); perm.add(Priviledge.BIND); perm.add(Priviledge.UNBIND); perm.add(Priviledge.UNLOCK); perm.add(Priviledge.WRITE_ACL); perm.add(Priviledge.WRITE_CONTENT); perm.add(Priviledge.WRITE_PROPERTIES); } return perm; } @Override public Map<Principal, List<Priviledge>> getAccessControlList() { Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "getAccessControlList for {0}", getPath()); Permissions resourcePermission; HashMap<Principal, List<Priviledge>> acl = new HashMap<>(); try { // Do the mapping Principal p = new DavPrincipals.AbstractDavPrincipal(getPrincipalURL()) { @Override public boolean matches(Auth auth, Resource current) { return true; } }; resourcePermission = getPermissions(); List<Priviledge> perm = new ArrayList<>(); if (getPrincipal().canRead(resourcePermission)) { perm.add(Priviledge.READ); perm.add(Priviledge.READ_ACL); perm.add(Priviledge.READ_CONTENT); perm.add(Priviledge.READ_CURRENT_USER_PRIVILEDGE); perm.add(Priviledge.READ_PROPERTIES); } if (getPrincipal().canWrite(resourcePermission)) { perm.add(Priviledge.WRITE); perm.add(Priviledge.BIND); perm.add(Priviledge.UNBIND); perm.add(Priviledge.UNLOCK); perm.add(Priviledge.WRITE_ACL); perm.add(Priviledge.WRITE_CONTENT); perm.add(Priviledge.WRITE_PROPERTIES); } acl.put(p, perm); for (String r : resourcePermission.getRead()) { perm = new ArrayList<>(); p = new DavPrincipals.AbstractDavPrincipal(getRoleUrlPrefix() + r) { @Override public boolean matches(Auth auth, Resource current) { return true; } }; perm.add(Priviledge.READ); perm.add(Priviledge.READ_ACL); perm.add(Priviledge.READ_CONTENT); perm.add(Priviledge.READ_CURRENT_USER_PRIVILEDGE); perm.add(Priviledge.READ_PROPERTIES); acl.put(p, perm); } for (String r : resourcePermission.getWrite()) { perm = new ArrayList<>(); p = new DavPrincipals.AbstractDavPrincipal(getRoleUrlPrefix() + r) { @Override public boolean matches(Auth auth, Resource current) { return true; } }; perm.add(Priviledge.WRITE); perm.add(Priviledge.BIND); perm.add(Priviledge.UNBIND); perm.add(Priviledge.UNLOCK); perm.add(Priviledge.WRITE_ACL); perm.add(Priviledge.WRITE_CONTENT); perm.add(Priviledge.WRITE_PROPERTIES); acl.put(p, perm); } } catch (SQLException e) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, "Cannot read permissions for resource " + getPath(), e); } return acl; } @Override public void setAccessControlList(Map<Principal, List<Priviledge>> map) { Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "PLACEHOLDER setAccessControlList() for {0}", getPath()); for (Map.Entry<Principal, List<Priviledge>> me : map.entrySet()) { Principal principal = me.getKey(); for (Priviledge priviledge : me.getValue()) { Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "Set priveledges {0} for {1}", new Object[]{priviledge, principal}); //String id = principal.getIdenitifer().getValue(); //id = id.substring(id.lastIndexOf("/") + 1); } } } @Override public HrefList getPrincipalCollectionHrefs() { HrefList list = new HrefList(); list.add(""); return list; } protected PDRI createPDRI(long fileLength, String fileName, Connection connection) throws SQLException, NoSuchAlgorithmException, IOException { // Collection<StorageSite> cacheSS = getCatalogue().getCacheStorageSites(connection); Collection<StorageSite> cacheSS = getCatalogue().getStorageSites(connection, Boolean.TRUE, getPrincipal().isAdmin()); String nameWithoutSpace = fileName.replaceAll(" ", "_"); if (cacheSS == null || cacheSS.isEmpty()) { return new CachePDRI(UUID.randomUUID().toString() + "-" + nameWithoutSpace); } else { StorageSite ss = cacheSS.iterator().next(); PDRIDescr pdriDescr = new PDRIDescr( UUID.randomUUID().toString() + "-" + nameWithoutSpace, ss.getStorageSiteId(), ss.getResourceURI(), ss.getCredential().getStorageSiteUsername(), ss.getCredential().getStorageSitePassword(), ss.isEncrypt(), DesEncrypter.generateKey(), null, null, ss.isCache()); return PDRIFactory.getFactory().createInstance(pdriDescr, true); } } @Override public Object getProperty(QName qname) { try { if (qname.equals(Constants.DATA_DIST_PROP_NAME)) { return getDataDistString(); } else if (qname.equals(Constants.DRI_SUPERVISED_PROP_NAME)) { return String.valueOf(getLogicalData().getSupervised()); } else if (qname.equals(Constants.DRI_CHECKSUM_PROP_NAME)) { return String.valueOf(getLogicalData().getChecksum()); } else if (qname.equals(Constants.DRI_LAST_VALIDATION_DATE_PROP_NAME)) { return String.valueOf(getLogicalData().getLastValidationDate()); } else if (qname.equals(Constants.DRI_STATUS_PROP_NANE)) { return getLogicalData().getStatus(); } else if (qname.equals(Constants.DAV_CURRENT_USER_PRIVILAGE_SET_PROP_NAME)) { //List<Priviledge> list = getPriviledges(null); return ""; } else if (qname.equals(Constants.DAV_ACL_PROP_NAME)) { //List<Priviledge> list = getPriviledges(null); return ""; } else if (qname.equals(Constants.DESCRIPTION_PROP_NAME)) { return getLogicalData().getDescription(); } else if (qname.equals(Constants.DATA_LOC_PREF_NAME)) { return getDataLocationPreferencesString(); } else if (qname.equals(Constants.ENCRYPT_PROP_NAME)) { return getEcryptionString(); } else if (qname.equals(Constants.AVAIL_STORAGE_SITES_PROP_NAME)) { return getAvailStorageSitesString(getPrincipal().isAdmin()); } else if (qname.equals(Constants.TTL)) { return getLogicalData().getTtlSec(); } else if (qname.equals(Constants.REPLICATION_QUEUE)) { if (getPrincipal().isAdmin()) { return getReplicationQueueString(); } } else if (qname.equals(Constants.REPLICATION_QUEUE_LEN)) { // if (getPrincipal().isAdmin()) { return getReplicationQueueLen(); // } } else if (qname.equals(Constants.REPLICATION_QUEUE_SIZE)) { // if (getPrincipal().isAdmin()) { return getReplicationQueueSize(); // } } return PropertySource.PropertyMetaData.UNKNOWN; } catch (Throwable th) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, "Exception in getProperty() for resource " + getPath(), th); return PropertySource.PropertyMetaData.UNKNOWN; } } @Override public void setProperty(QName qname, Object o) throws PropertySource.PropertySetException, NotAuthorizedException { Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "setProperty for resource {0} : {1} = {2}", new Object[]{getPath(), qname, o}); try (Connection connection = getCatalogue().getConnection()) { try { if (o != null) { String value = (String) o; if (qname.equals(Constants.DRI_SUPERVISED_PROP_NAME)) { Boolean v = Boolean.valueOf(value); getLogicalData().setSupervised(v); getCatalogue().setLogicalDataSupervised(getLogicalData().getUid(), v, connection); } else if (qname.equals(Constants.DRI_CHECKSUM_PROP_NAME)) { getLogicalData().setChecksum(value); getCatalogue().setFileChecksum(getLogicalData().getUid(), value, connection); } else if (qname.equals(Constants.DRI_LAST_VALIDATION_DATE_PROP_NAME)) { Long v = Long.valueOf(value); getLogicalData().setLastValidationDate(v); getCatalogue().setLastValidationDate(getLogicalData().getUid(), v, connection); } else if (qname.equals(Constants.DRI_STATUS_PROP_NANE)) { getLogicalData().setStatus(value); getCatalogue().setDriStatus(getLogicalData().getUid(), value, connection); } else if (qname.equals(Constants.DESCRIPTION_PROP_NAME)) { String v = value; getLogicalData().setDescription(v); getCatalogue().setDescription(getLogicalData().getUid(), v, connection); } else if (qname.equals(Constants.DATA_LOC_PREF_NAME)) { setDataLocationPref(value, connection); } else if (qname.equals(Constants.ENCRYPT_PROP_NAME)) { setEncryptionPropertyValues(value, connection); } else if (qname.equals(Constants.TTL)) { String v = value; getLogicalData().setTtlSec(Integer.valueOf(v)); getCatalogue().setTTL(getLogicalData().getUid(), Integer.valueOf(v), connection); } connection.commit(); } } catch (SQLException | NumberFormatException e) { connection.rollback(); throw new PropertySource.PropertySetException(Response.Status.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } catch (SQLException e) { throw new PropertySource.PropertySetException(Response.Status.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } @Override public PropertySource.PropertyMetaData getPropertyMetaData(QName qname) { if (qname.equals(Constants.DATA_DIST_PROP_NAME) || qname.equals(Constants.REPLICATION_QUEUE) || qname.equals(Constants.REPLICATION_QUEUE_LEN)) { return new PropertySource.PropertyMetaData(PropertySource.PropertyAccessibility.READ_ONLY, String.class); } // if (qname.equals(Constants.DRI_CHECKSUM_PROP_NAME)) { // return new PropertySource.PropertyMetaData(PropertySource.PropertyAccessibility.READ_ONLY, String.class); // } for (QName n : Constants.PROP_NAMES) { if (n.equals(qname) && !n.equals(Constants.DATA_DIST_PROP_NAME)) { return new PropertySource.PropertyMetaData(PropertySource.PropertyAccessibility.WRITABLE, String.class); } } return PropertySource.PropertyMetaData.UNKNOWN; } @Override public List<QName> getAllPropertyNames() { return Arrays.asList(Constants.PROP_NAMES); } @Override public LockResult lock(LockTimeout timeout, LockInfo lockInfo) throws NotAuthorizedException, PreConditionFailedException, LockedException { if (getCurrentLock() != null) { throw new LockedException(this); } LockToken lockToken = new LockToken(UUID.randomUUID().toString(), lockInfo, timeout); Long lockTimeout; try (Connection connection = getCatalogue().getConnection()) { try { getLogicalData().setLockTokenID(lockToken.tokenId); getCatalogue().setLockTokenID(getLogicalData().getUid(), getLogicalData().getLockTokenID(), connection); getLogicalData().setLockScope(lockToken.info.scope.toString()); getCatalogue().setLockScope(getLogicalData().getUid(), getLogicalData().getLockScope(), connection); getLogicalData().setLockType(lockToken.info.type.toString()); getCatalogue().setLockType(getLogicalData().getUid(), getLogicalData().getLockType(), connection); getLogicalData().setLockedByUser(lockToken.info.lockedByUser); getCatalogue().setLockByUser(getLogicalData().getUid(), getLogicalData().getLockedByUser(), connection); getLogicalData().setLockDepth(lockToken.info.depth.toString()); getCatalogue().setLockDepth(getLogicalData().getUid(), getLogicalData().getLockDepth(), connection); lockTimeout = lockToken.timeout.getSeconds(); if (lockTimeout == null) { lockTimeout = Long.valueOf(System.currentTimeMillis() + Constants.LOCK_TIME); } getLogicalData().setLockTimeout(lockTimeout); getCatalogue().setLockTimeout(getLogicalData().getUid(), lockTimeout, connection); connection.commit(); return LockResult.success(lockToken); } catch (Exception ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); connection.rollback(); throw new PreConditionFailedException(this); } } catch (SQLException e) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, e); throw new PreConditionFailedException(this); } } @Override public LockResult refreshLock(String token) throws NotAuthorizedException, PreConditionFailedException { try (Connection connection = getCatalogue().getConnection()) { try { if (getLogicalData().getLockTokenID() == null) { throw new RuntimeException("not locked"); } else if (!getLogicalData().getLockTokenID().equals(token)) { throw new RuntimeException("invalid lock id"); } getLogicalData().setLockTimeout(System.currentTimeMillis() + Constants.LOCK_TIME); getCatalogue().setLockTimeout(getLogicalData().getUid(), getLogicalData().getLockTimeout(), connection); LockInfo lockInfo = new LockInfo(LockInfo.LockScope.valueOf(getLogicalData().getLockScope()), LockInfo.LockType.valueOf(getLogicalData().getLockType()), getLogicalData().getLockedByUser(), LockInfo.LockDepth.valueOf(getLogicalData().getLockDepth())); LockTimeout lockTimeOut = new LockTimeout(getLogicalData().getLockTimeout()); LockToken lockToken = new LockToken(token, lockInfo, lockTimeOut); connection.commit(); return LockResult.success(lockToken); } catch (Exception ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); connection.rollback(); throw new PreConditionFailedException(this); } } catch (SQLException e) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, e); throw new PreConditionFailedException(this); } } @Override public void unlock(String token) throws NotAuthorizedException, PreConditionFailedException { try (Connection connection = getCatalogue().getConnection()) { try { String tokenID = getLogicalData().getLockTokenID(); if (tokenID == null || tokenID.length() <= 0) { return; } else { if (tokenID.startsWith("<") && tokenID.endsWith(">") && !token.startsWith("<") && !token.endsWith(">")) { StringBuilder sb = new StringBuilder(); sb.append("<").append(token).append(">"); token = sb.toString(); } if (!tokenID.startsWith("<") && !tokenID.endsWith(">") && token.startsWith("<") && token.endsWith(">")) { token = token.replaceFirst("<", ""); token = token.replaceFirst(">", ""); } if (!tokenID.equals(token)) { throw new PreConditionFailedException(this); } } getCatalogue().setLockTokenID(getLogicalData().getUid(), null, connection); connection.commit(); getLogicalData().setLockTokenID(null); getLogicalData().setLockScope(null); getLogicalData().setLockType(null); getLogicalData().setLockedByUser(null); getLogicalData().setLockDepth(null); getLogicalData().setLockTimeout(null); } catch (Exception ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); connection.rollback(); throw new PreConditionFailedException(this); } } catch (SQLException e) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, e); throw new PreConditionFailedException(this); } } @Override public LockToken getCurrentLock() { if (getLogicalData().getLockTokenID() == null) { return null; } else { LockInfo lockInfo = new LockInfo(LockInfo.LockScope.valueOf(getLogicalData().getLockScope()), LockInfo.LockType.valueOf(getLogicalData().getLockType()), getLogicalData().getLockedByUser(), LockInfo.LockDepth.valueOf(getLogicalData().getLockDepth())); LockTimeout lockTimeOut = new LockTimeout(getLogicalData().getLockTimeout()); return new LockToken(getLogicalData().getLockTokenID(), lockInfo, lockTimeOut); } } @Override public String checkRedirect(Request request) throws NotAuthorizedException, BadRequestException { switch (request.getMethod()) { case PUT: case POST: if (!redirectPosts) { return null; } String redirect = null; try { if (!canRedirect(request)) { return null; } Map<Long, Pair<WebDataFileResource, Long>> resources = createResouses(request); // lockResources(resources); Map<String, Pair<Long, Collection<Long>>> storageMap = getStorageMap(resources); StringBuilder sb = new StringBuilder(); Set<String> keys = storageMap.keySet(); for (String k : keys) { sb.append("file_name=").append(k).append("/"); Pair pair = storageMap.get(k); Long fileUid = (Long) pair.getLeft(); sb.append("file_uid=").append(fileUid).append("/"); Long pdriGroupUid = resources.get(fileUid).getRight(); sb.append("pdrigroup_uid=").append(pdriGroupUid).append("/"); Collection<Long> ssids = (Collection<Long>) pair.getRight(); for (Long ssid : ssids) { sb.append("ss_id=").append(ssid).append("/"); } sb.append("&"); } sb.deleteCharAt(sb.length() - 1); String folder = request.getAbsolutePath(); if (!folder.endsWith("/")) { folder += "/"; } redirect = "http://localhost:8080/lobcder-worker" + folder + "?" + sb.toString(); } catch (Exception ex) { Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex); } return redirect; default: return null; } // return null; } private String getDataDistString() throws SQLException { try (Connection connection = getCatalogue().getConnection()) { try { connection.commit(); StringBuilder sb = new StringBuilder(); if (getLogicalData().isFolder()) { List<? extends WebDataResource> children = (List<? extends WebDataResource>) ((WebDataDirResource) (this)).getChildren(); if (children != null) { sb.append("["); for (WebDataResource r : children) { if (r instanceof WebDataFileResource) { // sb.append("'").append(r.getName()).append("' : ["); sb.append(r.getName()).append(" : ["); Collection<PDRIDescr> pdris = getCatalogue().getPdriDescrByGroupId(r.getLogicalData().getPdriGroupId(), connection); for (PDRIDescr p : pdris) { // sb.append("'").append(p.getResourceUrl()).append("/").append(p.getName()).append("',"); sb.append(p.getResourceUrl()).append("/").append(p.getName()).append(","); } sb.replace(sb.lastIndexOf(","), sb.length(), "").append("],"); } } } } else { Collection<PDRIDescr> pdris = getCatalogue().getPdriDescrByGroupId(getLogicalData().getPdriGroupId(), connection); if (pdris != null) { sb.append("["); for (PDRIDescr p : pdris) { // sb.append("'").append(p.getResourceUrl()).append("/").append(p.getName()).append("'"); sb.append(p.getResourceUrl()); if (!sb.toString().endsWith("/")) { sb.append("/"); } sb.append(p.getName()); sb.append(","); } } } if (sb.toString().contains(",")) { sb.replace(sb.lastIndexOf(","), sb.length(), ""); } sb.append("]"); return sb.toString(); } catch (NotAuthorizedException | SQLException e) { connection.rollback(); } } return null; } private String getEcryptionString() throws NotAuthorizedException, SQLException { try (Connection connection = getCatalogue().getConnection()) { StringBuilder sb = new StringBuilder(); if (getLogicalData().isFolder()) { List<? extends WebDataResource> children = (List<? extends WebDataResource>) ((WebDataDirResource) (this)).getChildren(); sb.append("["); if (children != null && !children.isEmpty()) { for (WebDataResource r : children) { if (r instanceof WebDataFileResource) { sb.append("'").append(r.getName()).append("' : ["); Collection<PDRIDescr> pdris = getCatalogue().getPdriDescrByGroupId(r.getLogicalData().getPdriGroupId(), connection); for (PDRIDescr p : pdris) { sb.append("["); sb.append(p.getResourceUrl()).append(","); sb.append(p.getEncrypt()); sb.append("],"); } sb.replace(sb.lastIndexOf(","), sb.length(), "").append("],"); } } } } else { Collection<PDRIDescr> pdris = getCatalogue().getPdriDescrByGroupId(getLogicalData().getPdriGroupId(), connection); sb.append("["); for (PDRIDescr p : pdris) { sb.append("["); sb.append(p.getResourceUrl()); sb.append(","); sb.append(p.getEncrypt()); sb.append("]"); sb.append(","); } } if (sb.toString().contains(",")) { sb.replace(sb.lastIndexOf(","), sb.length(), ""); } sb.append("]"); connection.commit(); return sb.toString(); } } private String getAvailStorageSitesString(Boolean includePrivate) throws SQLException { try (Connection connection = getCatalogue().getConnection()) { StringBuilder sb = new StringBuilder(); sb.append("["); for (String s : getAvailStorageSitesStr(includePrivate, connection)) { sb.append(s).append(","); } sb.replace(sb.lastIndexOf(","), sb.length(), ""); sb.append("]"); return sb.toString(); } } private void setEncryptionPropertyValues(String value, Connection connection) { String v = value; /// HashMap<String, Boolean> hostEncryptMap = new HashMap<>(); // String[] parts = v.split("[\\[\\]]"); // for (String p : parts) { // Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "Parts: {0}", p); // if (!p.isEmpty()) { // String[] hostEncryptValue = p.split(","); // if (hostEncryptValue.length == 2) { // String hostStr = hostEncryptValue[0]; // URI uri; // try { // uri = new URI(hostStr); // String host = uri.getScheme(); // host += "://" + uri.getHost(); // String encrypt = hostEncryptValue[1]; // hostEncryptMap.put(host, Boolean.valueOf(encrypt)); // } catch (URISyntaxException ex) { // //Wrong URI syntax, don't add it // } // } // } // } // List<PDRIDescr> pdris = getCatalogue().getPdriDescrByGroupId(getLogicalData().getPdriGroupId(), connection); // List<PDRIDescr> pdrisToUpdate = new ArrayList<PDRIDescr>(); // for (PDRIDescr p : pdris) { // URI uri = new URI(p.getResourceUrl()); // String host = uri.getScheme(); // host += "://" + uri.getHost(); // if (hostEncryptMap.containsKey(host)) { // p.setEncrypt(hostEncryptMap.get(host)); // pdrisToUpdate.add(p); // }} // } // if (!hostEncryptMap.isEmpty()) { // getCatalogue().updateStorageSites(hostEncryptMap, connection); // } // if (!pdrisToUpdate.isEmpty()) { // getCatalogue().updatePdris(pdrisToUpdate, connection); // } } protected String getDataLocationPreferencesString() throws SQLException { try (Connection connection = getCatalogue().getConnection()) { StringBuilder sb = new StringBuilder(); sb.append("["); for (String s : getLocationPrefStr(getLogicalData().getUid(), connection)) { sb.append(s).append(","); } if (sb.length() > 1) { sb.replace(sb.lastIndexOf(","), sb.length(), ""); sb.append("]"); return sb.toString(); } } return null; } private Collection<Long> getLocationPrefLong(Long uid, Connection connection) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("SELECT storageSiteRef FROM pref_table WHERE ld_uid=?")) { Collection<Long> result = new ArrayList<>(); ps.setLong(1, uid); ResultSet rs = ps.executeQuery(); while (rs.next()) { result.add(rs.getLong(1)); } return result; } } private Collection<String> getLocationPrefStr(Long uid, Connection connection) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("SELECT resourceUri " + "FROM pref_table " + "JOIN storage_site_table " + "ON storageSiteRef=storageSiteId " + "WHERE ld_uid=?")) { Collection<String> result = new ArrayList<>(); ps.setLong(1, uid); ResultSet rs = ps.executeQuery(); while (rs.next()) { result.add(rs.getString(1)); } return result; } } private Collection<String> getAvailStorageSitesStr(Boolean includePrivate, Connection connection) throws SQLException { try (Statement statement = connection.createStatement()) { Collection<String> result = new ArrayList<>(); ResultSet rs = includePrivate ? statement.executeQuery("SELECT resourceUri FROM storage_site_table WHERE isCache=FALSE AND removing=FALSE") : statement.executeQuery("SELECT resourceUri FROM storage_site_table WHERE isCache=FALSE AND removing=FALSE AND private=FALSE"); while (rs.next()) { result.add(rs.getString(1)); } return result; } } protected List<String> property2List(String value) { if (value.startsWith("[") && value.endsWith("]")) { value = value.substring(1, value.length() - 1); } return Arrays.asList(value.split("\\s*,\\s*")); } private void setDataLocationPref(String value, Connection connection) throws SQLException { List<String> list = property2List(value); getCatalogue().setLocationPreferences(connection, getLogicalData().getUid(), list, getPrincipal().isAdmin()); List<String> sites = property2List(getDataLocationPreferencesString()); getLogicalData().setDataLocationPreferences(sites); } private String getReplicationQueueString() throws SQLException { List<LogicalData> list = getCatalogue().getReplicationQueue(); if (list != null && !list.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append("["); for (LogicalData ld : getCatalogue().getReplicationQueue()) { sb.append(ld.getName()).append(","); } sb.replace(sb.lastIndexOf(","), sb.length(), "").append("],"); return sb.toString(); } return null; } private String getReplicationQueueLen() throws SQLException { return String.valueOf(getCatalogue().getReplicationQueueLen()); } private String getReplicationQueueSize() throws SQLException { return String.valueOf(getCatalogue().getReplicationQueueSize()); } private void lockResources(List<WebDataFileResource> resources) throws NotAuthorizedException, PreConditionFailedException, LockedException { for (WebDataFileResource r : resources) { LockToken tocken = r.getCurrentLock(); if (tocken == null || tocken.isExpired()) { LockTimeout timeout = new LockTimeout(System.currentTimeMillis() + Constants.LOCK_TIME); LockInfo info = new LockInfo(LockInfo.LockScope.EXCLUSIVE, LockInfo.LockType.WRITE, getPrincipal().getUserId(), LockInfo.LockDepth.INFINITY); LockResult lockResult = r.lock(timeout, info); } } } private Collection<Long> getPreferencesForFile(Long uid, Connection connection) throws SQLException { try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT " + "storageSiteRef FROM pref_table WHERE ld_uid=?")) { Collection<Long> result = new ArrayList<>(); preparedStatement.setLong(1, uid); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { result.add(resultSet.getLong(1)); } return result; } } private Map<Long, Pair<WebDataFileResource, Long>> createResouses(Request request) throws SQLException, UnsupportedEncodingException, NotAuthorizedException, NoSuchAlgorithmException, IOException { Map<Long, Pair<WebDataFileResource, Long>> resources = null; try (Connection connection = getCatalogue().getConnection()) { Map<String, FileItem> files = request.getFiles(); Collection<FileItem> fileItems = files.values(); resources = new HashMap<>(); WebDataFileResource resource = null; for (FileItem fi : fileItems) { Long pdriGroupid; Path newPath = Path.path(getPath(), fi.getName()); LogicalData fileLogicalData = getCatalogue().getLogicalDataByPath(newPath, connection); String contentType = mimeTypeMap.get(FilenameUtils.getExtension(fi.getName())); if (fileLogicalData != null) { Permissions p = getCatalogue().getPermissions(fileLogicalData.getUid(), fileLogicalData.getOwner(), connection); if (!getPrincipal().canWrite(p)) { throw new NotAuthorizedException(this); } fileLogicalData.setLength(fi.getSize()); fileLogicalData.setModifiedDate(System.currentTimeMillis()); fileLogicalData.setLastAccessDate(fileLogicalData.getModifiedDate()); fileLogicalData.addContentType(contentType); pdriGroupid = fileLogicalData.getPdriGroupId(); resource = new WebDataFileResource(fileLogicalData, Path.path(getPath(), fi.getName()), getCatalogue(), authList); } else { fileLogicalData = new LogicalData(); fileLogicalData.setName(fi.getName()); fileLogicalData.setParentRef(getLogicalData().getUid()); fileLogicalData.setType(Constants.LOGICAL_FILE); fileLogicalData.setOwner(getPrincipal().getUserId()); fileLogicalData.setLength(fi.getSize()); fileLogicalData.setCreateDate(System.currentTimeMillis()); fileLogicalData.setModifiedDate(System.currentTimeMillis()); fileLogicalData.setLastAccessDate(System.currentTimeMillis()); fileLogicalData.setTtlSec(getLogicalData().getTtlSec()); fileLogicalData.addContentType(contentType); pdriGroupid = getCatalogue().associateLogicalDataAndPdriGroup(fileLogicalData, connection); getCatalogue().setPreferencesOn(fileLogicalData.getUid(), getLogicalData().getUid(), connection); List<String> pref = getLogicalData().getDataLocationPreferences(); fileLogicalData.setDataLocationPreferences(pref); resource = new WebDataFileResource(fileLogicalData, Path.path(getPath(), fi.getName()), getCatalogue(), authList); } MutablePair<WebDataFileResource, Long> pair = new MutablePair<>(); pair.setRight(pdriGroupid); pair.setLeft(resource); resources.put(Long.valueOf(resource.getUniqueId()), pair); } connection.commit(); connection.close(); } return resources; } private Map<String, Pair<Long, Collection<Long>>> getStorageMap(Map<Long, Pair<WebDataFileResource, Long>> resources) throws SQLException, Exception { Map<String, Pair<Long, Collection<Long>>> storageMap = new HashMap<>(resources.size()); MutablePair<Long, Collection<Long>> pair; Collection<Pair<WebDataFileResource, Long>> val = resources.values(); try (Connection connection = getCatalogue().getConnection()) { for (Pair<WebDataFileResource, Long> r : val) { Long uid = Long.valueOf(r.getLeft().getUniqueId()); Collection<Long> pref = getPreferencesForFile(uid, connection); pair = new MutablePair<>(); if (pref != null && !pref.isEmpty()) { pair.setLeft(uid); pair.setRight(pref); storageMap.put(r.getLeft().getName(), pair); } else { Collection<Long> sites = getReplicationPolicy().getSitesToReplicate(connection); pair.setLeft(uid); pair.setRight(sites); storageMap.put(r.getLeft().getName(), pair); } } } return storageMap; } private ReplicationPolicy getReplicationPolicy() throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException { Class<? extends ReplicationPolicy> replicationPolicyClass = Class.forName(PropertiesHelper.getReplicationPolicy()).asSubclass(ReplicationPolicy.class); return replicationPolicyClass.newInstance(); } protected boolean canRedirect(Request request) throws SQLException, UnsupportedEncodingException, URISyntaxException, IOException { if (isInCache()) { return false; } Auth auth = request.getAuthorization(); if (auth == null) { return false; } final String autheader = request.getHeaders().get("authorization"); if (autheader != null) { final int index = autheader.indexOf(' '); if (index > 0) { final String credentials = new String(Base64.decodeBase64(autheader.substring(index).getBytes()), "UTF8"); final String uname = credentials.substring(0, credentials.indexOf(":")); final String token = credentials.substring(credentials.indexOf(":") + 1); if (authenticate(uname, token) == null) { return false; } if (!authorise(request, Request.Method.GET, auth)) { return false; } } } String userAgent = request.getHeaders().get("user-agent"); if (userAgent == null || userAgent.length() <= 1) { return false; } // WebDataFileResource.Logger.getLogger(WebDataResource.class.getName()).log(Level.FINE, "userAgent: {0}", userAgent); List<String> nonRedirectableUserAgents = PropertiesHelper.getNonRedirectableUserAgents(); for (String s : nonRedirectableUserAgents) { if (userAgent.contains(s)) { return false; } } return true; } protected boolean isInCache() throws SQLException, URISyntaxException, IOException { List<PDRIDescr> pdriDescr = getCatalogue().getPdriDescrByGroupId(getLogicalData().getPdriGroupId()); for (PDRIDescr pdri : pdriDescr) { if (pdri.getResourceUrl().startsWith("file")) { return true; } } // try (Connection cn = getCatalogue().getConnection()) { // List<PDRIDescr> pdriDescr = getCatalogue().getPdriDescrByGroupId(getLogicalData().getPdriGroupId(), cn); // for (PDRIDescr pdri : pdriDescr) { // if (pdri.getResourceUrl().startsWith("file")) { // return true; // } // } // } return false; } /** * @return the logicalData */ public LogicalData getLogicalData() { return logicalData; } /** * @return the catalogue */ public JDBCatalogue getCatalogue() { return catalogue; } /** * @return the path */ public Path getPath() { return path; } }
apache-2.0
waiwong/Eclipse_Workspace
Flash/src/jsp/sqlServer/bean/Flasher.java
5671
package jsp.sqlServer.bean; import java.io.IOException; import java.sql.ResultSet; import java.util.Vector; import jsp.sqlServer.database.DBConnect; public class Flasher { private int ID; private String Nickname; private String Truename; private String Kind; private String First; private String Classic; private String Photo; private String Detail; public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public String getNickname() { return Nickname; } public void setNickname(String Nickname) { this.Nickname = Nickname; } public String getTruename() { return Truename; } public void setTruename(String Truename) { this.Truename = Truename; } public String getKind() { return Kind; } public void setKind(String Kind) { this.Kind = Kind; } public String getPhoto() { return Photo; } public void setPhoto(String Photo) { this.Photo = Photo; } public String getFirst() { return First; } public void setFirst(String First) { this.First = First; } public String getClassic() { return Classic; } public void setClassic(String Classic) { this.Classic = Classic; } public String getDetail() { return Detail; } public void setDetail(String Detail) { this.Detail = Detail; } // add record public int addFlasher() throws Exception { String sql = "insert into t_flasher (Nickname,Truename,Type,Photo," +"First,Classic,Detail) Values(?,?,?,?,?,?,?)"; DBConnect dbc = new DBConnect(sql); dbc.setString(1,Nickname); dbc.setString(2,Truename); dbc.setString(3,Kind); dbc.setString(4,Photo); dbc.setString(5,First); dbc.setString(6,Classic); dbc.setString(7,Detail); int flag = dbc.executeUpdate(); dbc.close(); return flag; } // delete record public int deleteFlasher() throws Exception { String sql = "delete from t_flasher where ID='" + ID + "'"; DBConnect dbc = new DBConnect(sql); int flag = dbc.executeUpdate(); dbc.close(); return flag; } // modify record public int modifyFlasher() throws Exception { String sql = "update t_flasher set Nickname=?,Truename=?,Type=?," +"Photo=?,First=?,Classic=?,Detail=? where ID = ?"; DBConnect dbc = new DBConnect(sql); dbc.setString(1,Nickname); dbc.setString(2,Truename); dbc.setString(3,Kind); dbc.setString(4,Photo); dbc.setString(5,First); dbc.setString(6,Classic); dbc.setString(7,Detail); dbc.setInt(8,ID); int flag = dbc.executeUpdate(); dbc.close(); return flag; } // get a flasher object by searching flasher_id public Flasher getFlasherByFlasherID() throws IOException { try { String sql = "select * from t_flasher where ID = ?"; DBConnect dbc = new DBConnect(); dbc.prepareStatement(sql); dbc.setInt(1,ID); ResultSet rs = dbc.executeQuery(); if (rs.next()) { Flasher flasher = new Flasher(); flasher.setID(rs.getInt(1)); flasher.setNickname(rs.getString(2)); flasher.setTruename(rs.getString(3)); flasher.setKind(rs.getString(4)); flasher.setPhoto(rs.getString(5)); flasher.setFirst(rs.getString(6)); flasher.setClassic(rs.getString(7)); flasher.setDetail(rs.getString(8)); dbc.close(); return flasher; } else dbc.close(); } catch (Exception ex) { ex.printStackTrace(); } return null; } //get all index public Vector getAllFlasher() throws Exception { String sql = "select * from t_flasher"; try { DBConnect dbc = new DBConnect(); ResultSet rs = dbc.executeQuery(sql); Vector flasherVector = new Vector(); while(rs.next()){ Flasher flasher = new Flasher(); flasher.setID(rs.getInt(1)); flasher.setNickname(rs.getString(2)); flasher.setTruename(rs.getString(3)); flasher.setKind(rs.getString(4)); flasher.setPhoto(rs.getString(5)); flasher.setFirst(rs.getString(6)); flasher.setClassic(rs.getString(7)); flasher.setDetail(rs.getString(8)); flasherVector.add(flasher); } dbc.close(); return flasherVector; } catch (Exception ex) { ex.printStackTrace(); } return null; } public Vector getFlasherType() throws Exception { String sql = "select Distinct Type from t_flasher"; try { DBConnect dbc = new DBConnect(); ResultSet rs = dbc.executeQuery(sql); Vector flasherVector = new Vector(); while(rs.next()){ Flasher flasher = new Flasher(); flasher.setKind(rs.getString(1)); flasherVector.add(flasher); } dbc.close(); return flasherVector; } catch (Exception ex) { ex.printStackTrace(); } return null; } public Vector searchFlasher(String param,String value) throws IOException { if(param!=null&&value!=null&&(param.equals("ÄÐÉÁ¿Í")||param.equals("Å®ÉÁ¿Í")||param.equals("ÉÁ¿Í¹¤×÷ÊÒ"))) { String sql="select * from t_flasher where Type='" +param+"'" +"and Nickname like '%"+value+"%' or Truename like '%"+value+"%'"; try { DBConnect dbc = new DBConnect(); ResultSet rs=dbc.executeQuery(sql); Vector flasherVector = new Vector(); while(rs.next()){ Flasher flasher = new Flasher(); flasher.setID(rs.getInt(1)); flasher.setNickname(rs.getString(2)); flasher.setTruename(rs.getString(3)); flasher.setKind(rs.getString(4)); flasher.setPhoto(rs.getString(5)); flasher.setFirst(rs.getString(6)); flasher.setClassic(rs.getString(7)); flasher.setDetail(rs.getString(8)); flasherVector.add(flasher); } dbc.close(); return flasherVector; } catch (Exception ex) { ex.printStackTrace(); } return null; } else return null; } }
apache-2.0
petezybrick/iote2e
iote2e-stream/src/main/java/com/pzybrick/iote2e/stream/persist/BodyTemperatureVo.java
9422
/** * Copyright 2016, 2017 Peter Zybrick and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Pete Zybrick * @version 1.0.0, 2017-09 * */ package com.pzybrick.iote2e.stream.persist; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openmhealth.schema.domain.omh.BodyTemperature; import org.openmhealth.schema.domain.omh.DataPointHeader; /** * The Class BodyTemperatureVo. */ public class BodyTemperatureVo extends OmhVo { /** The Constant logger. */ private static final Logger logger = LogManager.getLogger(BodyTemperatureVo.class); /** The body temperature uuid. */ private String bodyTemperatureUuid; /** The effective time frame. */ private Timestamp effectiveTimeFrame; /** The descriptive statistic. */ private String descriptiveStatistic; /** The user notes. */ private String userNotes; /** The measurement location. */ private String measurementLocation; /** The body temperature unit. */ private String bodyTemperatureUnit; /** The body temperature value. */ private float bodyTemperatureValue; /** The insert ts. */ private Timestamp insertTs; /** * Instantiates a new body temperature vo. */ public BodyTemperatureVo() { } /** * Instantiates a new body temperature vo. * * @param header the header * @param bodyTemperature the body temperature * @throws SQLException the SQL exception */ public BodyTemperatureVo( DataPointHeader header, BodyTemperature bodyTemperature ) throws SQLException { this.bodyTemperatureUuid = header.getId(); setHeaderCommon(header); this.effectiveTimeFrame = new Timestamp( offsetDateTimeToMillis( bodyTemperature.getEffectiveTimeFrame().getDateTime() )); this.descriptiveStatistic = bodyTemperature.getDescriptiveStatistic().name(); this.userNotes = bodyTemperature.getUserNotes(); this.measurementLocation = bodyTemperature.getMeasurementLocation().name(); this.bodyTemperatureUnit = bodyTemperature.getBodyTemperature().getUnit(); this.bodyTemperatureValue = bodyTemperature.getBodyTemperature().getValue().floatValue(); } /** * Instantiates a new body temperature vo. * * @param rs the rs * @throws SQLException the SQL exception */ public BodyTemperatureVo(ResultSet rs) throws SQLException { this.bodyTemperatureUuid = rs.getString("body_temperature_uuid"); this.hdrSourceName = rs.getString("hdr_source_name"); this.hdrSourceCreationDateTime = rs.getTimestamp("hdr_source_creation_date_time"); this.hdrUserId = rs.getString("hdr_user_id"); this.hdrModality = rs.getString("hdr_modality"); this.hdrSchemaNamespace = rs.getString("hdr_schema_namespace"); this.hdrSchemaVersion = rs.getString("hdr_schema_version"); this.effectiveTimeFrame = rs.getTimestamp("effective_time_frame"); this.descriptiveStatistic = rs.getString("descriptive_statistic"); this.userNotes = rs.getString("user_notes"); this.measurementLocation = rs.getString("measurement_location"); this.bodyTemperatureUnit = rs.getString("body_temperature_unit"); this.bodyTemperatureValue = rs.getFloat("body_temperature_value"); this.insertTs = rs.getTimestamp("insert_ts"); } /** * Gets the body temperature uuid. * * @return the body temperature uuid */ public String getBodyTemperatureUuid() { return this.bodyTemperatureUuid; } /** * Gets the effective time frame. * * @return the effective time frame */ public Timestamp getEffectiveTimeFrame() { return this.effectiveTimeFrame; } /** * Gets the descriptive statistic. * * @return the descriptive statistic */ public String getDescriptiveStatistic() { return this.descriptiveStatistic; } /** * Gets the user notes. * * @return the user notes */ public String getUserNotes() { return this.userNotes; } /** * Gets the measurement location. * * @return the measurement location */ public String getMeasurementLocation() { return this.measurementLocation; } /** * Gets the body temperature unit. * * @return the body temperature unit */ public String getBodyTemperatureUnit() { return this.bodyTemperatureUnit; } /** * Gets the body temperature value. * * @return the body temperature value */ public float getBodyTemperatureValue() { return this.bodyTemperatureValue; } /** * Gets the insert ts. * * @return the insert ts */ public Timestamp getInsertTs() { return this.insertTs; } /** * Sets the body temperature uuid. * * @param bodyTemperatureUuid the body temperature uuid * @return the body temperature vo */ public BodyTemperatureVo setBodyTemperatureUuid( String bodyTemperatureUuid ) { this.bodyTemperatureUuid = bodyTemperatureUuid; return this; } /** * Sets the effective time frame. * * @param effectiveTimeFrame the effective time frame * @return the body temperature vo */ public BodyTemperatureVo setEffectiveTimeFrame( Timestamp effectiveTimeFrame ) { this.effectiveTimeFrame = effectiveTimeFrame; return this; } /** * Sets the descriptive statistic. * * @param descriptiveStatistic the descriptive statistic * @return the body temperature vo */ public BodyTemperatureVo setDescriptiveStatistic( String descriptiveStatistic ) { this.descriptiveStatistic = descriptiveStatistic; return this; } /** * Sets the user notes. * * @param userNotes the user notes * @return the body temperature vo */ public BodyTemperatureVo setUserNotes( String userNotes ) { this.userNotes = userNotes; return this; } /** * Sets the measurement location. * * @param measurementLocation the measurement location * @return the body temperature vo */ public BodyTemperatureVo setMeasurementLocation( String measurementLocation ) { this.measurementLocation = measurementLocation; return this; } /** * Sets the body temperature unit. * * @param bodyTemperatureUnit the body temperature unit * @return the body temperature vo */ public BodyTemperatureVo setBodyTemperatureUnit( String bodyTemperatureUnit ) { this.bodyTemperatureUnit = bodyTemperatureUnit; return this; } /** * Sets the body temperature value. * * @param bodyTemperatureValue the body temperature value * @return the body temperature vo */ public BodyTemperatureVo setBodyTemperatureValue( float bodyTemperatureValue ) { this.bodyTemperatureValue = bodyTemperatureValue; return this; } /** * Sets the insert ts. * * @param insertTs the insert ts * @return the body temperature vo */ public BodyTemperatureVo setInsertTs( Timestamp insertTs ) { this.insertTs = insertTs; return this; } /** * Sets the hdr source name. * * @param hdrSourceName the hdr source name * @return the body temperature vo */ public BodyTemperatureVo setHdrSourceName(String hdrSourceName) { this.hdrSourceName = hdrSourceName; return this; } /** * Sets the hdr source creation date time. * * @param hdrSourceCreationDateTime the hdr source creation date time * @return the body temperature vo */ public BodyTemperatureVo setHdrSourceCreationDateTime(Timestamp hdrSourceCreationDateTime) { this.hdrSourceCreationDateTime = hdrSourceCreationDateTime; return this; } /** * Sets the hdr user id. * * @param hdrUserId the hdr user id * @return the body temperature vo */ public BodyTemperatureVo setHdrUserId(String hdrUserId) { this.hdrUserId = hdrUserId; return this; } /** * Sets the hdr modality. * * @param hdrModality the hdr modality * @return the body temperature vo */ public BodyTemperatureVo setHdrModality(String hdrModality) { this.hdrModality = hdrModality; return this; } /** * Sets the hdr schema namespace. * * @param hdrSchemaNamespace the hdr schema namespace * @return the body temperature vo */ public BodyTemperatureVo setHdrSchemaNamespace(String hdrSchemaNamespace) { this.hdrSchemaNamespace = hdrSchemaNamespace; return this; } /** * Sets the hdr schema version. * * @param hdrSchemaVersion the hdr schema version * @return the body temperature vo */ public BodyTemperatureVo setHdrSchemaVersion(String hdrSchemaVersion) { this.hdrSchemaVersion = hdrSchemaVersion; return this; } } // BodyTemperatureVo bodyTemperatureVo = new BodyTemperatureVo() // .setBodyTemperatureUuid("xxx") // .setHdrSourceName("xxx") // .setHdrSourceCreationDateTime("xxx") // .setHdrUserId("xxx") // .setHdrModality("xxx") // .setHdrSchemaNamespace("xxx") // .setHdrSchemaVersion("xxx") // .setEffectiveTimeFrame("xxx") // .setDescriptiveStatistic("xxx") // .setUserNotes("xxx") // .setMeasurementLocation("xxx") // .setBodyTemperatureUnit("xxx") // .setBodyTemperatureValue("xxx") // .setInsertTs("xxx") // ;
apache-2.0
google/jsinterop-generator
java/jsinterop/generator/model/WildcardTypeReference.java
3975
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package jsinterop.generator.model; import static jsinterop.generator.model.PredefinedTypeReference.OBJECT; import com.google.j2cl.common.visitor.Processor; import com.google.j2cl.common.visitor.Visitable; import java.util.Arrays; import java.util.Objects; /** * Represents a wildcard type argument. Examples: * * <ul> * <li>? * <li>? extends Foo * <li>? super T * </ul> * * <p>A wildcard may have a upper bound ({@code ? extends Foo}) or a lower bound ({@code ? super * Foo}) or neither ({@code ?}) but not both. */ @Visitable public class WildcardTypeReference implements TypeReference { public static WildcardTypeReference createWildcardUpperBound(TypeReference upperBound) { if (upperBound.equals(PredefinedTypeReference.OBJECT)) { return createUnboundedWildcard(); } return new WildcardTypeReference(upperBound, null); } public static WildcardTypeReference createWildcardLowerBound(TypeReference lowerBound) { if (lowerBound.equals(PredefinedTypeReference.OBJECT)) { return createUnboundedWildcard(); } return new WildcardTypeReference(null, lowerBound); } public static WildcardTypeReference createUnboundedWildcard() { return new WildcardTypeReference(null, null); } private TypeReference upperBound; private TypeReference lowerBound; private WildcardTypeReference(TypeReference upperBound, TypeReference lowerBound) { this.upperBound = upperBound; this.lowerBound = lowerBound; } public TypeReference getLowerBound() { return lowerBound; } public TypeReference getUpperBound() { return upperBound; } public void setLowerBound(TypeReference lowerBound) { this.lowerBound = lowerBound; } public void setUpperBound(TypeReference upperBound) { this.upperBound = upperBound; } public TypeReference getBound() { return (lowerBound != null) ? lowerBound : (upperBound != null) ? upperBound : OBJECT; } @Override public String getTypeName() { return getBound().getTypeName(); } @Override public String getImport() { return null; } @Override public String getComment() { return null; } @Override public String getJsDocAnnotationString() { return getBound().getJsDocAnnotationString(); } @Override public String getJavaTypeFqn() { throw new UnsupportedOperationException(); } @Override public String getJavaRelativeQualifiedTypeName() { throw new UnsupportedOperationException(); } @Override public String getJniSignature() { throw new UnsupportedOperationException(); } @Override public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof WildcardTypeReference)) { return false; } return Objects.equals(lowerBound, ((WildcardTypeReference) o).lowerBound) && Objects.equals(upperBound, ((WildcardTypeReference) o).upperBound); } @Override public int hashCode() { return Arrays.hashCode(new Object[] {lowerBound, upperBound}); } @Override public String toString() { if (lowerBound != null) { return "? super " + lowerBound; } else if (upperBound != null) { return "? extends " + upperBound; } return "?"; } @Override public TypeReference accept(Processor processor) { return Visitor_WildcardTypeReference.visit(processor, this); } }
apache-2.0
BladeRunnerJS/brjs-JsTestDriver
eclipse-plugin/plugins/com.google.eclipse.javascript.jstestdriver.core/src/com/google/eclipse/javascript/jstestdriver/core/model/ResultModel.java
3285
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.eclipse.javascript.jstestdriver.core.model; import com.google.jstestdriver.TestResult; import java.util.Collection; /** * Model of the test results from JS Test Driver which is used by the UI to render and display test * results returned from JS Test Driver. * Each level of test results, like an individual test, a test case, a browser test suite etc * needs to implement these common methods for ease of rendering in the tree. * * @author shyamseshadri@gmail.com (Shyam Seshadri) */ public interface ResultModel { /** * Did the test (potentially set of tests) pass or not. * * @return boolean representing whether this set of test results passed or not. A single failure * in a child implies a failure overall. */ boolean passed(); /** * The display label for this collection of results. * * @return string to represent the test result in a results tree. */ String getDisplayLabel(); /** * Gets all the children of this result model. Empty collection if no children present. * * @return all the children results of this model */ Collection<? extends ResultModel> getChildren(); /** * Parent of this result model, or {@code null} if it is the root. * * @return get the parent result model, or {@code null} if this is the root */ ResultModel getParent(); /** * Does this result model have any children. * * @return false if this the leaf result, true otherwise */ boolean hasChildren(); /** * The absolute path to the image. * * @return the absolute path to the display image */ String getDisplayImagePath(); /** * Clears all the test results underneath this result model. Recursively clears everything under * it first before clearing itself. */ void clear(); /** * Add the JS Test Driver test result as a child. Each type of test result in the * tree should handle their labeling themselves. * * @param result The JS Test Driver test result to be added as a child. * @return the leaf result model created */ ResultModel addTestResult(TestResult result); /** * Total number of tests under this model. * @return the total number of tests under this result model. Recurses into its children. */ int getNumberOfTests(); /** * Number of failures under this model. * * @return the total number of failing tests under this result model. Recurses into its children. */ int getNumberOfFailures(); /** * Number of errors under this model. * * @return the total number of tests with errors under this result model. Recurses into its * children. */ int getNumberOfErrors(); }
apache-2.0
pwilder/jsonschema2pojo
jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/rules/ObjectRule.java
18680
/** * Copyright © 2010-2014 Nokia * * 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.jsonschema2pojo.rules; import static org.apache.commons.lang3.StringUtils.*; import static org.jsonschema2pojo.rules.PrimitiveTypes.*; import static org.jsonschema2pojo.util.TypeUtil.*; import java.io.Serializable; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.jsonschema2pojo.AnnotationStyle; import org.jsonschema2pojo.Schema; import org.jsonschema2pojo.SchemaMapper; import org.jsonschema2pojo.exception.ClassAlreadyExistsException; import org.jsonschema2pojo.util.NameHelper; import org.jsonschema2pojo.util.ParcelableHelper; import org.jsonschema2pojo.util.TypeUtil; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.JsonNode; import com.sun.codemodel.ClassType; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JPackage; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import android.os.Parcelable; /** * Applies the generation steps required for schemas of type "object". * * @see <a href= * "http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1">http:/ * /tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1</a> */ public class ObjectRule implements Rule<JPackage, JType> { private final RuleFactory ruleFactory; private final ParcelableHelper parcelableHelper; protected ObjectRule(RuleFactory ruleFactory, ParcelableHelper parcelableHelper) { this.ruleFactory = ruleFactory; this.parcelableHelper = parcelableHelper; } /** * Applies this schema rule to take the required code generation steps. * <p> * When this rule is applied for schemas of type object, the properties of * the schema are used to generate a new Java class and determine its * characteristics. See other implementers of {@link Rule} for details. * <p> * A new Java type will be created when this rule is applied, it is * annotated as {@link Generated}, it is given <code>equals</code>, * <code>hashCode</code> and <code>toString</code> methods and implements * {@link Serializable}. */ @Override public JType apply(String nodeName, JsonNode node, JPackage _package, Schema schema) { JType superType = getSuperType(nodeName, node, _package, schema); if (superType.isPrimitive() || isFinal(superType)) { return superType; } JDefinedClass jclass; try { jclass = createClass(nodeName, node, _package); } catch (ClassAlreadyExistsException e) { return e.getExistingClass(); } jclass._extends((JClass) superType); schema.setJavaTypeIfEmpty(jclass); addGeneratedAnnotation(jclass); if (node.has("deserializationClassProperty")) { addJsonTypeInfoAnnotation(jclass, node); } if (node.has("title")) { ruleFactory.getTitleRule().apply(nodeName, node.get("title"), jclass, schema); } if (node.has("description")) { ruleFactory.getDescriptionRule().apply(nodeName, node.get("description"), jclass, schema); } if (node.has("properties")) { ruleFactory.getPropertiesRule().apply(nodeName, node.get("properties"), jclass, schema); } if (ruleFactory.getGenerationConfig().isIncludeToString()) { addToString(jclass); } if (node.has("javaInterfaces")) { addInterfaces(jclass, node.get("javaInterfaces")); } ruleFactory.getAdditionalPropertiesRule().apply(nodeName, node.get("additionalProperties"), jclass, schema); ruleFactory.getDynamicPropertiesRule().apply(nodeName, node.get("properties"), jclass, schema); if (node.has("required")) { ruleFactory.getRequiredArrayRule().apply(nodeName, node.get("required"), jclass, schema); } if (ruleFactory.getGenerationConfig().isIncludeHashcodeAndEquals()) { addHashCode(jclass); addEquals(jclass); } if (ruleFactory.getGenerationConfig().isParcelable()) { addParcelSupport(jclass); } if (ruleFactory.getGenerationConfig().isIncludeConstructors()) { addConstructors(jclass, getConstructorProperties(node, ruleFactory.getGenerationConfig().isConstructorsRequiredPropertiesOnly())); } return jclass; } private void addParcelSupport(JDefinedClass jclass) { jclass._implements(Parcelable.class); parcelableHelper.addWriteToParcel(jclass); parcelableHelper.addDescribeContents(jclass); parcelableHelper.addCreator(jclass); } /** * Retrieve the list of properties to go in the constructor from node. This * is all properties listed in node["properties"] if ! onlyRequired, and * only required properties if onlyRequired. * * @param node * @return */ private List<String> getConstructorProperties(JsonNode node, boolean onlyRequired) { if (!node.has("properties")) { return new ArrayList<String>(); } List<String> rtn = new ArrayList<String>(); NameHelper nameHelper = ruleFactory.getNameHelper(); for (Iterator<Map.Entry<String, JsonNode>> properties = node.get("properties").fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); JsonNode propertyObj = property.getValue(); if (onlyRequired) { if (propertyObj.has("required") && propertyObj.get("required").asBoolean()) { rtn.add(nameHelper.getPropertyName(property.getKey())); } } else { rtn.add((nameHelper.getPropertyName(property.getKey()))); } } return rtn; } /** * Creates a new Java class that will be generated. * * @param nodeName * the node name which may be used to dictate the new class name * @param node * the node representing the schema that caused the need for a * new class. This node may include a 'javaType' property which * if present will override the fully qualified name of the newly * generated class. * @param _package * the package which may contain a new class after this method * call * @return a reference to a newly created class * @throws ClassAlreadyExistsException * if the given arguments cause an attempt to create a class * that already exists, either on the classpath or in the * current map of classes to be generated. */ private JDefinedClass createClass(String nodeName, JsonNode node, JPackage _package) throws ClassAlreadyExistsException { JDefinedClass newType; try { boolean usePolymorphicDeserialization = usesPolymorphicDeserialization(node); if (node.has("javaType")) { String fqn = substringBefore(node.get("javaType").asText(), "<"); if (isPrimitive(fqn, _package.owner())) { throw new ClassAlreadyExistsException(primitiveType(fqn, _package.owner())); } int index = fqn.lastIndexOf(".") + 1; if (index >= 0 && index < fqn.length()) { fqn = fqn.substring(0, index) + ruleFactory.getGenerationConfig().getClassNamePrefix() + fqn.substring(index) + ruleFactory.getGenerationConfig().getClassNameSuffix(); } try { _package.owner().ref(Thread.currentThread().getContextClassLoader().loadClass(fqn)); JClass existingClass = TypeUtil.resolveType(_package, fqn + (node.get("javaType").asText().contains("<") ? "<" + substringAfter(node.get("javaType").asText(), "<") : "")); throw new ClassAlreadyExistsException(existingClass); } catch (ClassNotFoundException e) { if (usePolymorphicDeserialization) { newType = _package.owner()._class(JMod.PUBLIC, fqn, ClassType.CLASS); } else { newType = _package.owner()._class(fqn); } } } else { if (usePolymorphicDeserialization) { newType = _package._class(JMod.PUBLIC, getClassName(nodeName, _package), ClassType.CLASS); } else { newType = _package._class(getClassName(nodeName, _package)); } } } catch (JClassAlreadyExistsException e) { throw new ClassAlreadyExistsException(e.getExistingClass()); } ruleFactory.getAnnotator().propertyInclusion(newType, node); return newType; } private boolean isFinal(JType superType) { try { Class<?> javaClass = Class.forName(superType.fullName()); return Modifier.isFinal(javaClass.getModifiers()); } catch (ClassNotFoundException e) { return false; } } private JType getSuperType(String nodeName, JsonNode node, JPackage jPackage, Schema schema) { if (node.has("extends") && node.has("extendsJavaClass")) { throw new IllegalStateException("'extends' and 'extendsJavaClass' defined simultaneously"); } JType superType = jPackage.owner().ref(Object.class); if (node.has("extends")) { String path; if (schema.getId().getFragment() == null) { path = "#extends"; } else { path = "#" + schema.getId().getFragment() + "/extends"; } Schema superTypeSchema = ruleFactory.getSchemaStore().create(schema, path); superType = ruleFactory.getSchemaRule().apply(nodeName + "Parent", node.get("extends"), jPackage, superTypeSchema); } else if (node.has("extendsJavaClass")) { superType = resolveType(jPackage, node.get("extendsJavaClass").asText()); } return superType; } private void addGeneratedAnnotation(JDefinedClass jclass) { JAnnotationUse generated = jclass.annotate(Generated.class); generated.param("value", SchemaMapper.class.getPackage().getName()); } private void addJsonTypeInfoAnnotation(JDefinedClass jclass, JsonNode node) { if (this.ruleFactory.getGenerationConfig().getAnnotationStyle() == AnnotationStyle.JACKSON2) { String annotationName = node.get("deserializationClassProperty").asText(); JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class); jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS); jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY); jsonTypeInfo.param("property", annotationName); } } private void addToString(JDefinedClass jclass) { JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString"); Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class; JBlock body = toString.body(); JInvocation reflectionToString = jclass.owner().ref(toStringBuilder).staticInvoke("reflectionToString"); reflectionToString.arg(JExpr._this()); body._return(reflectionToString); toString.annotate(Override.class); } private void addHashCode(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode"); Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class; JBlock body = hashCode.body(); JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder); JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass); if (!jclass._extends().name().equals("Object")) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { if( (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) continue; hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); } private void addConstructors(JDefinedClass jclass, List<String> properties) { // no properties to put in the constructor => default constructor is good enough. if (properties.isEmpty()) { return; } // add a no-args constructor for serialization purposes JMethod noargsConstructor = jclass.constructor(JMod.PUBLIC); noargsConstructor.javadoc().add("No args constructor for use in serialization"); // add the public constructor with property parameters JMethod fieldsConstructor = jclass.constructor(JMod.PUBLIC); JBlock constructorBody = fieldsConstructor.body(); Map<String, JFieldVar> fields = jclass.fields(); for (String property : properties) { JFieldVar field = fields.get(property); if (field == null) { throw new IllegalStateException("Property " + property + " hasn't been added to JDefinedClass before calling addConstructors"); } fieldsConstructor.javadoc().addParam(property); JVar param = fieldsConstructor.param(field.type(), field.name()); constructorBody.assign(JExpr._this().ref(field), param); } } private void addEquals(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); Class<?> equalsBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.EqualsBuilder.class : org.apache.commons.lang.builder.EqualsBuilder.class; JBlock body = equals.body(); body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE); body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE); JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject)); JClass equalsBuilderClass = jclass.owner().ref(equalsBuilder); JInvocation equalsBuilderInvocation = JExpr._new(equalsBuilderClass); if (!jclass._extends().name().equals("Object")) { equalsBuilderInvocation = equalsBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("equals").arg(otherObject)); } for (JFieldVar fieldVar : fields.values()) { if( (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC ) continue; equalsBuilderInvocation = equalsBuilderInvocation.invoke("append") .arg(fieldVar) .arg(rhsVar.ref(fieldVar.name())); } JInvocation reflectionEquals = jclass.owner().ref(equalsBuilder).staticInvoke("reflectionEquals"); reflectionEquals.arg(JExpr._this()); reflectionEquals.arg(otherObject); body._return(equalsBuilderInvocation.invoke("isEquals")); equals.annotate(Override.class); } private void addInterfaces(JDefinedClass jclass, JsonNode javaInterfaces) { for (JsonNode i : javaInterfaces) { jclass._implements(resolveType(jclass._package(), i.asText())); } } private String getClassName(String nodeName, JPackage _package) { String prefix = ruleFactory.getGenerationConfig().getClassNamePrefix(); String suffix = ruleFactory.getGenerationConfig().getClassNameSuffix(); String capitalizedNodeName = capitalize(nodeName); String fullNodeName = createFullNodeName(capitalizedNodeName, prefix, suffix); String className = ruleFactory.getNameHelper().replaceIllegalCharacters(fullNodeName); String normalizedName = ruleFactory.getNameHelper().normalizeName(className); return makeUnique(normalizedName, _package); } private String createFullNodeName(String nodeName, String prefix, String suffix) { String returnString = nodeName; if (prefix != null) { returnString = prefix + returnString; } if (suffix != null) { returnString = returnString + suffix; } return returnString; } private String makeUnique(String className, JPackage _package) { try { JDefinedClass _class = _package._class(className); _package.remove(_class); return className; } catch (JClassAlreadyExistsException e) { return makeUnique(className + "_", _package); } } private boolean usesPolymorphicDeserialization(JsonNode node) { if (ruleFactory.getGenerationConfig().getAnnotationStyle() == AnnotationStyle.JACKSON2) { return node.has("deserializationClassProperty"); } return false; } }
apache-2.0
blackducksoftware/common-framework
src/main/java/com/blackducksoftware/tools/commonframework/core/config/server/ServerBeanList.java
2225
/** * CommonFramework * * Copyright (C) 2017 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.blackducksoftware.tools.commonframework.core.config.server; import java.util.ArrayList; import java.util.List; import com.blackducksoftware.tools.commonframework.core.config.ConfigConstants; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; /** * Class that holds the list of server objects (used by parsers to generate * implicit lists) * * @author akamen * */ @XStreamAlias(ConfigConstants.SERVERS_PROPERTY) public class ServerBeanList extends ConfigConstants { /** The server list. */ @XStreamImplicit(itemFieldName = SERVER_PROPERTY) private List<ServerBean> serverList = new ArrayList<ServerBean>(); /** * Instantiates a new server bean list. */ public ServerBeanList() { } /** * Adds the. * * @param bean * the bean */ public void add(ServerBean bean) { serverList.add(bean); } /** * Gets the servers. * * @return the servers */ public List<ServerBean> getServers() { return serverList; } /** * Sets the servers. * * @param serverList * the new servers */ public void setServers(List<ServerBean> serverList) { this.serverList = serverList; } }
apache-2.0
alter-ego/androidbound
AndroidBound/src/main/java/solutions/alterego/androidbound/android/interfaces/INeedsNewIntent.java
173
package solutions.alterego.androidbound.android.interfaces; import android.content.Intent; public interface INeedsNewIntent { void onNewIntent (Intent newIntent); }
apache-2.0
daedric/buck
test/com/facebook/buck/apple/MultiarchFileTest.java
8293
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.apple; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import com.facebook.buck.cxx.CxxCompilationDatabase; import com.facebook.buck.cxx.CxxInferEnhancer; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.Flavored; import com.facebook.buck.model.ImmutableFlavor; import com.facebook.buck.rules.AbstractNodeBuilder; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.FakeBuildContext; import com.facebook.buck.rules.FakeBuildableContext; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.SourceWithFlags; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.shell.ShellStep; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.testutil.TargetGraphFactory; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.environment.Platform; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class MultiarchFileTest { @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "AppleBinaryDescription", FakeAppleRuleDescriptions.BINARY_DESCRIPTION, (NodeBuilderFactory) AppleBinaryBuilder::createBuilder }, { "AppleLibraryDescription (static)", FakeAppleRuleDescriptions.LIBRARY_DESCRIPTION, (NodeBuilderFactory) target -> AppleLibraryBuilder .createBuilder(target.withAppendedFlavors(ImmutableFlavor.of("static"))) .setSrcs(ImmutableSortedSet.of( SourceWithFlags.of(new FakeSourcePath("foo.c")))) }, { "AppleLibraryDescription (shared)", FakeAppleRuleDescriptions.LIBRARY_DESCRIPTION, (NodeBuilderFactory) target -> AppleLibraryBuilder .createBuilder(target.withAppendedFlavors(ImmutableFlavor.of("shared"))) .setSrcs(ImmutableSortedSet.of( SourceWithFlags.of(new FakeSourcePath("foo.c")))) }, }); } @Parameterized.Parameter(0) public String name; @Parameterized.Parameter(1) public Description<?> description; @Parameterized.Parameter(2) public NodeBuilderFactory nodeBuilderFactory; @Before public void setUp() { assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX); } @Test public void shouldAllowMultiplePlatformFlavors() { assertTrue( ((Flavored) description).hasFlavors( ImmutableSet.of( ImmutableFlavor.of("iphoneos-i386"), ImmutableFlavor.of("iphoneos-x86_64")))); } @SuppressWarnings({"unchecked"}) @Test public void descriptionWithMultiplePlatformArgsShouldGenerateMultiarchFile() throws Exception { BuildTarget target = BuildTargetFactory.newInstance("//foo:thing#iphoneos-i386,iphoneos-x86_64"); BuildTarget sandboxTarget = BuildTargetFactory.newInstance( "//foo:thing#iphoneos-i386,iphoneos-x86_64,sandbox"); BuildRuleResolver resolver = new BuildRuleResolver( TargetGraphFactory.newInstance(new AppleLibraryBuilder(sandboxTarget).build()), new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver)); ProjectFilesystem filesystem = new FakeProjectFilesystem(); BuildRule multiarchRule = nodeBuilderFactory .getNodeBuilder(target) .build(resolver, filesystem); assertThat(multiarchRule, instanceOf(MultiarchFile.class)); ImmutableList<Step> steps = multiarchRule.getBuildSteps( FakeBuildContext.withSourcePathResolver(pathResolver), new FakeBuildableContext()); ShellStep step = Iterables.getLast(Iterables.filter(steps, ShellStep.class)); ExecutionContext executionContext = TestExecutionContext.newInstance(); ImmutableList<String> command = step.getShellCommand(executionContext); assertThat( command, Matchers.contains( endsWith("lipo"), equalTo("-create"), equalTo("-output"), containsString("foo/thing#"), containsString("/thing#"), containsString("/thing#"))); } @Test public void descriptionWithMultipleDifferentSdksShouldFail() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); HumanReadableException exception = null; try { nodeBuilderFactory .getNodeBuilder( BuildTargetFactory.newInstance("//foo:xctest#iphoneos-i386,macosx-x86_64")) .build(resolver); } catch (HumanReadableException e) { exception = e; } assertThat(exception, notNullValue()); assertThat( "Should throw exception about different architectures", exception.getHumanReadableErrorMessage(), endsWith("Fat binaries can only be generated from binaries compiled for the same SDK.")); } @Test public void ruleWithSpecialBuildActionShouldFail() throws Exception { BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); HumanReadableException exception = null; Iterable<Flavor> forbiddenFlavors = ImmutableList.<Flavor>builder() .addAll(CxxInferEnhancer.InferFlavors.getAll()) .add(CxxCompilationDatabase.COMPILATION_DATABASE) .build(); for (Flavor flavor : forbiddenFlavors) { try { nodeBuilderFactory .getNodeBuilder( BuildTargetFactory.newInstance("//foo:xctest#" + "iphoneos-i386,iphoneos-x86_64," + flavor.toString())) .build(resolver); } catch (HumanReadableException e) { exception = e; } assertThat(exception, notNullValue()); assertThat( "Should throw exception about special build actions.", exception.getHumanReadableErrorMessage(), endsWith("Fat binaries is only supported when building an actual binary.")); } } /** * Rule builders pass BuildTarget as a constructor arg, so this is unfortunately necessary. */ private interface NodeBuilderFactory { AbstractNodeBuilder<?, ?> getNodeBuilder(BuildTarget target); } }
apache-2.0
aviral26/ucsb-cs-263
goplaces/src/test/java/goplaces/workers/BoxRouteWorkerTest.java
4025
package goplaces.workers; import static org.junit.Assert.*; import java.util.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BoxRouteWorkerTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } // Commenting this out because I want to check the 100 (at most) places which are returned by BoxRouteWorker @Test public void testFilterPlacesRandomly() { JSONObject initialJSONObject = new JSONObject(); int finalPlacesNumberPerRequest = 100; for (int key = 0; key < 20; key++) { JSONArray jsonArrayForKey = new JSONArray(); for (int valueIndex = 0; valueIndex < finalPlacesNumberPerRequest; valueIndex++) { int value = key * finalPlacesNumberPerRequest + valueIndex; JSONObject jsonObjectForArray = new JSONObject(); jsonObjectForArray.put(String.valueOf(valueIndex), value); jsonArrayForKey.add(jsonObjectForArray); } initialJSONObject.put(String.valueOf(key), jsonArrayForKey); } assertEquals(20, initialJSONObject.keySet().size()); Set<String> keySet = initialJSONObject.keySet(); for (String key : keySet) { assertEquals(100, ((JSONArray)initialJSONObject.get(key)).size()); } // We get an JSONObject that looks like: /* * { * "0": [ * {"0": 0}, * {"1": 1}, * {"2": 2}, * ... * {"99": 99} * ], * "1": [ * {"0": 100}, * {"1": 101}, * {"2": 102}, * ... * {"99": 199} * ], * ... * "19": [ * {"0": 1900}, * {"1": 1901}, * {"2": 1902}, * ... * {"99": 1999} * ] * } */ BoxRouteWorker boxRouteWorker = new BoxRouteWorker(); JSONObject finalJSONObject = boxRouteWorker.filterPlacesRandomly(initialJSONObject, 100, new ArrayList<String>()); assertEquals(20, finalJSONObject.keySet().size()); Set<String> finalKeySet = finalJSONObject.keySet(); for (String key : finalKeySet) { JSONArray finalJSONArrayForKey = (JSONArray)finalJSONObject.get(key); assertEquals(5, finalJSONArrayForKey.size()); for (int i = 0; i < finalJSONArrayForKey.size(); i++) { JSONObject jsonObject = (JSONObject)finalJSONArrayForKey.get(i); int valueInJSON = ((int)jsonObject.values().toArray()[0]); assertTrue(valueInJSON >= Integer.parseInt(key) * 100); assertTrue(valueInJSON < (Integer.parseInt(key)+1) * 100); } } } @Test public void testFilterPlacesRandomly__when_only_few_places_per_key() { JSONObject initialJSONObject = new JSONObject(); JSONArray jsonArrayForKey1 = new JSONArray(); for (int i = 0; i < 100; i++) { JSONObject jsonObjectForArray = new JSONObject(); jsonObjectForArray.put(String.valueOf(i), i); jsonArrayForKey1.add(jsonObjectForArray); } initialJSONObject.put("0", jsonArrayForKey1); JSONArray jsonArrayForKey2 = new JSONArray(); for (int i = 0; i < 4; i++) { JSONObject jsonObjectForArray = new JSONObject(); jsonObjectForArray.put(String.valueOf(i), i); jsonArrayForKey2.add(jsonObjectForArray); } initialJSONObject.put("1", jsonArrayForKey2); JSONArray jsonArrayForKey3 = new JSONArray(); for (int i = 0; i < 4; i++) { JSONObject jsonObjectForArray = new JSONObject(); jsonObjectForArray.put(String.valueOf(i), i); jsonArrayForKey3.add(jsonObjectForArray); } initialJSONObject.put("2", jsonArrayForKey3); // Let's test now BoxRouteWorker boxRouteWorker = new BoxRouteWorker(); JSONObject finalJSONObject = boxRouteWorker.filterPlacesRandomly(initialJSONObject, 100, new ArrayList<String>()); assertEquals(3, finalJSONObject.keySet().size()); Set<String> finalKeySet = finalJSONObject.keySet(); assertEquals(92, ((JSONArray)finalJSONObject.get("0")).size()); assertEquals(4, ((JSONArray)finalJSONObject.get("1")).size()); assertEquals(4, ((JSONArray)finalJSONObject.get("2")).size()); } }
apache-2.0
LuckyMagpie/Cumulus
app/src/main/java/com/ecaresoft/cumulus/models/MPermitHospital.java
462
package com.ecaresoft.cumulus.models; /** * Created by erodriguez on 09/10/2015. */ public class MPermitHospital { private String id; private String nombre; public MPermitHospital(){} public void setId(String id) { this.id = id; } public String getId() { return id; } public void setNombre(String nombre) { this.nombre = nombre; } public String getNombre() { return nombre; } }
apache-2.0
mini2Dx/mini2Dx
core/src/main/java/org/mini2Dx/core/Logger.java
1177
/******************************************************************************* * Copyright 2019 See AUTHORS file * * 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.mini2Dx.core; /** * Interface for game/application logging */ public interface Logger { int LOG_NONE = 0; int LOG_DEBUG = 3; int LOG_INFO = 2; int LOG_ERROR = 1; void info(String tag, String message); void debug(String tag, String message); void error(String tag, String message); void error(String tag, String message, Exception e); void setLoglevel(int loglevel); }
apache-2.0
sandeep-n/incubator-apex-malhar
library/src/main/java/org/apache/apex/malhar/lib/wal/WAL.java
2864
/** * 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.apex.malhar.lib.wal; import java.io.IOException; import com.datatorrent.netlet.util.Slice; /** * This interface represents a write ahead log that can be used by operator. * the WAL is split into two interfaces, a WALWriter which allows writing * data, and WALReader which provides iterator like interface to read entries * written to the WAL. * * @param <READER> Type of WAL Reader * @param <WRITER> WAL Pointer Type. */ public interface WAL<READER extends WAL.WALReader, WRITER extends WAL.WALWriter> { void setup(); void teardown(); void beforeCheckpoint(long window); void committed(long window); READER getReader(); WRITER getWriter(); /** * Provides iterator like interface to read entries from the WAL. * @param <P> type of Pointer in the WAL */ interface WALReader<P> { /** * Seek to middle of the WAL. This is used primarily during recovery, * when we need to start recovering data from middle of WAL file. */ void seek(P pointer) throws IOException; /** * Returns the next entry from WAL. It returns null if data isn't available. * @return next entry when available; null otherwise. */ Slice next() throws IOException; /** * Returns the start pointer from which data is available to read.<br/> * WAL Writer supports purging of aged data so the start pointer will change over time. * * @return the start pointer from which the data is available to read. */ P getStartPointer(); } /** * Provide method to write entries to the WAL. * @param <P> type of Pointer in the WAL */ interface WALWriter<P> { /** * Write an entry to the WAL */ int append(Slice entry) throws IOException; /** * * @return current pointer in the WAL. */ P getPointer(); /** * Deletes the WAL data till the given pointer.<br/> * * @param pointer pointer in the WAL * @throws IOException */ void delete(P pointer) throws IOException; } }
apache-2.0
JAVA201708/Homework
201709/20170907/Team1/SunHongJiang/works/work03/Client.java
3309
public class Client { public static void main(String[] args) { PhoneFactory pf = new PhoneFactory(); pf.setName("富士康"); pf.setAddress("昆山市富士康路"); pf.setEmail("abc@foxcon.com"); pf.produce(); System.out.println("--------上转型后--------"); Factory f = pf; f.setName("淳华科技"); f.setAddress("昆山市市后街"); f.setEmail("abc@flexium.com"); f.produce(); System.out.println("--------下转型后--------"); PhoneFactory pfx = (PhoneFactory) f; System.out.println("--------多态性--------"); Factory x = null; x = getInstance(1); x.setName("其然软件"); x.setAddress("昆山市震川路"); x.setEmail("abc@cheersoftware.com"); x.produce(); } public static Factory getInstance(int flag) { return flag == 0 ? new PhoneFactory() : new ShoesFactory(); } } class Factory { private String name; private String address; private String email; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Product produce() { return null; } } class PhoneFactory extends Factory { @Override public Product produce() { System.out.println("工厂名称:" + super.getName() + ",地址:" + super.getAddress() + ",电子邮箱:" + super.getEmail()); Phone p = new Phone(); p.setName("iPhone"); p.setId(8); p.setBrand("苹果"); p.setNumber(110); p.call(); return p; } } class ShoesFactory extends Factory { @Override public Product produce() { System.out.println("工厂名称:" + super.getName() + ",地址:" + super.getAddress() + ",电子邮箱:" + super.getEmail()); Shoes s = new Shoes(); s.setName("KOBE"); s.setId(11); s.setBrand("Nike"); s.setSize(40); s.wear(); return s; } } class Product { private String name; private int id; private String brand; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getBrand() { return this.brand; } public void setBrand(String brand) { this.brand = brand; } } class Phone extends Product { private int number; public int getNumber() { return this.number; } public void setNumber(int number) { this.number = number; } public void call() { System.out.println("生产了一批" + this.getBrand() + super.getName() + super.getId() + "手机,并拨打号码:" + getNumber() + "进行测试"); } } class Shoes extends Product { private int size; public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } public void wear() { System.out.println("生产了一批" + super.getBrand() + super.getName() + super.getId() + "鞋子,鞋子尺码是:" + getSize()); } }
apache-2.0
forgeide/forgeide
src/main/java/ch/iserver/ace/net/InvitationPort.java
1625
/* * $Id$ * * ace - a collaborative editor * Copyright (C) 2005 Mark Bigler, Simon Raess, Lukas Zbinden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package ch.iserver.ace.net; /** * An InvitationPort is passed from the collaboration layer to the network * layer whenever the publisher invites a user. The port allows the network * layer to return the response of the invitation request to the * collaboration layer of the publisher. */ public interface InvitationPort { /** * The user that is to be invited. * * @return the invited user */ RemoteUserProxy getUser(); /** * Notifies the collaboration layer that the invitation was accepted * by the invited user. * * @param connection the connection to the invited participant */ void accept(ParticipantConnection connection); /** * Notifies the collaboration layer that the invitation has been * rejected by the invited user. */ void reject(); }
apache-2.0
Codetail/Mover
app/src/main/java/io/codetail/fragments/WatchMeRecycleFragment.java
5247
package io.codetail.fragments; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.telly.mrvector.MrVector; import butterknife.ButterKnife; import codetail.graphics.drawables.DrawableHelper; import codetail.utils.ThemeUtils; import codetail.utils.ViewUtils; import codetail.widget.FloatingActionButton; import io.codetail.WatchMeActivity; import io.codetail.adapters.WatchMeAdapterNew; import io.codetail.recycle.DividerDecoration; import io.codetail.recycle.ItemClickSupport; import io.codetail.utils.ScrollManager; import io.codetail.watchme.R; import static android.support.v7.widget.LinearLayoutManager.VERTICAL; public abstract class WatchMeRecycleFragment extends BaseWatchMeFragment implements ItemClickSupport.OnItemClickListener, ItemClickSupport.OnItemLongClickListener{ private WatchMeAdapterNew mWatchMeAdapter; private ScrollManager mScrollManager; private RecyclerView mRecycleView; private ProgressBar mContentProgress; private final View.OnClickListener mScrollToTopClick = new View.OnClickListener() { @Override public void onClick(View v) { scrollToTop(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWatchMeAdapter = new WatchMeAdapterNew(WatchMeAdapterNew.generateKey(this)); if(savedInstanceState != null) { mWatchMeAdapter.onRestoreInstanceState(savedInstanceState); } } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_watchme, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecycleView = ButterKnife.findById(view, R.id.recycler_view); mContentProgress = ButterKnife.findById(view, R.id.content_progress); FloatingActionButton scrollUpFab = ButterKnife.findById(view, R.id.fab_scroll_up); scrollUpFab.setOnClickListener(mScrollToTopClick); WatchMeActivity context = getWatchMeActivity(); mWatchMeAdapter.initResources(context); Drawable drawable = MrVector.inflate(getResources(), R.drawable.ic_arrow_scroll_to_top); DrawableHelper.setTint(drawable, ThemeUtils.getThemeColor(context, R.attr.fabIconColor)); scrollUpFab.setActionIcon(drawable); ItemClickSupport itemClickSupport = ItemClickSupport.addTo(mRecycleView); itemClickSupport.setOnItemClickListener(this); itemClickSupport.setOnItemLongClickListener(this); ViewGroup toolbarWrapper = (ViewGroup) context.getToolbar().getParent(); mScrollManager = new ScrollManager(toolbarWrapper, scrollUpFab); mRecycleView.setVerticalScrollBarEnabled(true); mRecycleView.addItemDecoration(new DividerDecoration(context)); mRecycleView.setOnScrollListener(mScrollManager); mRecycleView.setHasFixedSize(false); mRecycleView.setLayoutManager(new LinearLayoutManager(context, VERTICAL, false)); mRecycleView.setAdapter(mWatchMeAdapter); showContent(); } public void scrollToTop(){ mRecycleView.scrollToPosition(0); mScrollManager.showToolbar(); mScrollManager.hideFab(); } @Override public void onResume() { super.onResume(); mWatchMeAdapter.notifyDataSetChanged(); } public void showProgress(){ ViewUtils.setVisibilityWithGoneFlag(mRecycleView, false); ViewUtils.setVisibilityWithGoneFlag(mContentProgress, true); } public void showContent(){ ViewUtils.setVisibilityWithGoneFlag(mRecycleView, true); ViewUtils.setVisibilityWithGoneFlag(mContentProgress, false); mScrollManager.toggleScrollUp(mRecycleView); } public boolean isProgressVisible(){ return false; } public WatchMeAdapterNew getWatchMeAdapter() { return mWatchMeAdapter; } public ScrollManager getScrollManager() { return mScrollManager; } public RecyclerView getRecycleView() { return mRecycleView; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mWatchMeAdapter.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); if(mRecycleView != null) { mRecycleView.setOnScrollListener(null); mScrollManager = null; ItemClickSupport.removeFrom(mRecycleView); } } @Override public void onItemClick(RecyclerView parent, View view, int position, long id) { } @Override public boolean onItemLongClick(RecyclerView parent, View view, int position, long id) { return false; } }
apache-2.0
rahulnusiss/PRMS_Android
app/src/main/java/sg/edu/nus/iss/phoenix/authenticate/android/controller/LoginController.java
1485
package sg.edu.nus.iss.phoenix.authenticate.android.controller; import android.content.Intent; import android.os.Bundle; import sg.edu.nus.iss.phoenix.authenticate.android.delegate.LoginDelegate; import sg.edu.nus.iss.phoenix.authenticate.android.ui.LoginScreen; import sg.edu.nus.iss.phoenix.core.android.controller.ControlFactory; import sg.edu.nus.iss.phoenix.core.android.ui.MainScreen; import sg.edu.nus.iss.phoenix.core.android.controller.MainController; public class LoginController { // Tag for logging. private static final String TAG = LoginController.class.getName(); private LoginScreen loginScreen; public void onDisplay(LoginScreen loginScreen) { this.loginScreen = loginScreen; } public void login(String userName, String password) { loginScreen.showLoadingIndicator(); // Below comment should be removed after connection with backend //new LoginDelegate(this).execute(userName, password); // Below line should be removed after connection with backend loggedIn(true, userName); } public void loggedIn(boolean success, String username) { loginScreen.hideLoadingIndicator(); if (!success) { loginScreen.showErrorMessage(); return; } ControlFactory.getMainController().startUseCase(username); } public void logout() { Intent intent = new Intent(MainController.getApp(), LoginScreen.class); MainController.displayScreen(intent); } }
apache-2.0
Squeegee/batik
sources/org/apache/batik/transcoder/TranscodingHints.java
5049
/* 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.batik.transcoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * The <code>TranscodingHints</code> class defines a way to pass * transcoding parameters or options to any transcoders. * * @author <a href="mailto:Thierry.Kormann@sophia.inria.fr">Thierry Kormann</a> * @version $Id$ */ public class TranscodingHints extends HashMap { /** * Constructs a new empty <code>TranscodingHints</code>. */ public TranscodingHints() { this(null); } /** * Constructs a new <code>TranscodingHints</code> with keys and values * initialized from the specified Map object (which may be null). * * @param init a map of key/value pairs to initialize the hints * or null if the object should be empty */ public TranscodingHints(Map init) { super(7); if (init != null) { putAll(init); } } /** * Returns <code>true</code> if this <code>TranscodingHints</code> contains a * mapping for the specified key, false otherwise. * * @param key key whose present in this <code>TranscodingHints</code> * is to be tested. * @exception ClassCastException key is not of type * <code>TranscodingHints.Key</code> */ public boolean containsKey(Object key) { return super.containsKey(key); } /** * Returns the value to which the specified key is mapped. * * @param key a trancoding hint key * @exception ClassCastException key is not of type * <code>TranscodingHints.Key</code> */ public Object get(Object key) { return super.get(key); } /** * Maps the specified <code>key</code> to the specified <code>value</code> * in this <code>TranscodingHints</code> object. * * @param key the trancoding hint key. * @param value the trancoding hint value. * @exception IllegalArgumentException value is not * appropriate for the specified key. * @exception ClassCastException key is not of type * <code>TranscodingHints.Key</code> */ public Object put(Object key, Object value) { if (!((Key) key).isCompatibleValue(value)) { throw new IllegalArgumentException(value+ " incompatible with "+ key); } return super.put(key, value); } /** * Removes the key and its corresponding value from this * <code>TranscodingHints</code> object. * * @param key the trancoding hints key that needs to be removed * @exception ClassCastException key is not of type * <code>TranscodingHints.Key</code> */ public Object remove(Object key) { return super.remove(key); } /** * Copies all of the keys and corresponding values from the * specified <code>TranscodingHints</code> object to this * <code>TranscodingHints</code> object. */ public void putAll(TranscodingHints hints) { super.putAll(hints); } /** * Copies all of the mappings from the specified <code>Map</code> * to this <code>TranscodingHints</code>. * * @param m mappings to be stored in this <code>TranscodingHints</code>. * @exception ClassCastException key is not of type * <code>TranscodingHints.Key</code> */ public void putAll(Map m) { if (m instanceof TranscodingHints) { putAll(((TranscodingHints) m)); } else { Iterator iter = m.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); put(entry.getKey(), entry.getValue()); } } } /** * Defines the base type of all keys used to control various * aspects of the transcoding operations. */ public abstract static class Key { /** * Constructs a key. */ protected Key() { } /** * Returns true if the specified object is a valid value for * this key, false otherwise. */ public abstract boolean isCompatibleValue(Object val); } }
apache-2.0
Ariah-Group/Continuity
src/main/java/org/kuali/continuity/plan/service/CriticalCentralApplicationService.java
1218
// // Copyright 2011 Kuali Foundation, Inc. Licensed under the // Educational Community 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.opensource.org/licenses/ecl2.php // // 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.kuali.continuity.plan.service; import java.util.List; import org.kuali.continuity.plan.domain.CriticalCentralApplication; import org.kuali.continuity.service.BaseService; public interface CriticalCentralApplicationService extends BaseService { public void create(CriticalCentralApplication obj); public void update(CriticalCentralApplication obj); public void updateList(List<CriticalCentralApplication> objs); public void delete(int id); public CriticalCentralApplication getById(int id); public List<CriticalCentralApplication> getListByOwnerId(int ownerId); }
apache-2.0
mapr/impala
thirdparty/hive-0.12.0-cdh5.1.2/src/metastore/src/java/org/apache/hadoop/hive/metastore/RetryingHMSHandler.java
6852
/** * 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.hive.metastore; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.common.classification.InterfaceAudience; import org.apache.hadoop.hive.common.classification.InterfaceStability; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; @InterfaceAudience.Private @InterfaceStability.Evolving public class RetryingHMSHandler implements InvocationHandler { private static final Log LOG = LogFactory.getLog(RetryingHMSHandler.class); private final IHMSHandler base; private final MetaStoreInit.MetaStoreInitData metaStoreInitData = new MetaStoreInit.MetaStoreInitData(); private final HiveConf hiveConf; protected RetryingHMSHandler(final HiveConf hiveConf, final String name) throws MetaException { this.hiveConf = hiveConf; // This has to be called before initializing the instance of HMSHandler init(); this.base = new HiveMetaStore.HMSHandler(name, hiveConf); } public static IHMSHandler getProxy(HiveConf hiveConf, String name) throws MetaException { RetryingHMSHandler handler = new RetryingHMSHandler(hiveConf, name); return (IHMSHandler) Proxy.newProxyInstance( RetryingHMSHandler.class.getClassLoader(), new Class[] { IHMSHandler.class }, handler); } private void init() throws MetaException { // Using the hook on startup ensures that the hook always has priority // over settings in *.xml. The thread local conf needs to be used because at this point // it has already been initialized using hiveConf. MetaStoreInit.updateConnectionURL(hiveConf, getConf(), null, metaStoreInitData); } private void initMS() { base.setConf(getConf()); } @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { Object ret = null; boolean gotNewConnectUrl = false; boolean reloadConf = HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF); int retryInterval = HiveConf.getIntVar(hiveConf, HiveConf.ConfVars.HMSHANDLERINTERVAL); int retryLimit = HiveConf.getIntVar(hiveConf, HiveConf.ConfVars.HMSHANDLERATTEMPTS); if (reloadConf) { MetaStoreInit.updateConnectionURL(hiveConf, getConf(), null, metaStoreInitData); } int retryCount = 0; // Exception caughtException = null; Throwable caughtException = null; while (true) { try { if (reloadConf || gotNewConnectUrl) { initMS(); } ret = method.invoke(base, args); break; } catch (javax.jdo.JDOException e) { caughtException = e; } catch (UndeclaredThrowableException e) { if (e.getCause() != null) { if (e.getCause() instanceof javax.jdo.JDOException) { // Due to reflection, the jdo exception is wrapped in // invocationTargetException caughtException = e.getCause(); } else if (e.getCause() instanceof MetaException && e.getCause().getCause() != null && e.getCause().getCause() instanceof javax.jdo.JDOException) { // The JDOException may be wrapped further in a MetaException caughtException = e.getCause().getCause(); } else { LOG.error(ExceptionUtils.getStackTrace(e.getCause())); throw e.getCause(); } } else { LOG.error(ExceptionUtils.getStackTrace(e)); throw e; } } catch (InvocationTargetException e) { if (e.getCause() instanceof javax.jdo.JDOException) { // Due to reflection, the jdo exception is wrapped in // invocationTargetException caughtException = e.getCause(); } else if (e.getCause() instanceof NoSuchObjectException) { String methodName = method.getName(); if (!methodName.startsWith("get_table") && !methodName.startsWith("get_partition")) { LOG.error(ExceptionUtils.getStackTrace(e.getCause())); } throw e.getCause(); } else if (e.getCause() instanceof MetaException && e.getCause().getCause() != null && e.getCause().getCause() instanceof javax.jdo.JDOException) { // The JDOException may be wrapped further in a MetaException caughtException = e.getCause().getCause(); } else { LOG.error(ExceptionUtils.getStackTrace(e.getCause())); throw e.getCause(); } } if (retryCount >= retryLimit) { LOG.error("HMSHandler Fatal error: " + ExceptionUtils.getStackTrace(caughtException)); // Since returning exceptions with a nested "cause" can be a problem in // Thrift, we are stuffing the stack trace into the message itself. throw new MetaException(ExceptionUtils.getStackTrace(caughtException)); } assert (retryInterval >= 0); retryCount++; LOG.error( String.format( "Retrying HMSHandler after %d ms (attempt %d of %d)", retryInterval, retryCount, retryLimit) + " with error: " + ExceptionUtils.getStackTrace(caughtException)); Thread.sleep(retryInterval); // If we have a connection error, the JDO connection URL hook might // provide us with a new URL to access the datastore. String lastUrl = MetaStoreInit.getConnectionURL(getConf()); gotNewConnectUrl = MetaStoreInit.updateConnectionURL(hiveConf, getConf(), lastUrl, metaStoreInitData); } return ret; } public Configuration getConf() { return hiveConf; } }
apache-2.0
tsegismont/vertx-hawkular-metrics
src/main/java/io/vertx/ext/hawkular/impl/CounterPoint.java
1202
/* * Copyright 2015 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.hawkular.impl; /** * A counter {@link DataPoint}. Counters are used when we are more interested in changes of the values, rather than in * the value themselves (e.g. number of requests processed since startup). * * @author Thomas Segismont */ public class CounterPoint extends DataPoint { private final long value; public CounterPoint(String name, long timestamp, long value) { super(name, timestamp); this.value = value; } public Long getValue() { return value; } @Override public String toString() { return "CounterPoint{" + "name=" + getName() + ", timestamp=" + getTimestamp() + ", value=" + value + '}'; } }
apache-2.0
estatio/estatio
estatioapp/app/src/main/java/org/estatio/module/capex/app/CodaMappingMenu.java
910
package org.estatio.module.capex.app; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainServiceLayout; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.SemanticsOf; import org.estatio.module.capex.imports.CodaMappingFraManager; @DomainService(nature = NatureOfService.VIEW_MENU_ONLY, objectType = "org.estatio.capex.dom.coda.CodaMappingMenu") @DomainServiceLayout( named = "Payments", menuBar = DomainServiceLayout.MenuBar.PRIMARY, menuOrder = "70.6" ) public class CodaMappingMenu { @Action(semantics = SemanticsOf.SAFE) @ActionLayout(cssClassFa = "map-o") public CodaMappingFraManager allCodaMappingsFra() { return new CodaMappingFraManager(); } }
apache-2.0
KAMP-Research/KAMP
bundles/Toometa/toometa.requirements/src/requirements/impl/SystemRequirementImpl.java
754
/** */ package requirements.impl; import org.eclipse.emf.ecore.EClass; import requirements.RequirementsPackage; import requirements.SystemRequirement; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>System Requirement</b></em>'. * <!-- end-user-doc --> * * @generated */ public abstract class SystemRequirementImpl extends RequirementImpl implements SystemRequirement { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SystemRequirementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RequirementsPackage.Literals.SYSTEM_REQUIREMENT; } } //SystemRequirementImpl
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/logging/LogManager/Utils.java
1805
/* * 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.harmony.test.func.api.java.util.logging.LogManager; import java.util.Enumeration; import java.util.Properties; import java.util.logging.LogManager; import org.apache.harmony.share.Result; /* * 25.10.2005 */ class Utils { public static LogManager getLogManager() { LogManager lm = LogManager.getLogManager(); lm.reset(); return lm; } static int verifyLogManager(Properties props) { LogManager lm = LogManager.getLogManager(); Enumeration e = props.propertyNames(); boolean failed = false; while (e.hasMoreElements()) { String elem = (String) e.nextElement(); if (!props.getProperty(elem).equals(lm.getProperty(elem))) { failed = true; System.err.println(elem + ": " + props.getProperty(elem) + " != " + lm.getProperty(elem)); } } return failed ? Result.FAIL : Result.PASS; } }
apache-2.0
webfirmframework/wff
wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/images/MapTag.java
2698
/* * Copyright 2014-2022 Web Firm Framework * * 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 WFF */ package com.webfirmframework.wffweb.tag.html.images; import java.io.Serial; import java.util.logging.Logger; import com.webfirmframework.wffweb.settings.WffConfiguration; import com.webfirmframework.wffweb.tag.html.AbstractHtml; import com.webfirmframework.wffweb.tag.html.attribute.core.AbstractAttribute; import com.webfirmframework.wffweb.tag.html.core.PreIndexedTagName; import com.webfirmframework.wffweb.tag.html.identifier.GlobalAttributable; import com.webfirmframework.wffweb.tag.html.identifier.MapTagAttributable; /** * This class represents &lt;map&gt; tag in html * * @author WFF * @since 1.0.0 * @version 1.0.0 * */ public class MapTag extends AbstractHtml { @Serial private static final long serialVersionUID = 1_0_0L; private static final Logger LOGGER = Logger.getLogger(MapTag.class.getName()); private static final PreIndexedTagName PRE_INDEXED_TAG_NAME; static { PRE_INDEXED_TAG_NAME = (PreIndexedTagName.MAP); } { init(); } /** * @param base i.e. parent tag of this tag * @param attributes An array of {@code AbstractAttribute} * * @since 1.0.0 */ public MapTag(final AbstractHtml base, final AbstractAttribute... attributes) { super(PRE_INDEXED_TAG_NAME, base, attributes); if (WffConfiguration.isDirectionWarningOn()) { warnForUnsupportedAttributes(attributes); } } private static void warnForUnsupportedAttributes(final AbstractAttribute... attributes) { for (final AbstractAttribute abstractAttribute : attributes) { if (!(abstractAttribute != null && (abstractAttribute instanceof MapTagAttributable || abstractAttribute instanceof GlobalAttributable))) { LOGGER.warning(abstractAttribute + " is not an instance of MapTagAttribute"); } } } /** * invokes only once per object * * @author WFF * @since 1.0.0 */ protected void init() { // to override and use this method } }
apache-2.0
elastic/elasticsearch-hadoop
qa/kerberos/src/itest/java/org/elasticsearch/hadoop/qa/kerberos/LocalKdc.java
2729
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.hadoop.qa.kerberos; import java.io.File; import org.junit.rules.ExternalResource; public class LocalKdc extends ExternalResource { /** * When set true in System properties, we should try seeing if the KDC is up and we're just missing the KRB5.CONF file. * Useful for running the test suite in an IDE. */ private static final String AUTO_SENSE_KDC = "test.kdc.autosense"; private static final String KRB_CONF = "java.security.krb5.conf"; private boolean sensedInstall = false; @Override protected void before() throws Throwable { boolean autoSense = Boolean.parseBoolean(System.getProperty(AUTO_SENSE_KDC, "false")); // Check krb5.conf file if (System.getProperty(KRB_CONF) == null) { // Tests that use this need to have a local kdc running. Check to see if there's a fixture near by. File fixtureDir = new File("build/fixtures/kdcFixture"); if (autoSense && new File(fixtureDir, "pid").exists()) { // Is KDC running but we don't have the setting? sensedInstall = true; File confFile = new File(fixtureDir, "krb5.conf"); System.setProperty(KRB_CONF, confFile.getAbsolutePath()); System.out.printf("Automatically sensed running KDC and configuration located at [%s].%n", confFile.getAbsolutePath()); } else { throw new IllegalStateException("Cannot run test that requires local kerberos instance running"); } } System.out.printf("Using KDC Configuration [%s].%n", System.getProperty(KRB_CONF)); } @Override protected void after() { if (sensedInstall) { // If we found the fixture on our own, reset the kerberos settings to the way they were. System.clearProperty(KRB_CONF); sensedInstall = false; } } }
apache-2.0
tomitribe/crest
tomitribe-crest-arthur-extension/src/main/java/org/tomitribe/crest/arthur/CrestExtension.java
8844
/* * 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.tomitribe.crest.arthur; import org.apache.geronimo.arthur.spi.ArthurExtension; import org.apache.geronimo.arthur.spi.model.ClassReflectionModel; import org.tomitribe.crest.api.Command; import org.tomitribe.crest.api.Editor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Stream; import static java.util.Collections.emptyList; import static java.util.Collections.list; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; public class CrestExtension implements ArthurExtension { @Override public void execute(final Context context) { final boolean alreadyScanned = Boolean.parseBoolean(context.getProperty("tomitribe.crest.useInPlaceRegistrations")); if (alreadyScanned) { doRegisters(context, doLoadCrestTxt("crest-commands.txt"), doLoadCrestTxt("crest-editors.txt")); return; } final Predicate<String> extensionFilter = context.createIncludesExcludes("tomitribe.crest.command.", PredicateType.STARTS_WITH); final Predicate<String> editorsFilter = context.createIncludesExcludes("tomitribe.crest.editors.", PredicateType.STARTS_WITH); final Collection<Method> commands = context.findAnnotatedMethods(Command.class); final List<String> commandsAndInterceptors = toClasses(context, commands) .filter(extensionFilter) .collect(toList()); final List<String> editors = findEditors(context) .filter(editorsFilter) .collect(toList()); doRegisters(context, commandsAndInterceptors, editors); } private void doRegisters(final Context context, final List<String> commandsAndInterceptors, final List<String> editors) { registerReflection(context, commandsAndInterceptors); registerConstructorReflection(context, editors); if (!editors.isEmpty()) { // uses a static block so init at runtime registerEditorsLoader(context, editors); registerCommandsLoader(context, // ensure editors are loaded early add EditorLoader in this SPI registration Stream.concat(Stream.of("org.tomitribe.crest.EditorLoader"), commandsAndInterceptors.stream()) .collect(toList())); context.register(toClassReflection("org.tomitribe.crest.EditorLoader")); } else { registerCommandsLoader(context, commandsAndInterceptors); } } private void registerEditorsLoader(final Context context, final List<String> keptClasses) { context.addNativeImageOption("-H:TomitribeCrestEditors=" + dump( Paths.get(requireNonNull(context.getProperty("workingDirectory"), "workingDirectory property")), "crest-editors.txt", String.join("\n", keptClasses))); } private void registerCommandsLoader(final Context context, final List<String> keptClasses) { context.addNativeImageOption("-H:TomitribeCrestCommands=" + dump( Paths.get(requireNonNull(context.getProperty("workingDirectory"), "workingDirectory property")), "crest-commands.txt", String.join("\n", keptClasses))); } private void registerConstructorReflection(final Context context, final List<String> classes) { classes.stream() .map(this::toConstructorModel) .forEach(context::register); } private void registerReflection(final Context context, final List<String> classes) { classes.stream() .map(this::toModel) .forEach(context::register); } private String dump(final Path workDir, final String name, final String value) { if (!java.nio.file.Files.isDirectory(workDir)) { try { java.nio.file.Files.createDirectories(workDir); } catch (final IOException e) { throw new IllegalStateException(e); } } final Path out = workDir.resolve(name); try { Files.write( out, value.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new IllegalStateException(e); } return out.toAbsolutePath().toString(); } private Stream<String> findEditors(final Context context) { // normally we would need context.findImplementations(Editor.class).stream() but since it is // a standard SPI, graal can do it alone so don't do it twice return context.findAnnotatedClasses(Editor.class).stream() .distinct() .map(Class::getName) .sorted(); } private Stream<String> toClasses(final Context context, final Collection<Method> commands) { return commands.stream() .flatMap(m -> Stream.concat( findInterceptors(m), Stream.of(m.getDeclaringClass()))) .distinct() .flatMap(context::findHierarchy) .distinct() // hierarchy can overlap but doing 2 distincts we have less classes to handle overall .map(Class::getName) .sorted(); } private Stream<Class<?>> findInterceptors(final Method method) { return Stream.of(method.getAnnotation(Command.class).interceptedBy()); } private ClassReflectionModel toClassReflection(final String name) { final ClassReflectionModel model = new ClassReflectionModel(); model.setName(name); return model; } private ClassReflectionModel toConstructorModel(final String name) { final ClassReflectionModel model = new ClassReflectionModel(); model.setName(name); model.setAllPublicConstructors(true); return model; } private ClassReflectionModel toModel(final String name) { final ClassReflectionModel model = new ClassReflectionModel(); model.setName(name); model.setAllPublicMethods(true); model.setAllPublicConstructors(true); return model; } private List<String> doLoadCrestTxt(final String name) { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { return list(loader.getResources(name)).stream() .flatMap(url -> { try (final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { return reader.lines() .filter(it -> !it.isEmpty() && !it.startsWith("#")) .map(it -> { try { return loader.loadClass(it).getName(); } catch (final Error | Exception e) { return null; } }) .filter(Objects::nonNull) .collect(toList()) // materialize before we close the stream .stream(); } catch (final IOException ioe) { return Stream.empty(); } }) .collect(toList()); } catch (final IOException e) { return emptyList(); } } }
apache-2.0
zhoudan1989/menasor
menasor-demo/src/main/java/org.zhou.menasor.menasor.demo/consumer/DemoConsumerTest.java
483
package org.zhou.menasor.menasor.demo.consumer; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by DT283 on 2017/7/3. */ public class DemoConsumerTest { public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"consumer.xml"}); context.start(); while (true) { Thread.sleep(10 * 60 * 1000); } } }
apache-2.0
einerc/RevisaPeru
src/RevisaPeru/GUI/JInFrmMark.java
6224
/* * 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 RevisaPeru.GUI; import RevisaPeru.BusinessLogic.*; import RevisaPeru.BusinessLogic.BLO.*; import RevisaPeru.Entities.*; import java.util.List; import javax.swing.table.DefaultTableModel; /** * * @author user */ public class JInFrmMark extends javax.swing.JInternalFrame { //Instanciamos al la logica del Negocio IMarkBL markBL; /* Patrón Singleton*/ private static JInFrmMark nonInstance = null; public static JInFrmMark getIntance() { //analizamos si el objecto no a sido creado es decir si no existe if(nonInstance==null) // si no se ah instanciado la clase entonces creamos el objeto nonInstance = new JInFrmMark(); return nonInstance; } /*End Singleton*/ /* Variables locales*/ DefaultTableModel markTableModel; //Object marks[]= new Object[3]; /** * Creates new form JInFrmMark */ private JInFrmMark() { initComponents(); //Inicializamos la instancia del BL markBL= new MarkBL(); markTableModel= new DefaultTableModel(); mostrarDatos(); } private void mostrarDatos() { List<Mark> marks= markBL.getAllFromMark(); markTableModel.addColumn("id"); markTableModel.addColumn("Nombre"); markTableModel.addColumn("Descripción"); for(Mark m : marks) { markTableModel.addRow(m.toArrayObject()); } this.title =markBL.getFromMarkById(3).toString(); jTableMarks.setModel(markTableModel); } /** * 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() { jPnDetails = new javax.swing.JPanel(); jScrollPMarks = new javax.swing.JScrollPane(); jTableMarks = new javax.swing.JTable(); jPnFields = new javax.swing.JPanel(); setClosable(true); setIconifiable(true); setMaximizable(true); setResizable(true); setTitle("Gestion de Marcas"); jPnDetails.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Listado de Marcas")); jTableMarks.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPMarks.setViewportView(jTableMarks); javax.swing.GroupLayout jPnDetailsLayout = new javax.swing.GroupLayout(jPnDetails); jPnDetails.setLayout(jPnDetailsLayout); jPnDetailsLayout.setHorizontalGroup( jPnDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPnDetailsLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPMarks, javax.swing.GroupLayout.PREFERRED_SIZE, 675, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(19, Short.MAX_VALUE)) ); jPnDetailsLayout.setVerticalGroup( jPnDetailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPnDetailsLayout.createSequentialGroup() .addComponent(jScrollPMarks, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 22, Short.MAX_VALUE)) ); jPnFields.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "Registrar Nueva Marca")); javax.swing.GroupLayout jPnFieldsLayout = new javax.swing.GroupLayout(jPnFields); jPnFields.setLayout(jPnFieldsLayout); jPnFieldsLayout.setHorizontalGroup( jPnFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPnFieldsLayout.setVerticalGroup( jPnFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 131, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPnDetails, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPnFields, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPnFields, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPnDetails, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPnDetails; private javax.swing.JPanel jPnFields; private javax.swing.JScrollPane jScrollPMarks; private javax.swing.JTable jTableMarks; // End of variables declaration//GEN-END:variables }
apache-2.0
Gaduo/hapi-fhir
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/util/SubscriptionsRequireManualActivationInterceptorDstu2.java
5436
package ca.uhn.fhir.jpa.util; import static org.apache.commons.lang3.StringUtils.isNotBlank; /* * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2016 University Health Network * %% * 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% */ import org.hl7.fhir.instance.model.api.IIdType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import ca.uhn.fhir.jpa.dao.FhirResourceDaoSubscriptionDstu2; import ca.uhn.fhir.jpa.dao.IFhirResourceDao; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; import ca.uhn.fhir.model.dstu2.resource.Subscription; import ca.uhn.fhir.model.dstu2.valueset.SubscriptionChannelTypeEnum; import ca.uhn.fhir.model.dstu2.valueset.SubscriptionStatusEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.CoverageIgnore; /** * Interceptor which requires newly created {@link Subscription subscriptions} to be in * {@link SubscriptionStatusEnum#REQUESTED} state and prevents clients from changing the status. */ public class SubscriptionsRequireManualActivationInterceptorDstu2 extends InterceptorAdapter { public static final ResourceMetadataKeyEnum<Object> ALLOW_STATUS_CHANGE = new ResourceMetadataKeyEnum<Object>(FhirResourceDaoSubscriptionDstu2.class.getName() + "_ALLOW_STATUS_CHANGE") { private static final long serialVersionUID = 1; @CoverageIgnore @Override public Object get(IResource theResource) { throw new UnsupportedOperationException(); } @CoverageIgnore @Override public void put(IResource theResource, Object theObject) { throw new UnsupportedOperationException(); } }; @Autowired @Qualifier("mySubscriptionDaoDstu2") private IFhirResourceDao<Subscription> myDao; @Override public void incomingRequestPreHandled(RestOperationTypeEnum theOperation, ActionRequestDetails theProcessedRequest) { switch (theOperation) { case CREATE: case UPDATE: if (theProcessedRequest.getResourceType().equals("Subscription")) { verifyStatusOk(theOperation, theProcessedRequest); } break; default: break; } } public void setDao(IFhirResourceDao<Subscription> theDao) { myDao = theDao; } private void verifyStatusOk(RestOperationTypeEnum theOperation, ActionRequestDetails theRequestDetails) { Subscription subscription = (Subscription) theRequestDetails.getResource(); SubscriptionStatusEnum newStatus = subscription.getStatusElement().getValueAsEnum(); if (newStatus == SubscriptionStatusEnum.REQUESTED || newStatus == SubscriptionStatusEnum.OFF) { return; } if (newStatus == null) { String actualCode = subscription.getStatusElement().getValueAsString(); throw new UnprocessableEntityException("Can not " + theOperation.getCode() + " resource: Subscription.status must be populated" + ((isNotBlank(actualCode)) ? " (invalid value " + actualCode + ")" : "")); } IIdType requestId = theRequestDetails.getId(); if (requestId != null && requestId.hasIdPart()) { Subscription existing; try { existing = myDao.read(requestId, null); SubscriptionStatusEnum existingStatus = existing.getStatusElement().getValueAsEnum(); if (existingStatus != newStatus) { verifyActiveStatus(subscription, newStatus, existingStatus); } } catch (ResourceNotFoundException e) { verifyActiveStatus(subscription, newStatus, null); } } else { verifyActiveStatus(subscription, newStatus, null); } } private void verifyActiveStatus(Subscription theSubscription, SubscriptionStatusEnum newStatus, SubscriptionStatusEnum theExistingStatus) { SubscriptionChannelTypeEnum channelType = theSubscription.getChannel().getTypeElement().getValueAsEnum(); if (channelType == null) { throw new UnprocessableEntityException("Subscription.channel.type must be populated"); } if (channelType == SubscriptionChannelTypeEnum.WEBSOCKET) { return; } if (theExistingStatus != null) { throw new UnprocessableEntityException("Subscription.status can not be changed from " + describeStatus(theExistingStatus) + " to " + describeStatus(newStatus)); } throw new UnprocessableEntityException("Subscription.status must be '" + SubscriptionStatusEnum.OFF.getCode() + "' or '" + SubscriptionStatusEnum.REQUESTED.getCode() + "' on a newly created subscription"); } private String describeStatus(SubscriptionStatusEnum existingStatus) { String existingStatusString; if (existingStatus != null) { existingStatusString = '\'' + existingStatus.getCode() + '\''; } else { existingStatusString = "null"; } return existingStatusString; } }
apache-2.0
oleg-pogiba/andcore
app/src/main/java/com/pogiba/core/data/SyncService.java
3080
package com.pogiba.core.data; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.IBinder; import javax.inject.Inject; import rx.Observer; import rx.Subscription; import rx.schedulers.Schedulers; import timber.log.Timber; import com.pogiba.core.CoreApplication; import com.pogiba.core.data.model.Ribot; import com.pogiba.core.util.AndroidComponentUtil; import com.pogiba.core.util.NetworkUtil; import com.pogiba.core.util.RxUtil; public class SyncService extends Service { @Inject DataManager mDataManager; private Subscription mSubscription; public static Intent getStartIntent(Context context) { return new Intent(context, SyncService.class); } public static boolean isRunning(Context context) { return AndroidComponentUtil.isServiceRunning(context, SyncService.class); } @Override public void onCreate() { super.onCreate(); CoreApplication.get(this).getComponent().inject(this); } @Override public int onStartCommand(Intent intent, int flags, final int startId) { Timber.i("Starting sync..."); if (!NetworkUtil.isNetworkConnected(this)) { Timber.i("Sync canceled, connection not available"); AndroidComponentUtil.toggleComponent(this, SyncOnConnectionAvailable.class, true); stopSelf(startId); return START_NOT_STICKY; } RxUtil.unsubscribe(mSubscription); mSubscription = mDataManager.syncRibots() .subscribeOn(Schedulers.io()) .subscribe(new Observer<Ribot>() { @Override public void onCompleted() { Timber.i("Synced successfully!"); stopSelf(startId); } @Override public void onError(Throwable e) { Timber.w(e, "Error syncing."); stopSelf(startId); } @Override public void onNext(Ribot ribot) { } }); return START_STICKY; } @Override public void onDestroy() { if (mSubscription != null) mSubscription.unsubscribe(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } public static class SyncOnConnectionAvailable extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) && NetworkUtil.isNetworkConnected(context)) { Timber.i("Connection is now available, triggering sync..."); AndroidComponentUtil.toggleComponent(context, this.getClass(), false); context.startService(getStartIntent(context)); } } } }
apache-2.0
inbloom/secure-data-service
tools/csv2xml/src/org/slc/sli/sample/entitiesR1/DisciplineIncidentIdentityType.java
3977
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // 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: 2012.12.05 at 01:12:38 PM EST // package org.slc.sli.sample.entitiesR1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; /** * Encapsulates the possible attributes that can be used to lookup the identity of discipline incidents. * * <p>Java class for DisciplineIncidentIdentityType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DisciplineIncidentIdentityType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="IncidentIdentifier" type="{http://ed-fi.org/0100}IncidentIdentifier"/> * &lt;choice maxOccurs="unbounded"> * &lt;element name="StateOrganizationId" type="{http://ed-fi.org/0100}IdentificationCode"/> * &lt;element name="EducationOrgIdentificationCode" type="{http://ed-fi.org/0100}EducationOrgIdentificationCode" maxOccurs="unbounded"/> * &lt;/choice> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DisciplineIncidentIdentityType", propOrder = { "incidentIdentifier", "stateOrganizationIdOrEducationOrgIdentificationCode" }) public class DisciplineIncidentIdentityType { @XmlElement(name = "IncidentIdentifier", required = true) protected String incidentIdentifier; @XmlElements({ @XmlElement(name = "EducationOrgIdentificationCode", type = EducationOrgIdentificationCode.class), @XmlElement(name = "StateOrganizationId", type = String.class) }) protected List<Object> stateOrganizationIdOrEducationOrgIdentificationCode; /** * Gets the value of the incidentIdentifier property. * * @return * possible object is * {@link String } * */ public String getIncidentIdentifier() { return incidentIdentifier; } /** * Sets the value of the incidentIdentifier property. * * @param value * allowed object is * {@link String } * */ public void setIncidentIdentifier(String value) { this.incidentIdentifier = value; } /** * Gets the value of the stateOrganizationIdOrEducationOrgIdentificationCode 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 stateOrganizationIdOrEducationOrgIdentificationCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStateOrganizationIdOrEducationOrgIdentificationCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EducationOrgIdentificationCode } * {@link String } * * */ public List<Object> getStateOrganizationIdOrEducationOrgIdentificationCode() { if (stateOrganizationIdOrEducationOrgIdentificationCode == null) { stateOrganizationIdOrEducationOrgIdentificationCode = new ArrayList<Object>(); } return this.stateOrganizationIdOrEducationOrgIdentificationCode; } }
apache-2.0
JimSeker/speech
eclipse/speech2textdemo2/gen/edu/cs4730/spk2txtDemo2/R.java
1900
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package edu.cs4730.spk2txtDemo2; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f070004; public static final int button1=0x7f070001; public static final int container=0x7f070000; public static final int horizontalScrollView1=0x7f070002; public static final int log=0x7f070003; } public static final class layout { public static final int activity_main=0x7f030000; public static final int fragment_main=0x7f030001; } public static final class menu { public static final int main=0x7f060000; } public static final class string { public static final int action_settings=0x7f050004; public static final int app_name=0x7f050001; public static final int hello=0x7f050000; public static final int hello_blank_fragment=0x7f050005; public static final int hello_world=0x7f050003; public static final int title_activity_main=0x7f050002; } }
apache-2.0
java110/MicroCommunity
java110-utils/src/main/java/com/java110/utils/constant/ServiceCodePurchaseApplyDetailConstant.java
767
package com.java110.utils.constant; /** * 订单明细常量类 * Created by wuxw on 2017/5/20. */ public class ServiceCodePurchaseApplyDetailConstant { /** * 添加 订单明细 */ public static final String ADD_PURCHASEAPPLYDETAIL = "purchaseApplyDetail.savePurchaseApplyDetail"; /** * 修改 订单明细 */ public static final String UPDATE_PURCHASEAPPLYDETAIL = "purchaseApplyDetail.updatePurchaseApplyDetail"; /** * 删除 订单明细 */ public static final String DELETE_PURCHASEAPPLYDETAIL = "purchaseApplyDetail.deletePurchaseApplyDetail"; /** * 查询 订单明细 */ public static final String LIST_PURCHASEAPPLYDETAILS = "purchaseApplyDetail.listPurchaseApplyDetails"; }
apache-2.0
mchaston/OakFunds
src/org/chaston/oakfunds/ledger/ui/BankAccountCreateServlet.java
3643
/* * Copyright 2014 Miles Chaston * * 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.chaston.oakfunds.ledger.ui; import com.google.inject.Inject; import org.chaston.oakfunds.account.AccountCode; import org.chaston.oakfunds.account.AccountCodeManager; import org.chaston.oakfunds.ledger.BankAccount; import org.chaston.oakfunds.ledger.BankAccountType; import org.chaston.oakfunds.ledger.LedgerManager; import org.chaston.oakfunds.storage.StorageException; import org.chaston.oakfunds.util.JSONUtils; import org.chaston.oakfunds.util.ParameterHandler; import org.chaston.oakfunds.util.RequestHandler; import org.json.simple.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * TODO(mchaston): write JavaDocs */ class BankAccountCreateServlet extends HttpServlet { private static final ParameterHandler<String> PARAMETER_TITLE = ParameterHandler.stringParameter("title") .required("A title must be supplied.") .build(); private static final ParameterHandler<Integer> PARAMETER_ACCOUNT_CODE_ID = ParameterHandler.intParameter("account_code_id") .required("An account code must be supplied.") .build(); private static final ParameterHandler<BankAccountType> PARAMETER_BANK_ACCOUNT_TYPE = ParameterHandler.identifiableParameter("bank_account_type", BankAccountType.getIdentifiableSource()) .required("A bank account type must be supplied.") .build(); private final RequestHandler requestHandler; private final AccountCodeManager accountCodeManager; private final LedgerManager ledgerManager; @Inject BankAccountCreateServlet(RequestHandler requestHandler, AccountCodeManager accountCodeManager, LedgerManager ledgerManager) { this.requestHandler = requestHandler; this.accountCodeManager = accountCodeManager; this.ledgerManager = ledgerManager; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final JSONObject jsonRequest = JSONUtils.readRequest(request, "create bank account"); BankAccount bankAccount = requestHandler.handleTransaction(request, response, new RequestHandler.Action<BankAccount>() { @Override public BankAccount doAction(HttpServletRequest request) throws StorageException, ServletException { AccountCode accountCode = accountCodeManager.getAccountCode( PARAMETER_ACCOUNT_CODE_ID.parse(jsonRequest)); return ledgerManager.createBankAccount(accountCode, PARAMETER_TITLE.parse(jsonRequest), PARAMETER_BANK_ACCOUNT_TYPE.parse(jsonRequest)); } }); // Write result to response. response.setContentType("application/json"); JSONUtils.writeJSONString(response.getWriter(), bankAccount); } }
apache-2.0
IstiN/android_xcore
xcore-library/xcore/src/main/java/org/apache/commons/codec/internal/binary/StringUtils.java
16510
/* * 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.commons.codec.internal.binary; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import org.apache.commons.codec.internal.CharEncoding; import org.apache.commons.codec.internal.Charsets; /** * Converts String to and from bytes using the encodings required by the Java specification. These encodings are * specified in <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html"> * Standard charsets</a>. * * <p>This class is immutable and thread-safe.</p> * * @see CharEncoding * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @version $Id: StringUtils.java 1435550 2013-01-19 14:09:52Z tn $ * @since 1.4 */ public class StringUtils { /** * Calls {@link String#getBytes(java.nio.charset.Charset)} * * @param string * The string to encode (if null, return null). * @param charset * The {@link java.nio.charset.Charset} to encode the {@code String} * @return the encoded bytes */ private static byte[] getBytes(final String string, final Charset charset) { if (string == null) { return null; } return string.getBytes(charset); } /** * Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing the result into a new * byte array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#ISO_8859_1} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesIso8859_1(final String string) { return getBytes(string, Charsets.ISO_8859_1); } /** * Encodes the given string into a sequence of bytes using the named charset, storing the result into a new byte * array. * <p> * This method catches {@link java.io.UnsupportedEncodingException} and rethrows it as {@link IllegalStateException}, which * should never happen for a required charset name. Use this method when the encoding is required to be in the JRE. * </p> * * @param string * the String to encode, may be {@code null} * @param charsetName * The name of a required {@link java.nio.charset.Charset} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws IllegalStateException * Thrown when a {@link java.io.UnsupportedEncodingException} is caught, which should never happen for a * required charset name. * @see CharEncoding * @see String#getBytes(String) */ public static byte[] getBytesUnchecked(final String string, final String charsetName) { if (string == null) { return null; } try { return string.getBytes(charsetName); } catch (final UnsupportedEncodingException e) { throw StringUtils.newIllegalStateException(charsetName, e); } } /** * Encodes the given string into a sequence of bytes using the US-ASCII charset, storing the result into a new byte * array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#US_ASCII} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUsAscii(final String string) { return getBytes(string, Charsets.US_ASCII); } /** * Encodes the given string into a sequence of bytes using the UTF-16 charset, storing the result into a new byte * array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#UTF_16} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUtf16(final String string) { return getBytes(string, Charsets.UTF_16); } /** * Encodes the given string into a sequence of bytes using the UTF-16BE charset, storing the result into a new byte * array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#UTF_16BE} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUtf16Be(final String string) { return getBytes(string, Charsets.UTF_16BE); } /** * Encodes the given string into a sequence of bytes using the UTF-16LE charset, storing the result into a new byte * array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#UTF_16LE} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUtf16Le(final String string) { return getBytes(string, Charsets.UTF_16LE); } /** * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte * array. * * @param string * the String to encode, may be {@code null} * @return encoded bytes, or {@code null} if the input string was {@code null} * @throws NullPointerException * Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> * @see #getBytesUnchecked(String, String) */ public static byte[] getBytesUtf8(final String string) { return getBytes(string, Charsets.UTF_8); } private static IllegalStateException newIllegalStateException(final String charsetName, final UnsupportedEncodingException e) { return new IllegalStateException(charsetName + ": " + e); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the given charset. * * @param bytes * The bytes to be decoded into characters * @param charset * The {@link java.nio.charset.Charset} to encode the {@code String} * @return A new <code>String</code> decoded from the specified array of bytes using the given charset, * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is * required by the Java platform specification. */ private static String newString(final byte[] bytes, final Charset charset) { return bytes == null ? null : new String(bytes, charset); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the given charset. * <p> * This method catches {@link java.io.UnsupportedEncodingException} and re-throws it as {@link IllegalStateException}, which * should never happen for a required charset name. Use this method when the encoding is required to be in the JRE. * </p> * * @param bytes * The bytes to be decoded into characters, may be {@code null} * @param charsetName * The name of a required {@link java.nio.charset.Charset} * @return A new <code>String</code> decoded from the specified array of bytes using the given charset, * or {@code null} if the input byte array was {@code null}. * @throws IllegalStateException * Thrown when a {@link java.io.UnsupportedEncodingException} is caught, which should never happen for a * required charset name. * @see CharEncoding * @see String#String(byte[], String) */ public static String newString(final byte[] bytes, final String charsetName) { if (bytes == null) { return null; } try { return new String(bytes, charsetName); } catch (final UnsupportedEncodingException e) { throw StringUtils.newIllegalStateException(charsetName, e); } } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the ISO-8859-1 charset. * * @param bytes * The bytes to be decoded into characters, may be {@code null} * @return A new <code>String</code> decoded from the specified array of bytes using the ISO-8859-1 charset, or * {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#ISO_8859_1} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringIso8859_1(final byte[] bytes) { return new String(bytes, Charsets.ISO_8859_1); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the US-ASCII charset. * * @param bytes * The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the US-ASCII charset, * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#US_ASCII} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringUsAscii(final byte[] bytes) { return new String(bytes, Charsets.US_ASCII); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16 charset. * * @param bytes * The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16 charset * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#UTF_16} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringUtf16(final byte[] bytes) { return new String(bytes, Charsets.UTF_16); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16BE charset. * * @param bytes * The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16BE charset, * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#UTF_16BE} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringUtf16Be(final byte[] bytes) { return new String(bytes, Charsets.UTF_16BE); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16LE charset. * * @param bytes * The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16LE charset, * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#UTF_16LE} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringUtf16Le(final byte[] bytes) { return new String(bytes, Charsets.UTF_16LE); } /** * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset. * * @param bytes * The bytes to be decoded into characters * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset, * or {@code null} if the input byte array was {@code null}. * @throws NullPointerException * Thrown if {@link Charsets#UTF_8} is not initialized, which should never happen since it is * required by the Java platform specification. * @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException */ public static String newStringUtf8(final byte[] bytes) { return newString(bytes, Charsets.UTF_8); } }
apache-2.0
objectos/memorabilia
src/main/java/br/com/objectos/wiki/core/attach/Mime.java
741
/* * Copyright 2013 Objectos, Fábrica de Software LTDA. * * 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 br.com.objectos.wiki.core.attach; /** * @author marcio.endo@objectos.com.br (Marcio Endo) */ public enum Mime { }
apache-2.0
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/proto/GetServiceInstanceProtocol.java
1533
/** * Copyright 2014 Cisco Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cisco.oss.foundation.directory.proto; /** * Get ServiceInstance Protocol. * * */ public class GetServiceInstanceProtocol extends Protocol { /** * */ private static final long serialVersionUID = 1L; /** * the serviceName. */ private String serviceName; /** * The instanceId. */ private String instanceId; public GetServiceInstanceProtocol(){ } public GetServiceInstanceProtocol(String serviceName, String instanceId){ this.serviceName = serviceName; this.instanceId = instanceId; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } }
apache-2.0
tjazi-com/infra_messages_router
core/src/main/java/com/tjazi/messagesrouter/core/MessagesRouterApplication.java
337
package com.tjazi.messagesrouter.core; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MessagesRouterApplication { public static void main(String[] args) { SpringApplication.run(MessagesRouterApplication.class, args); } }
apache-2.0
emakovsky/ffmpeg-android
FFmpegAndroid/src/main/java/com/github/libffmpeg/FileUtils.java
3175
package com.github.libffmpeg; import android.content.Context; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; import java.util.Map; class FileUtils { static final String ffmpegFileName = "ffmpeg"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final int EOF = -1; static boolean copyBinaryFromAssetsToData(Context context, String fileNameFromAssets, String outputFileName) { // create files directory under /data/data/package name File filesDirectory = getFilesDirectory(context); InputStream is; try { is = context.getAssets().open(fileNameFromAssets); // copy ffmpeg file from assets to files dir final FileOutputStream os = new FileOutputStream(new File(filesDirectory, outputFileName)); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n; while(EOF != (n = is.read(buffer))) { os.write(buffer, 0, n); } Util.close(os); Util.close(is); return true; } catch (IOException e) { Log.e("issue in coping binary from assets to data. ", e); } return false; } static File getFilesDirectory(Context context) { // creates files directory under data/data/package name return context.getFilesDir(); } static String getFFmpeg(Context context) { return getFilesDirectory(context).getAbsolutePath() + File.separator + FileUtils.ffmpegFileName; } static String getFFmpeg(Context context, Map<String,String> environmentVars) { String ffmpegCommand = ""; if (environmentVars != null) { for (Map.Entry<String, String> var : environmentVars.entrySet()) { ffmpegCommand += var.getKey()+"="+var.getValue()+" "; } } ffmpegCommand += getFFmpeg(context); return ffmpegCommand; } static String SHA1(String file) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); return SHA1(is); } catch (IOException e) { Log.e(e); } finally { Util.close(is); } return null; } static String SHA1(InputStream is) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; for (int read; (read = is.read(buffer)) != -1; ) { messageDigest.update(buffer, 0, read); } Formatter formatter = new Formatter(); // Convert the byte to hex format for (final byte b : messageDigest.digest()) { formatter.format("%02x", b); } return formatter.toString(); } catch (NoSuchAlgorithmException e) { Log.e(e); } catch (IOException e) { Log.e(e); } finally { Util.close(is); } return null; } }
apache-2.0
Dolodosia/java_pft_daria
sandbox/src/main/java/pl/stqa/pft/sandbox/Point.java
261
package pl.stqa.pft.sandbox; public class Point { double x; double y; public Point(double x, double y) { this.x = x; this.y = y; } public double distance(Point p) { return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); } }
apache-2.0
lifengsofts/AndroidDownloader
samples/src/main/java/com/ixuea/android/downloader/simple/domain/MyDownloadThreadInfoLocal.java
1646
package com.ixuea.android.downloader.simple.domain; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; /** * Created by ixuea(http://a.ixuea.com/3) on 17/1/22. */ @DatabaseTable(tableName = "MyDownloadThreadInfoLocal") public class MyDownloadThreadInfoLocal implements Serializable { @DatabaseField(id = true) private int id; @DatabaseField private int threadId; @DatabaseField private String downloadInfoId; private String uri; @DatabaseField private long start; @DatabaseField private long end; @DatabaseField private long progress; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getThreadId() { return threadId; } public void setThreadId(int threadId) { this.threadId = threadId; } public String getDownloadInfoId() { return downloadInfoId; } public void setDownloadInfoId(String downloadInfoId) { this.downloadInfoId = downloadInfoId; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public long getStart() { return start; } public void setStart(long start) { this.start = start; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } public long getProgress() { return progress; } public void setProgress(long progress) { this.progress = progress; } }
apache-2.0
yeleman/SNISI-droid
app/src/main/java/com/yeleman/snisidroid/SMSSentReceiver.java
2070
package com.yeleman.snisidroid; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast; public class SMSSentReceiver extends BroadcastReceiver { private static final String TAG = Constants.getLogTag("SMSSentReceiver"); private SMSUpdater mSmsUpdater; public SMSSentReceiver(SMSUpdater u) { super(); mSmsUpdater = u; Log.d(TAG, "SMSSentReceiver instanciated"); } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive SMS_SENT"); int feedback_status = Constants.SMS_UNKNOWN; String feedback_message = ""; switch (getResultCode()) { case Activity.RESULT_OK: feedback_status = Constants.SMS_SUCCESS; feedback_message = "SMS envoyé."; break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: feedback_status = Constants.SMS_ERROR; feedback_message = "Generic Failure"; break; case SmsManager.RESULT_ERROR_NO_SERVICE: feedback_status = Constants.SMS_ERROR; feedback_message = "Pas de réseau (No Service)"; break; case SmsManager.RESULT_ERROR_NULL_PDU: feedback_status = Constants.SMS_ERROR; feedback_message = "Null PDU"; break; case SmsManager.RESULT_ERROR_RADIO_OFF: feedback_status = Constants.SMS_ERROR; feedback_message = "Carte SIM désactivée."; break; default: break; } if (feedback_status == Constants.SMS_SUCCESS) { Toast.makeText(context, feedback_message, Toast.LENGTH_SHORT).show(); } Log.d(TAG, feedback_message); mSmsUpdater.gotSMSStatusUpdate(feedback_status, feedback_message); } }
apache-2.0
HaStr/kieker
kieker-common/test-gen/kieker/test/common/junit/api/jvm/TestClassLoadingRecordPropertyOrder.java
6251
/*************************************************************************** * Copyright 2015 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.test.common.junit.api.jvm; import java.nio.ByteBuffer; import org.junit.Assert; import org.junit.Test; import kieker.common.record.jvm.ClassLoadingRecord; import kieker.common.util.registry.IRegistry; import kieker.common.util.registry.Registry; import kieker.test.common.junit.AbstractKiekerTest; import kieker.test.common.junit.util.APIEvaluationFunctions; /** * Test API of {@link kieker.common.record.jvm.ClassLoadingRecord}. * * @author API Checker * * @since 1.12 */ public class TestClassLoadingRecordPropertyOrder extends AbstractKiekerTest { /** * All numbers and values must be pairwise unequal. As the string registry also uses integers, * we must guarantee this criteria by starting with 1000 instead of 0. */ /** Constant value parameter for timestamp. */ private static final long PROPERTY_TIMESTAMP = 2L; /** Constant value parameter for hostname. */ private static final String PROPERTY_HOSTNAME = "<hostname>"; /** Constant value parameter for vmName. */ private static final String PROPERTY_VM_NAME = "<vmName>"; /** Constant value parameter for totalLoadedClassCount. */ private static final long PROPERTY_TOTAL_LOADED_CLASS_COUNT = 3L; /** Constant value parameter for loadedClassCount. */ private static final int PROPERTY_LOADED_CLASS_COUNT = 1001; /** Constant value parameter for unloadedClassCount. */ private static final long PROPERTY_UNLOADED_CLASS_COUNT = 4L; /** * Empty constructor. */ public TestClassLoadingRecordPropertyOrder() { // Empty constructor for test class. } /** * Test property order processing of {@link kieker.common.record.jvm.ClassLoadingRecord} constructors and * different serialization routines. */ @Test public void testClassLoadingRecordPropertyOrder() { // NOPMD final IRegistry<String> stringRegistry = this.makeStringRegistry(); final Object[] values = { PROPERTY_TIMESTAMP, PROPERTY_HOSTNAME, PROPERTY_VM_NAME, PROPERTY_TOTAL_LOADED_CLASS_COUNT, PROPERTY_LOADED_CLASS_COUNT, PROPERTY_UNLOADED_CLASS_COUNT, }; final ByteBuffer inputBuffer = APIEvaluationFunctions.createByteBuffer(ClassLoadingRecord.SIZE, this.makeStringRegistry(), values); final ClassLoadingRecord recordInitParameter = new ClassLoadingRecord( PROPERTY_TIMESTAMP, PROPERTY_HOSTNAME, PROPERTY_VM_NAME, PROPERTY_TOTAL_LOADED_CLASS_COUNT, PROPERTY_LOADED_CLASS_COUNT, PROPERTY_UNLOADED_CLASS_COUNT ); final ClassLoadingRecord recordInitBuffer = new ClassLoadingRecord(inputBuffer, this.makeStringRegistry()); final ClassLoadingRecord recordInitArray = new ClassLoadingRecord(values); this.assertClassLoadingRecord(recordInitParameter); this.assertClassLoadingRecord(recordInitBuffer); this.assertClassLoadingRecord(recordInitArray); // test to array final Object[] valuesParameter = recordInitParameter.toArray(); Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesParameter); final Object[] valuesBuffer = recordInitBuffer.toArray(); Assert.assertArrayEquals("Result array of record initialized by buffer constructor differs from predefined array.", values, valuesBuffer); final Object[] valuesArray = recordInitArray.toArray(); Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesArray); // test write to buffer final ByteBuffer outputBufferParameter = ByteBuffer.allocate(ClassLoadingRecord.SIZE); recordInitParameter.writeBytes(outputBufferParameter, stringRegistry); Assert.assertArrayEquals("Byte buffer do not match (parameter).", inputBuffer.array(), outputBufferParameter.array()); final ByteBuffer outputBufferBuffer = ByteBuffer.allocate(ClassLoadingRecord.SIZE); recordInitParameter.writeBytes(outputBufferBuffer, stringRegistry); Assert.assertArrayEquals("Byte buffer do not match (buffer).", inputBuffer.array(), outputBufferBuffer.array()); final ByteBuffer outputBufferArray = ByteBuffer.allocate(ClassLoadingRecord.SIZE); recordInitParameter.writeBytes(outputBufferArray, stringRegistry); Assert.assertArrayEquals("Byte buffer do not match (array).", inputBuffer.array(), outputBufferArray.array()); } /** * Assertions for ClassLoadingRecord. */ private void assertClassLoadingRecord(final ClassLoadingRecord record) { Assert.assertEquals("'timestamp' value assertion failed.", record.getTimestamp(), PROPERTY_TIMESTAMP); Assert.assertEquals("'hostname' value assertion failed.", record.getHostname(), PROPERTY_HOSTNAME); Assert.assertEquals("'vmName' value assertion failed.", record.getVmName(), PROPERTY_VM_NAME); Assert.assertEquals("'totalLoadedClassCount' value assertion failed.", record.getTotalLoadedClassCount(), PROPERTY_TOTAL_LOADED_CLASS_COUNT); Assert.assertEquals("'loadedClassCount' value assertion failed.", record.getLoadedClassCount(), PROPERTY_LOADED_CLASS_COUNT); Assert.assertEquals("'unloadedClassCount' value assertion failed.", record.getUnloadedClassCount(), PROPERTY_UNLOADED_CLASS_COUNT); } /** * Build a populated string registry for all tests. */ private IRegistry<String> makeStringRegistry() { final IRegistry<String> stringRegistry = new Registry<String>(); // get registers string and returns their ID stringRegistry.get(PROPERTY_HOSTNAME); stringRegistry.get(PROPERTY_VM_NAME); return stringRegistry; } }
apache-2.0
reactor/reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoCacheTime.java
11859
/* * Copyright (c) 2017-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.time.Duration; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.function.Function; import java.util.function.Supplier; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.core.Exceptions; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import reactor.util.Logger; import reactor.util.Loggers; import reactor.util.annotation.Nullable; import reactor.util.context.Context; import reactor.util.context.ContextView; /** * An operator that caches the value from a source Mono with a TTL, after which the value * expires and the next subscription will trigger a new source subscription. * * @author Simon Baslé */ class MonoCacheTime<T> extends InternalMonoOperator<T, T> implements Runnable { private static final Duration DURATION_INFINITE = Duration.ofMillis(Long.MAX_VALUE); private static final Logger LOGGER = Loggers.getLogger(MonoCacheTime.class); final Function<? super Signal<T>, Duration> ttlGenerator; final Scheduler clock; volatile Signal<T> state; static final AtomicReferenceFieldUpdater<MonoCacheTime, Signal> STATE = AtomicReferenceFieldUpdater.newUpdater(MonoCacheTime.class, Signal.class, "state"); static final Signal<?> EMPTY = new ImmutableSignal<>(Context.empty(), SignalType.ON_NEXT, null, null, null); MonoCacheTime(Mono<? extends T> source, Duration ttl, Scheduler clock) { super(source); Objects.requireNonNull(ttl, "ttl must not be null"); Objects.requireNonNull(clock, "clock must not be null"); this.ttlGenerator = ignoredSignal -> ttl; this.clock = clock; @SuppressWarnings("unchecked") Signal<T> state = (Signal<T>) EMPTY; this.state = state; } MonoCacheTime(Mono<? extends T> source) { this(source, sig -> DURATION_INFINITE, Schedulers.immediate()); } MonoCacheTime(Mono<? extends T> source, Function<? super Signal<T>, Duration> ttlGenerator, Scheduler clock) { super(source); this.ttlGenerator = ttlGenerator; this.clock = clock; @SuppressWarnings("unchecked") Signal<T> state = (Signal<T>) EMPTY; this.state = state; } MonoCacheTime(Mono<? extends T> source, Function<? super T, Duration> valueTtlGenerator, Function<Throwable, Duration> errorTtlGenerator, Supplier<Duration> emptyTtlGenerator, Scheduler clock) { super(source); Objects.requireNonNull(valueTtlGenerator, "valueTtlGenerator must not be null"); Objects.requireNonNull(errorTtlGenerator, "errorTtlGenerator must not be null"); Objects.requireNonNull(emptyTtlGenerator, "emptyTtlGenerator must not be null"); Objects.requireNonNull(clock, "clock must not be null"); this.ttlGenerator = sig -> { if (sig.isOnNext()) return valueTtlGenerator.apply(sig.get()); if (sig.isOnError()) return errorTtlGenerator.apply(sig.getThrowable()); return emptyTtlGenerator.get(); }; this.clock = clock; @SuppressWarnings("unchecked") Signal<T> emptyState = (Signal<T>) EMPTY; this.state = emptyState; } public void run() { LOGGER.debug("expired {}", state); @SuppressWarnings("unchecked") Signal<T> emptyState = (Signal<T>) EMPTY; state = emptyState; } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { CacheMonoSubscriber<T> inner = new CacheMonoSubscriber<>(actual); actual.onSubscribe(inner); for(;;){ Signal<T> state = this.state; if (state == EMPTY || state instanceof CoordinatorSubscriber) { boolean subscribe = false; CoordinatorSubscriber<T> coordinator; if (state == EMPTY) { coordinator = new CoordinatorSubscriber<>(this); if (!STATE.compareAndSet(this, EMPTY, coordinator)) { continue; } subscribe = true; } else { coordinator = (CoordinatorSubscriber<T>) state; } if (coordinator.add(inner)) { if (inner.isCancelled()) { coordinator.remove(inner); } else { inner.coordinator = coordinator; } if (subscribe) { source.subscribe(coordinator); } break; } } else { //state is an actual signal, cached if (state.isOnNext()) { inner.complete(state.get()); } else if (state.isOnComplete()) { inner.onComplete(); } else { inner.onError(state.getThrowable()); } break; } } return null; } @Override public Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final class CoordinatorSubscriber<T> implements InnerConsumer<T>, Signal<T> { final MonoCacheTime<T> main; volatile Subscription subscription; static final AtomicReferenceFieldUpdater<CoordinatorSubscriber, Subscription> S = AtomicReferenceFieldUpdater.newUpdater(CoordinatorSubscriber.class, Subscription.class, "subscription"); volatile Operators.MonoSubscriber<T, T>[] subscribers; static final AtomicReferenceFieldUpdater<CoordinatorSubscriber, Operators.MonoSubscriber[]> SUBSCRIBERS = AtomicReferenceFieldUpdater.newUpdater(CoordinatorSubscriber.class, Operators.MonoSubscriber[].class, "subscribers"); @SuppressWarnings("unchecked") CoordinatorSubscriber(MonoCacheTime<T> main) { this.main = main; this.subscribers = EMPTY; } /** * unused in this context as the {@link Signal} interface is only * implemented for use in the main's STATE compareAndSet. */ @Override public Throwable getThrowable() { throw new UnsupportedOperationException("illegal signal use"); } /** * unused in this context as the {@link Signal} interface is only * implemented for use in the main's STATE compareAndSet. */ @Override public Subscription getSubscription() { throw new UnsupportedOperationException("illegal signal use"); } /** * unused in this context as the {@link Signal} interface is only * implemented for use in the main's STATE compareAndSet. */ @Override public T get() { throw new UnsupportedOperationException("illegal signal use"); } /** * unused in this context as the {@link Signal} interface is only * implemented for use in the main's STATE compareAndSet. */ @Override public SignalType getType() { throw new UnsupportedOperationException("illegal signal use"); } /** * unused in this context as the {@link Signal} interface is only * implemented for use in the main's STATE compareAndSet. */ @Override public ContextView getContextView() { throw new UnsupportedOperationException("illegal signal use: getContextView"); } final boolean add(Operators.MonoSubscriber<T, T> toAdd) { for (; ; ) { Operators.MonoSubscriber<T, T>[] a = subscribers; if (a == TERMINATED) { return false; } int n = a.length; @SuppressWarnings("unchecked") Operators.MonoSubscriber<T, T>[] b = new Operators.MonoSubscriber[n + 1]; System.arraycopy(a, 0, b, 0, n); b[n] = toAdd; if (SUBSCRIBERS.compareAndSet(this, a, b)) { return true; } } } final void remove(Operators.MonoSubscriber<T, T> toRemove) { for (; ; ) { Operators.MonoSubscriber<T, T>[] a = subscribers; if (a == TERMINATED || a == EMPTY) { return; } int n = a.length; int j = -1; for (int i = 0; i < n; i++) { if (a[i] == toRemove) { j = i; break; } } if (j < 0) { return; } Operators.MonoSubscriber<?, ?>[] b; if (n == 1) { b = EMPTY; } else { b = new Operators.MonoSubscriber<?, ?>[n - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, n - j - 1); } if (SUBSCRIBERS.compareAndSet(this, a, b)) { //no particular cleanup here for the EMPTY case, we don't cancel the // source because a new subscriber could come in before the coordinator // is terminated. return; } } } @Override public void onSubscribe(Subscription s) { if (Operators.validate(subscription, s)) { subscription = s; s.request(Long.MAX_VALUE); } } @SuppressWarnings("unchecked") private void signalCached(Signal<T> signal) { Signal<T> signalToPropagate = signal; if (STATE.compareAndSet(main, this, signal)) { Duration ttl = null; try { ttl = main.ttlGenerator.apply(signal); } catch (Throwable generatorError) { signalToPropagate = Signal.error(generatorError); STATE.set(main, signalToPropagate); if (signal.isOnError()) { //noinspection ThrowableNotThrown Exceptions.addSuppressed(generatorError, signal.getThrowable()); } } if (ttl != null) { if (ttl.isZero()) { //immediate cache clear main.run(); } else if (!ttl.equals(DURATION_INFINITE)) { main.clock.schedule(main, ttl.toNanos(), TimeUnit.NANOSECONDS); } //else TTL is Long.MAX_VALUE, schedule nothing but still cache } else { //error during TTL generation, signal != updatedSignal, aka dropped if (signal.isOnNext()) { Operators.onNextDropped(signal.get(), currentContext()); } //if signal.isOnError(), avoid dropping the error. it is not really dropped but already suppressed //in all cases, unless nextDropped hook throws, immediate cache clear main.run(); } } for (Operators.MonoSubscriber<T, T> inner : SUBSCRIBERS.getAndSet(this, TERMINATED)) { if (signalToPropagate.isOnNext()) { inner.complete(signalToPropagate.get()); } else if (signalToPropagate.isOnError()) { inner.onError(signalToPropagate.getThrowable()); } else { inner.onComplete(); } } } @Override public void onNext(T t) { if (main.state != this) { Operators.onNextDroppedMulticast(t, subscribers); return; } signalCached(Signal.next(t)); } @Override public void onError(Throwable t) { if (main.state != this) { Operators.onErrorDroppedMulticast(t, subscribers); return; } signalCached(Signal.error(t)); } @Override public void onComplete() { signalCached(Signal.complete()); } @Override public Context currentContext() { return Operators.multiSubscribersContext(subscribers); } @Nullable @Override public Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return null; } private static final Operators.MonoSubscriber[] TERMINATED = new Operators.MonoSubscriber[0]; private static final Operators.MonoSubscriber[] EMPTY = new Operators.MonoSubscriber[0]; } static final class CacheMonoSubscriber<T> extends Operators.MonoSubscriber<T, T> { CoordinatorSubscriber<T> coordinator; CacheMonoSubscriber(CoreSubscriber<? super T> actual) { super(actual); } @Override public void cancel() { super.cancel(); CoordinatorSubscriber<T> coordinator = this.coordinator; if (coordinator != null) { coordinator.remove(this); } } @Override public Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } } }
apache-2.0
Justson/AgentWeb
agentweb-core/src/main/java/com/just/agentweb/AgentWebView.java
20333
/* * Copyright (C) Justson(https://github.com/Justson/AgentWeb) * * 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.just.agentweb; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityManager; import android.webkit.JsPromptResult; import android.webkit.WebBackForwardList; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import org.json.JSONObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * @author cenxiaozhong * @since 1.0.0 */ public class AgentWebView extends LollipopFixedWebView { private static final String TAG = AgentWebView.class.getSimpleName(); private Map<String, JsCallJava> mJsCallJavas; private Map<String, String> mInjectJavaScripts; private FixedOnReceivedTitle mFixedOnReceivedTitle; private boolean mIsInited; private Boolean mIsAccessibilityEnabledOriginal; public AgentWebView(Context context) { this(context, null); } public AgentWebView(Context context, AttributeSet attrs) { super(context, attrs); removeSearchBoxJavaBridge(); mIsInited = true; mFixedOnReceivedTitle = new FixedOnReceivedTitle(); } /** * 经过大量的测试,按照以下方式才能保证JS脚本100%注入成功: * 1、在第一次loadUrl之前注入JS(在addJavascriptInterface里面注入即可,setWebViewClient和setWebChromeClient要在addJavascriptInterface之前执行); * 2、在webViewClient.onPageStarted中都注入JS; * 3、在webChromeClient.onProgressChanged中都注入JS,并且不能通过自检查(onJsPrompt里面判断)JS是否注入成功来减少注入JS的次数,因为网页中的JS可以同时打开多个url导致无法控制检查的准确性; * * @deprecated Android 4.2.2及以上版本的 addJavascriptInterface 方法已经解决了安全问题,如果不使用“网页能将JS函数传到Java层”功能,不建议使用该类,毕竟系统的JS注入效率才是最高的; */ @Override @Deprecated public final void addJavascriptInterface(Object interfaceObj, String interfaceName) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { super.addJavascriptInterface(interfaceObj, interfaceName); Log.i(TAG, "注入"); return; } else { Log.i(TAG, "use mJsCallJavas:" + interfaceName); } LogUtils.i(TAG, "addJavascriptInterface:" + interfaceObj + " interfaceName:" + interfaceName); if (mJsCallJavas == null) { mJsCallJavas = new HashMap<String, JsCallJava>(); } mJsCallJavas.put(interfaceName, new JsCallJava(interfaceObj, interfaceName)); injectJavaScript(); if (LogUtils.isDebug()) { Log.d(TAG, "injectJavaScript, addJavascriptInterface.interfaceObj = " + interfaceObj + ", interfaceName = " + interfaceName); } addJavascriptInterfaceSupport(interfaceObj, interfaceName); } protected void addJavascriptInterfaceSupport(Object interfaceObj, String interfaceName) { } @Override public final void setWebChromeClient(WebChromeClient client) { AgentWebChrome mAgentWebChrome = new AgentWebChrome(this); mAgentWebChrome.setDelegate(client); mFixedOnReceivedTitle.setWebChromeClient(client); super.setWebChromeClient(mAgentWebChrome); setWebChromeClientSupport(mAgentWebChrome); } protected final void setWebChromeClientSupport(WebChromeClient client) { } @Override public final void setWebViewClient(WebViewClient client) { AgentWebClient mAgentWebClient = new AgentWebClient(this); mAgentWebClient.setDelegate(client); super.setWebViewClient(mAgentWebClient); setWebViewClientSupport(mAgentWebClient); } public final void setWebViewClientSupport(WebViewClient client) { } @Override public void destroy() { setVisibility(View.GONE); if (mJsCallJavas != null) { mJsCallJavas.clear(); } if (mInjectJavaScripts != null) { mInjectJavaScripts.clear(); } removeAllViewsInLayout(); fixedStillAttached(); releaseConfigCallback(); if (mIsInited) { resetAccessibilityEnabled(); LogUtils.i(TAG, "destroy web"); super.destroy(); } } @Override public void clearHistory() { if (mIsInited) { super.clearHistory(); } } public static Pair<Boolean, String> isWebViewPackageException(Throwable e) { String messageCause = e.getCause() == null ? e.toString() : e.getCause().toString(); String trace = Log.getStackTraceString(e); if (trace.contains("android.content.pm.PackageManager$NameNotFoundException") || trace.contains("java.lang.RuntimeException: Cannot load WebView") || trace.contains("android.webkit.WebViewFactory$MissingWebViewPackageException: Failed to load WebView provider: No WebView installed")) { LogUtils.safeCheckCrash(TAG, "isWebViewPackageException", e); return new Pair<Boolean, String>(true, "WebView load failed, " + messageCause); } return new Pair<Boolean, String>(false, messageCause); } @Override public void setOverScrollMode(int mode) { try { super.setOverScrollMode(mode); } catch (Throwable e) { Pair<Boolean, String> pair = isWebViewPackageException(e); if (pair.first) { Toast.makeText(getContext(), pair.second, Toast.LENGTH_SHORT).show(); destroy(); } else { throw e; } } } @Override public boolean isPrivateBrowsingEnabled() { if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && getSettings() == null) { return false; // getSettings().isPrivateBrowsingEnabled() } else { return super.isPrivateBrowsingEnabled(); } } /** * 添加并注入JavaScript脚本(和“addJavascriptInterface”注入对象的注入时机一致,100%能注入成功); * 注意:为了做到能100%注入,需要在注入的js中自行判断对象是否已经存在(如:if (typeof(window.Android) = 'undefined')); * * @param javaScript */ public void addInjectJavaScript(String javaScript) { if (mInjectJavaScripts == null) { mInjectJavaScripts = new HashMap<String, String>(); } mInjectJavaScripts.put(String.valueOf(javaScript.hashCode()), javaScript); injectExtraJavaScript(); } private void injectJavaScript() { for (Map.Entry<String, JsCallJava> entry : mJsCallJavas.entrySet()) { this.loadUrl(buildNotRepeatInjectJS(entry.getKey(), entry.getValue().getPreloadInterfaceJs())); } } private void injectExtraJavaScript() { for (Map.Entry<String, String> entry : mInjectJavaScripts.entrySet()) { this.loadUrl(buildNotRepeatInjectJS(entry.getKey(), entry.getValue())); } } /** * 构建一个“不会重复注入”的js脚本; * * @param key * @param js * @return */ public String buildNotRepeatInjectJS(String key, String js) { String obj = String.format("__injectFlag_%1$s__", key); StringBuilder sb = new StringBuilder(); sb.append("javascript:try{(function(){if(window."); sb.append(obj); sb.append("){console.log('"); sb.append(obj); sb.append(" has been injected');return;}window."); sb.append(obj); sb.append("=true;"); sb.append(js); sb.append("}())}catch(e){console.warn(e)}"); return sb.toString(); } /** * 构建一个“带try catch”的js脚本; * * @param js * @return */ public String buildTryCatchInjectJS(String js) { StringBuilder sb = new StringBuilder(); sb.append("javascript:try{"); sb.append(js); sb.append("}catch(e){console.warn(e)}"); return sb.toString(); } public static class AgentWebClient extends MiddlewareWebClientBase { private AgentWebView mAgentWebView; private AgentWebClient(AgentWebView agentWebView) { this.mAgentWebView = agentWebView; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (mAgentWebView.mJsCallJavas != null) { mAgentWebView.injectJavaScript(); if (LogUtils.isDebug()) { Log.d(TAG, "injectJavaScript, onPageStarted.url = " + view.getUrl()); } } if (mAgentWebView.mInjectJavaScripts != null) { mAgentWebView.injectExtraJavaScript(); } mAgentWebView.mFixedOnReceivedTitle.onPageStarted(); mAgentWebView.fixedAccessibilityInjectorExceptionForOnPageFinished(url); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mAgentWebView.mFixedOnReceivedTitle.onPageFinished(view); if (LogUtils.isDebug()) { Log.d(TAG, "onPageFinished.url = " + view.getUrl()); } } } public static class AgentWebChrome extends MiddlewareWebChromeBase { private AgentWebView mAgentWebView; private AgentWebChrome(AgentWebView agentWebView) { this.mAgentWebView = agentWebView; } @Override public void onReceivedTitle(WebView view, String title) { this.mAgentWebView.mFixedOnReceivedTitle.onReceivedTitle(); super.onReceivedTitle(view, title); } @Override public void onProgressChanged(WebView view, int newProgress) { if (this.mAgentWebView.mJsCallJavas != null) { this.mAgentWebView.injectJavaScript(); if (LogUtils.isDebug()) { Log.d(TAG, "injectJavaScript, onProgressChanged.newProgress = " + newProgress + ", url = " + view.getUrl()); } } if (this.mAgentWebView.mInjectJavaScripts != null) { this.mAgentWebView.injectExtraJavaScript(); } super.onProgressChanged(view, newProgress); } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { Log.i(TAG, "onJsPrompt:" + url + " message:" + message + " d:" + defaultValue + " "); if (this.mAgentWebView.mJsCallJavas != null && JsCallJava.isSafeWebViewCallMsg(message)) { JSONObject jsonObject = JsCallJava.getMsgJSONObject(message); String interfacedName = JsCallJava.getInterfacedName(jsonObject); if (interfacedName != null) { JsCallJava mJsCallJava = this.mAgentWebView.mJsCallJavas.get(interfacedName); if (mJsCallJava != null) { result.confirm(mJsCallJava.call(view, jsonObject)); } } return true; } else { return super.onJsPrompt(view, url, message, defaultValue, result); } } } /** * 解决部分手机webView返回时不触发onReceivedTitle的问题(如:三星SM-G9008V 4.4.2); */ private static class FixedOnReceivedTitle { private WebChromeClient mWebChromeClient; private boolean mIsOnReceivedTitle; public void setWebChromeClient(WebChromeClient webChromeClient) { mWebChromeClient = webChromeClient; } public void onPageStarted() { mIsOnReceivedTitle = false; } public void onPageFinished(WebView view) { if (!mIsOnReceivedTitle && mWebChromeClient != null) { WebBackForwardList list = null; try { list = view.copyBackForwardList(); } catch (NullPointerException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } if (list != null && list.getSize() > 0 && list.getCurrentIndex() >= 0 && list.getItemAtIndex(list.getCurrentIndex()) != null) { String previousTitle = list.getItemAtIndex(list.getCurrentIndex()).getTitle(); mWebChromeClient.onReceivedTitle(view, previousTitle); } } } public void onReceivedTitle() { mIsOnReceivedTitle = true; } } // Activity在onDestory时调用webView的destroy,可以停止播放页面中的音频 private void fixedStillAttached() { // java.lang.Throwable: Error: WebView.destroy() called while still attached! // at android.webkit.WebViewClassic.destroy(WebViewClassic.java:4142) // at android.webkit.WebView.destroy(WebView.java:707) ViewParent parent = getParent(); if (parent instanceof ViewGroup) { // 由于自定义webView构建时传入了该Activity的context对象,因此需要先从父容器中移除webView,然后再销毁webView; ViewGroup mWebViewContainer = (ViewGroup) getParent(); mWebViewContainer.removeAllViewsInLayout(); } } // 解决WebView内存泄漏问题; private void releaseConfigCallback() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // JELLY_BEAN try { Field field = WebView.class.getDeclaredField("mWebViewCore"); field = field.getType().getDeclaredField("mBrowserFrame"); field = field.getType().getDeclaredField("sConfigCallback"); field.setAccessible(true); field.set(null, null); } catch (NoSuchFieldException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } catch (IllegalAccessException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // KITKAT try { Field sConfigCallback = Class.forName("android.webkit.BrowserFrame").getDeclaredField("sConfigCallback"); if (sConfigCallback != null) { sConfigCallback.setAccessible(true); sConfigCallback.set(null, null); } } catch (NoSuchFieldException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } catch (ClassNotFoundException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } catch (IllegalAccessException e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } } } /** * Android 4.4 KitKat 使用Chrome DevTools 远程调试WebView * WebView.setWebContentsDebuggingEnabled(true); * http://blog.csdn.net/t12x3456/article/details/14225235 */ @TargetApi(19) protected void trySetWebDebuggEnabled() { if (LogUtils.isDebug() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { Class<?> clazz = WebView.class; Method method = clazz.getMethod("setWebContentsDebuggingEnabled", boolean.class); method.invoke(null, true); } catch (Throwable e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } } } @TargetApi(11) protected boolean removeSearchBoxJavaBridge() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { Method method = this.getClass().getMethod("removeJavascriptInterface", String.class); method.invoke(this, "searchBoxJavaBridge_"); return true; } } catch (Exception e) { if (LogUtils.isDebug()) { e.printStackTrace(); } } return false; } protected void fixedAccessibilityInjectorException() { if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1 && mIsAccessibilityEnabledOriginal == null && isAccessibilityEnabled()) { mIsAccessibilityEnabledOriginal = true; setAccessibilityEnabled(false); } } protected void fixedAccessibilityInjectorExceptionForOnPageFinished(String url) { if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN && getSettings().getJavaScriptEnabled() && mIsAccessibilityEnabledOriginal == null && isAccessibilityEnabled()) { try { try { URLEncoder.encode(String.valueOf(new URI(url)), "utf-8"); // URLEncodedUtils.parse(new URI(url), null); // AccessibilityInjector.getAxsUrlParameterValue } catch (IllegalArgumentException e) { if ("bad parameter".equals(e.getMessage())) { mIsAccessibilityEnabledOriginal = true; setAccessibilityEnabled(false); LogUtils.safeCheckCrash(TAG, "fixedAccessibilityInjectorExceptionForOnPageFinished.url = " + url, e); } } } catch (Throwable e) { if (LogUtils.isDebug()) { LogUtils.e(TAG, "fixedAccessibilityInjectorExceptionForOnPageFinished", e); } } } } private boolean isAccessibilityEnabled() { AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); return am.isEnabled(); } private void setAccessibilityEnabled(boolean enabled) { AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); try { Method setAccessibilityState = am.getClass().getDeclaredMethod("setAccessibilityState", boolean.class); setAccessibilityState.setAccessible(true); setAccessibilityState.invoke(am, enabled); setAccessibilityState.setAccessible(false); } catch (Throwable e) { if (LogUtils.isDebug()) { LogUtils.e(TAG, "setAccessibilityEnabled", e); } } } private void resetAccessibilityEnabled() { if (mIsAccessibilityEnabledOriginal != null) { setAccessibilityEnabled(mIsAccessibilityEnabledOriginal); } } }
apache-2.0
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201306/DateTimeRangeTargetingError.java
4582
/** * DateTimeRangeTargetingError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201306; /** * Lists all date time range errors caused by associating a line item * with a targeting * expression. */ public class DateTimeRangeTargetingError extends com.google.api.ads.dfp.axis.v201306.ApiError implements java.io.Serializable { /* The error reason represented by an enum. */ private com.google.api.ads.dfp.axis.v201306.DateTimeRangeTargetingErrorReason reason; public DateTimeRangeTargetingError() { } public DateTimeRangeTargetingError( java.lang.String fieldPath, java.lang.String trigger, java.lang.String errorString, java.lang.String apiErrorType, com.google.api.ads.dfp.axis.v201306.DateTimeRangeTargetingErrorReason reason) { super( fieldPath, trigger, errorString, apiErrorType); this.reason = reason; } /** * Gets the reason value for this DateTimeRangeTargetingError. * * @return reason * The error reason represented by an enum. */ public com.google.api.ads.dfp.axis.v201306.DateTimeRangeTargetingErrorReason getReason() { return reason; } /** * Sets the reason value for this DateTimeRangeTargetingError. * * @param reason * The error reason represented by an enum. */ public void setReason(com.google.api.ads.dfp.axis.v201306.DateTimeRangeTargetingErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof DateTimeRangeTargetingError)) return false; DateTimeRangeTargetingError other = (DateTimeRangeTargetingError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(DateTimeRangeTargetingError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "DateTimeRangeTargetingError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "DateTimeRangeTargetingError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
sunshinefather/platform
src/main/java/com/platform/modules/sys/dao/AreaDao.java
341
package com.platform.modules.sys.dao; import com.platform.common.persistence.TreeDao; import com.platform.common.persistence.annotation.MyBatisDao; import com.platform.modules.sys.bean.Area; /** * 区域DAO接口 * @author sunshine * @date 2014-05-16 */ @MyBatisDao public interface AreaDao extends TreeDao<Area> { }
apache-2.0
brockhaus-gruppe/M2M_framework
m2m_base/src/main/java/de/brockhaus/m2m/handler/database/cassandra/SensorDataCassandraDAO.java
6249
package de.brockhaus.m2m.handler.database.cassandra; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import de.brockhaus.m2m.handler.database.SensorDataDAO; import de.brockhaus.m2m.message.M2MDataType; import de.brockhaus.m2m.message.M2MSensorMessage; /** * The concrete DAO for Cassandra * * The DDL for the table is: * * CREATE TABLE sensor_data ( * sensor_id text, * datatype text, * time timestamp, * string_value text, * boolean_value boolean, * float_value float, * PRIMARY KEY(sensor_id, time) * ); * * Obviously this is the most simple table design one can think of, we might change it later, when need a more * sophisticated aggregation over the time line as well as a dedicated TTL * * Regarding the table design check: * http://planetcassandra.org/getting-started-with-time-series-data-modeling/ * http://stackoverflow.com/questions/29806707/data-scheme-cassandra-using-various-data-types * http://www.datastax.com/dev/blog/advanced-time-series-with-cassandra * * TODO: configure TTL 4 individual sensors * TODO: enhance data model for hourly/daily/monthly rows * * Example config: * <bean name="cassandra-dao" class="de.brockhaus.m2m.handler.database.cassandra.SensorDataCassandraDAO" scope="singleton" init-method = "init" destroy-method = "shutDown"> <constructor-arg ref="cassandra-datasource" /> </bean> <bean name="cassandra-datasource" class="de.brockhaus.m2m.handler.database.cassandra.CassandraDataSource" scope="singleton"> <property name="hostIP"> <value>127.0.0.1</value> </property> <property name="keyspace"> <value>test</value> </property> </bean> * * Project: m2m-base * * Copyright (c) by Brockhaus Group www.brockhaus-gruppe.de * * @author mbohnen, Mar 27, 2015 * */ public class SensorDataCassandraDAO implements SensorDataDAO { private static final Logger LOG = Logger .getLogger(SensorDataCassandraDAO.class); private CassandraDataSource datasource; private Session session; public SensorDataCassandraDAO(CassandraDataSource datasource) { this.datasource = datasource; } public void insertSensorData(M2MSensorMessage data) { LOG.info("inserting"); M2MDataType type = data.getDatatype(); switch (type) { case BOOLEAN: this.insertBoolean(data); break; case FLOAT: this.insertFloat(data); break; case STRING: this.insertString(data); } } private void insertString(M2MSensorMessage data) { LOG.debug("inserting a string value"); String cql = "INSERT INTO sensor_data(SENSOR_ID, DATATYPE, TIME, STRING_VALUE) VALUES(?, ?, ?, ?)"; PreparedStatement pStat = session.prepare(cql); BoundStatement bStat = new BoundStatement(pStat); bStat.bind(data.getSensorId(), data.getDatatype().toString(), data.getTime(), data.getValue()); session.execute(bStat); } private void insertFloat(M2MSensorMessage data) { Float value = new Float(data.getValue()); LOG.debug("inserting a float value: " + value); String cql = "INSERT INTO sensor_data(SENSOR_ID, DATATYPE, TIME, FLOAT_VALUE) VALUES(?, ?, ?, ?)"; PreparedStatement pStat = session.prepare(cql); BoundStatement bStat = new BoundStatement(pStat); bStat.bind(data.getSensorId(), data.getDatatype().toString(), data.getTime(), value); session.execute(bStat); } private void insertBoolean(M2MSensorMessage data) { LOG.debug("inserting a boolean value"); String cql = "INSERT INTO sensor_data(SENSOR_ID, DATATYPE, TIME, BOOLEAN_VALUE) VALUES(?, ?, ?, ?)"; PreparedStatement pStat = session.prepare(cql); BoundStatement bStat = new BoundStatement(pStat); bStat.bind(data.getSensorId(), data.getDatatype(), data.getTime(), new Boolean(data.getValue())); session.execute(bStat); } public void bulkInsertOfSensorData(List<M2MSensorMessage> list) { for (M2MSensorMessage sensorData : list) { this.insertSensorData(sensorData); } } public List<M2MSensorMessage> findBySensorIDAndTimeInterval( String sensorId, Date from, Date to) { List<M2MSensorMessage> tos = new ArrayList<M2MSensorMessage>(); // TODO: checkout if this is necessary Timestamp fromTs = new Timestamp(from.getTime()); Timestamp toTs = new Timestamp(to.getTime()); String cql = "SELECT * FROM sensor_data WHERE SENSOR_ID = ? AND TIME > ? AND TIME < ?"; PreparedStatement pStat = session.prepare(cql); BoundStatement bStat = new BoundStatement(pStat); bStat.bind(sensorId, fromTs, toTs); ResultSet res = session.execute(bStat); for (Row row : res) { M2MSensorMessage sensorData = new M2MSensorMessage(); sensorData.setDatatype(M2MDataType.valueOf(row .getString("DATATYPE"))); sensorData.setSensorId(row.getString("SENSOR_ID")); sensorData.setTime(row.getDate("TIME")); sensorData.setValue(row.getString("VALUE")); tos.add(sensorData); } return tos; } public List<M2MSensorMessage> findByTimeInterval(Date from, Date to) { List<M2MSensorMessage> tos = new ArrayList<M2MSensorMessage>(); // TODO: checkout if this is necessary Timestamp fromTs = new Timestamp(from.getTime()); Timestamp toTs = new Timestamp(to.getTime()); String cql = "SELECT * FROM sensor_data WHERE TIME > ? AND TIME < ?"; PreparedStatement pStat = session.prepare(cql); BoundStatement bStat = new BoundStatement(pStat); bStat.bind(fromTs, toTs); ResultSet res = session.execute(bStat); for (Row row : res) { M2MSensorMessage sensorData = new M2MSensorMessage(); sensorData.setDatatype(M2MDataType.valueOf(row .getString("DATATYPE"))); sensorData.setSensorId(row.getString("SENSOR_ID")); sensorData.setTime(row.getDate("TIME")); sensorData.setValue(row.getString("VALUE")); tos.add(sensorData); } return tos; } public void init() { LOG.debug("init"); session = datasource.connect(); } // housekeeping public void shutDown() { LOG.debug("cleaning up"); this.session.close(); } }
apache-2.0