code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
package org.diorite.material.blocks.stony;
import java.util.Map;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.BlockFace;
import org.diorite.cfg.magic.MagicNumbers;
import org.diorite.material.BlockMaterialData;
import org.diorite.material.blocks.StairsMat;
import org.diorite.utils.collections.maps.CaseInsensitiveMap;
import gnu.trove.map.TByteObjectMap;
import gnu.trove.map.hash.TByteObjectHashMap;
/**
* Class representing block "RedSandstoneStairs" and all its subtypes.
*/
public class RedSandstoneStairsMat extends BlockMaterialData implements StairsMat
{
/**
* Sub-ids used by diorite/minecraft by default
*/
public static final byte USED_DATA_VALUES = 8;
/**
* Blast resistance of block, can be changed only before server start.
* Final copy of blast resistance from {@link MagicNumbers} class.
*/
public static final float BLAST_RESISTANCE = MagicNumbers.MATERIAL__RED_SANDSTONE_STAIRS__BLAST_RESISTANCE;
/**
* Hardness of block, can be changed only before server start.
* Final copy of hardness from {@link MagicNumbers} class.
*/
public static final float HARDNESS = MagicNumbers.MATERIAL__RED_SANDSTONE_STAIRS__HARDNESS;
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_EAST = new RedSandstoneStairsMat();
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_WEST = new RedSandstoneStairsMat(BlockFace.WEST, false);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_SOUTH = new RedSandstoneStairsMat(BlockFace.SOUTH, false);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_NORTH = new RedSandstoneStairsMat(BlockFace.NORTH, false);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_EAST_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.EAST, true);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_WEST_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.WEST, true);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_SOUTH_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.SOUTH, true);
public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_NORTH_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.NORTH, true);
private static final Map<String, RedSandstoneStairsMat> byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
private static final TByteObjectMap<RedSandstoneStairsMat> byID = new TByteObjectHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
protected final BlockFace face;
protected final boolean upsideDown;
@SuppressWarnings("MagicNumber")
protected RedSandstoneStairsMat()
{
super("RED_SANDSTONE_STAIRS", 180, "minecraft:red_sandstone_stairs", "EAST", (byte) 0x00);
this.face = BlockFace.EAST;
this.upsideDown = false;
}
protected RedSandstoneStairsMat(final BlockFace face, final boolean upsideDown)
{
super(RED_SANDSTONE_STAIRS_EAST.name(), RED_SANDSTONE_STAIRS_EAST.ordinal(), RED_SANDSTONE_STAIRS_EAST.getMinecraftId(), face.name() + (upsideDown ? "_UPSIDE_DOWN" : ""), StairsMat.combine(face, upsideDown));
this.face = face;
this.upsideDown = upsideDown;
}
protected RedSandstoneStairsMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final byte type, final BlockFace face, final boolean upsideDown)
{
super(enumName, id, minecraftId, maxStack, typeName, type);
this.face = face;
this.upsideDown = upsideDown;
}
@Override
public float getBlastResistance()
{
return BLAST_RESISTANCE;
}
@Override
public float getHardness()
{
return HARDNESS;
}
@Override
public boolean isUpsideDown()
{
return this.upsideDown;
}
@Override
public RedSandstoneStairsMat getUpsideDown(final boolean upsideDown)
{
return getByID(StairsMat.combine(this.face, upsideDown));
}
@Override
public RedSandstoneStairsMat getType(final BlockFace face, final boolean upsideDown)
{
return getByID(StairsMat.combine(face, upsideDown));
}
@Override
public BlockFace getBlockFacing()
{
return this.face;
}
@Override
public RedSandstoneStairsMat getBlockFacing(final BlockFace face)
{
return getByID(StairsMat.combine(face, this.upsideDown));
}
@Override
public RedSandstoneStairsMat getType(final String name)
{
return getByEnumName(name);
}
@Override
public RedSandstoneStairsMat getType(final int id)
{
return getByID(id);
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("face", this.face).append("upsideDown", this.upsideDown).toString();
}
/**
* Returns one of RedSandstoneStairs sub-type based on sub-id, may return null
*
* @param id sub-type id
*
* @return sub-type of RedSandstoneStairs or null
*/
public static RedSandstoneStairsMat getByID(final int id)
{
return byID.get((byte) id);
}
/**
* Returns one of RedSandstoneStairs sub-type based on name (selected by diorite team), may return null
* If block contains only one type, sub-name of it will be this same as name of material.
*
* @param name name of sub-type
*
* @return sub-type of RedSandstoneStairs or null
*/
public static RedSandstoneStairsMat getByEnumName(final String name)
{
return byName.get(name);
}
/**
* Returns one of RedSandstoneStairs sub-type based on facing direction and upside-down state.
* It will never return null.
*
* @param blockFace facing direction of stairs.
* @param upsideDown if stairs should be upside-down.
*
* @return sub-type of RedSandstoneStairs
*/
public static RedSandstoneStairsMat getRedSandstoneStairs(final BlockFace blockFace, final boolean upsideDown)
{
return getByID(StairsMat.combine(blockFace, upsideDown));
}
/**
* Register new sub-type, may replace existing sub-types.
* Should be used only if you know what are you doing, it will not create fully usable material.
*
* @param element sub-type to register
*/
public static void register(final RedSandstoneStairsMat element)
{
byID.put((byte) element.getType(), element);
byName.put(element.name(), element);
}
@Override
public RedSandstoneStairsMat[] types()
{
return RedSandstoneStairsMat.redSandstoneStairsTypes();
}
/**
* @return array that contains all sub-types of this block.
*/
public static RedSandstoneStairsMat[] redSandstoneStairsTypes()
{
return byID.values(new RedSandstoneStairsMat[byID.size()]);
}
static
{
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_EAST);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_WEST);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_SOUTH);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_NORTH);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_EAST_UPSIDE_DOWN);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_WEST_UPSIDE_DOWN);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_SOUTH_UPSIDE_DOWN);
RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_NORTH_UPSIDE_DOWN);
}
}
|
joda17/Diorite-API
|
src/main/java/org/diorite/material/blocks/stony/RedSandstoneStairsMat.java
|
Java
|
mit
| 7,654 |
package cn.ezandroid.ezfilter.render;
import android.content.Context;
import android.opengl.GLES20;
import cn.ezandroid.lib.ezfilter.core.util.Path;
import cn.ezandroid.lib.ezfilter.extra.IAdjustable;
import cn.ezandroid.lib.ezfilter.extra.MultiBitmapInputRender;
/**
* 黑白滤镜
*
* @author like
* @date 2017-09-17
*/
public class BWRender extends MultiBitmapInputRender implements IAdjustable {
private static final String[] BITMAP_PATHS = new String[]{
Path.ASSETS.wrap("filter/bw.png"),
// Path.DRAWABLE.wrap("" + R.drawable.bw)
};
private static final String UNIFORM_MIX = "u_mix";
private int mMixHandle;
private float mMix = 1f; // 滤镜强度
public BWRender(Context context) {
super(context, BITMAP_PATHS);
setFragmentShader("precision lowp float;\n" +
" uniform lowp float u_mix;\n" +
" \n" +
" varying highp vec2 textureCoordinate;\n" +
" \n" +
" uniform sampler2D inputImageTexture;\n" +
" uniform sampler2D inputImageTexture2;\n" +
" \n" +
" \n" +
" void main()\n" +
"{\n" +
" lowp vec4 sourceImageColor = texture2D(inputImageTexture, textureCoordinate)" +
";\n" +
" \n" +
" vec3 texel = texture2D(inputImageTexture, textureCoordinate).rgb;\n" +
" texel = vec3(dot(vec3(0.3, 0.6, 0.1), texel));\n" +
" texel = vec3(texture2D(inputImageTexture2, vec2(texel.r, .16666)).r);\n" +
" mediump vec4 fragColor = vec4(texel, 1.0);\n" +
" gl_FragColor = mix(sourceImageColor, fragColor, u_mix);\n" +
"}");
}
@Override
protected void initShaderHandles() {
super.initShaderHandles();
mMixHandle = GLES20.glGetUniformLocation(mProgramHandle, UNIFORM_MIX);
}
@Override
protected void bindShaderValues() {
super.bindShaderValues();
GLES20.glUniform1f(mMixHandle, mMix);
}
@Override
public void adjust(float progress) {
mMix = progress;
}
}
|
uestccokey/EZFilter
|
app/src/main/java/cn/ezandroid/ezfilter/render/BWRender.java
|
Java
|
mit
| 2,224 |
/*
* The MIT License
*
* Copyright 2014 Sebastian Russ <citeaux at https://github.com/citeaux/JAHAP>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jahap.business.base;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import org.jahap.business.acc.revaccountsbean;
import org.jahap.entities.JahapDatabaseConnector;
import org.jahap.entities.acc.AccountPosition;
import org.jahap.entities.acc.Csc;
import org.jahap.entities.acc.Revaccounts;
import org.jahap.entities.base.Rates;
import org.jahap.entities.base.Vattype;
/**
*
* @author russ
*/
public class ratesbean extends DatabaseOperations implements rates_i{
static Logger log = Logger.getLogger(ratesbean.class.getName());
JahapDatabaseConnector dbhook;
private static List<Rates> allrecordlist;
private revaccountsbean revAccBean;
public ratesbean(){
long testg;
dbhook = JahapDatabaseConnector.getConnector();
revAccBean= new revaccountsbean();
try {
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rates t ORDER BY t.id");
List<Rates>allroomslist= query_AllDbRecords.getResultList();
numberOfLastRecord= allroomslist.size()-1;
} catch (Exception e) {
numberOfLastRecord=-1;
}
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rates t ORDER BY t.id");
allrecordlist= query_AllDbRecords.getResultList();
try {
testg=allrecordlist.get(currentRecordNumber).getId();
tabelIsEmpty=false;
tabelIsInit=true;
} catch (Exception e) {
tabelIsEmpty=true;
}
log.trace("DB connected");
// If the table is yet empty, init List
}
public List<Rates>getCurrentRate(){
List<Rates>hh=new ArrayList<Rates>();
hh.add(allrecordlist.get(currentRecordNumber));
return hh;
}
public void createNewEmptyRecord() {
log.debug("Function entry createNewEmptyRecord");
if(numberOfLastRecord==-1){
allrecordlist = new ArrayList();
numberOfLastRecord++;
}
if(numberOfLastRecord>-1){
numberOfLastRecord++;
}
Rates emptyroom = new Rates();
allrecordlist.add(emptyroom);
currentRecordNumber=numberOfLastRecord;
setNewEmptyRecordCreadted();
tabelIsInit=true; // Set Tabel iniated - List is connected
}
public void nextRecordBackward() {
if (currentRecordNumber>0) {
currentRecordNumber--;
}
}
public void nextRecordForeward() {
if (currentRecordNumber<numberOfLastRecord) {
currentRecordNumber++;
}
}
public void saveRecord() {
log.debug("Function entry save Record");
if (newEmptyRecordCreated==false){
saveOldRecord();
}
if (newEmptyRecordCreated==true){
saveNewRecord();
setNewEmptyRecordSaved();
}
}
private void saveOldRecord(){
log.debug("Function entry saveOldRecord");
if(newEmptyRecordCreated==false){
dbhook.getEntity().getTransaction().begin();
dbhook.getEntity().find(Rates.class,allrecordlist.get(currentRecordNumber).getId() );
dbhook.getEntity().merge(allrecordlist.get(currentRecordNumber));
dbhook.getEntity().getTransaction().commit();
}
}
private void saveNewRecord(){
log.debug("Function entry saveNewRecord");
if ( newEmptyRecordCreated==true){
try{
dbhook.getEntity().getTransaction().begin();
dbhook.getEntity().persist(allrecordlist.get(currentRecordNumber));
dbhook.getEntity().getTransaction().commit();
newEmptyRecordCreated=false;
}
catch (Exception e){
e.printStackTrace();
}
}
}
public void setDataRecordId(Long id){
int inl=-1;
try {
do {
inl++;
} while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl);
currentRecordNumber=inl;
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Rates>SearchForRate(String searchstring){
return allrecordlist;
}
/* Depricated - not used
public Rates SearchForRatewithId(long id){
for(Rates kj:allrecordlist){
if(kj.getId()==id){
return kj;
}
}
return null;
}
*/
public Rates getDataRecord(Long id){
int inl=-1;
try {
do {
inl++;
} while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl);
currentRecordNumber = inl;
System.out.println(currentRecordNumber);
} catch (Exception e) {
e.printStackTrace();
}
return allrecordlist.get(currentRecordNumber);
}
public void quitDBaccess() {
dbhook.getEntity().close();
}
// ---------------------- Getters & Setters ------------------
public Collection<AccountPosition> getAccountPositionCollection() {
if( tabelIsEmpty!=true){
return allrecordlist.get(currentRecordNumber).getAccountPositionCollection();
}
return null;
}
public String getCode() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getCode();
return "";
}
public Long getId() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getId();
return null;
}
public String getName() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getName();
return null;
}
public double getPrice() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getPrice();
return 0;
}
public void setAccountPositionCollection(Collection<AccountPosition> accountPositionCollection) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
}
public void setCode(String code) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setCode(code);
}
public void setName(String name) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setName(name);
}
public void setPrice(double price) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setPrice(price);
}
public void setId(Long id) {
throw new UnsupportedOperationException("Not supported yet.");
}
// public long getRevaccount() {
// if( tabelIsEmpty!=true)
// return allrecordlist.get(currentRecordNumber).getRevaccount().getId();
// return 0;
// }
public Collection<Csc> getCscCollection() {
if( tabelIsEmpty!=true){
return allrecordlist.get(currentRecordNumber).getCscCollection();
}
return null;
}
public boolean getOvernight() {
if( tabelIsEmpty!=true){
return allrecordlist.get(currentRecordNumber).getOvernight();
}
return false;
}
public void setCscCollection(Collection<Csc> cscCollection) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setOvernight(boolean overnight) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setOvernight(overnight);
}
public void setRevaccount(long revaccount) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setRevaccount(revAccBean.SearchForRevAccount(revaccount));
}
@Override
public Vattype getVattype() {
if( tabelIsEmpty!=true){
return allrecordlist.get(currentRecordNumber).getVattype();
}
return null;
}
public void setVattype(long vattype) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
vattypesbean vatb= new vattypesbean();
allrecordlist.get(currentRecordNumber).setVattype(vatb.getDataRecord(vattype));
}
@Override
public void setVattype(Vattype vattype) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setVattype(vattype);
}
@Override
public Revaccounts getRevaccount() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getRevaccount();
return null;
}
@Override
public void setRevaccount(Revaccounts revaccount) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setRevaccount(revaccount);
}
}
|
citeaux/JAHAP
|
src/main/java/org/jahap/business/base/ratesbean.java
|
Java
|
mit
| 11,151 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.data.processor.block;
import static org.spongepowered.common.data.DataTransactionBuilder.fail;
import com.google.common.base.Optional;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.DataPriority;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.DataView;
import org.spongepowered.api.data.manipulator.block.DirectionalData;
import org.spongepowered.api.service.persistence.InvalidDataException;
import org.spongepowered.common.data.DataTransactionBuilder;
import org.spongepowered.common.data.SpongeBlockProcessor;
import org.spongepowered.common.data.SpongeDataProcessor;
import org.spongepowered.common.data.manipulator.block.SpongeDirectionalData;
import org.spongepowered.common.interfaces.block.IMixinBlockDirectional;
public class SpongeDirectionalProcessor implements SpongeDataProcessor<DirectionalData>, SpongeBlockProcessor<DirectionalData> {
@Override
public Optional<DirectionalData> fillData(DataHolder dataHolder, DirectionalData manipulator, DataPriority priority) {
return Optional.absent();
}
@Override
public DataTransactionResult setData(DataHolder dataHolder, DirectionalData manipulator, DataPriority priority) {
return DataTransactionBuilder.successNoData();
}
@Override
public boolean remove(DataHolder dataHolder) {
return false;
}
@Override
public Optional<DirectionalData> build(DataView container) throws InvalidDataException {
return Optional.absent();
}
@Override
public DirectionalData create() {
return new SpongeDirectionalData();
}
@Override
public Optional<DirectionalData> createFrom(DataHolder dataHolder) {
return Optional.absent();
}
@Override
public Optional<DirectionalData> fromBlockPos(final World world, final BlockPos blockPos) {
IBlockState blockState = world.getBlockState(blockPos);
if (blockState.getBlock() instanceof IMixinBlockDirectional) {
return Optional.of(((IMixinBlockDirectional) blockState.getBlock()).getDirectionalData(blockState));
}
return Optional.absent();
}
@Override
public DataTransactionResult setData(World world, BlockPos blockPos, DirectionalData manipulator, DataPriority priority) {
IBlockState blockState = world.getBlockState(blockPos);
if (blockState.getBlock() instanceof IMixinBlockDirectional) {
return ((IMixinBlockDirectional) blockState.getBlock()).setDirectionalData(manipulator, world, blockPos, priority);
}
return fail(manipulator);
}
@Override
public boolean remove(World world, BlockPos blockPos) {
IBlockState blockState = world.getBlockState(blockPos);
if (blockState.getBlock() instanceof IMixinBlockDirectional) {
// ((IMixinBlockDirectional) blockState.getBlock()).resetDirectionData(blockState);
return true;
}
return false;
}
@Override
public Optional<BlockState> removeFrom(IBlockState blockState) {
return Optional.absent();
}
@Override
public Optional<DirectionalData> createFrom(IBlockState blockState) {
if (blockState.getBlock() instanceof IMixinBlockDirectional) {
((IMixinBlockDirectional) blockState.getBlock()).getDirectionalData(blockState);
}
return Optional.absent();
}
@Override
public Optional<DirectionalData> getFrom(DataHolder dataHolder) {
return Optional.absent();
}
}
|
gabizou/SpongeCommon
|
src/main/java/org/spongepowered/common/data/processor/block/SpongeDirectionalProcessor.java
|
Java
|
mit
| 5,006 |
package com.dreamdevs.sunshine.fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.dreamdevs.sunshine.R;
import com.dreamdevs.sunshine.adapter.ForecastAdapter;
import com.dreamdevs.sunshine.data.WeatherContract;
import com.dreamdevs.sunshine.sync.SunshineSyncAdapter;
import com.dreamdevs.sunshine.util.Utility;
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String LOG_TAG = ForecastFragment.class.getSimpleName();
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data
// Specify the columns we need
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
public static final int COL_WEATHER_ID = 0;
public static final int COL_WEATHER_DATE = 1;
public static final int COL_WEATHER_DESC = 2;
public static final int COL_WEATHER_MAX_TEMP = 3;
public static final int COL_WEATHER_MIN_TEMP = 4;
public static final int COL_LOCATION_SETTING = 5;
public static final int COL_WEATHER_CONDITION_ID = 6;
public static final int COL_COORD_LAT = 7;
public static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
private int mPosition = ListView.INVALID_POSITION;
private static final String SELECTED_KEY = "selected_position";
private static final int SET_LIST_ITEM_SELECTED = 100;
private ListView mListView;
private boolean mUseTodayLayout;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what == SET_LIST_ITEM_SELECTED) {
setListItemSelected();
}
}
};
public ForecastFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onResume() {
PreferenceManager.getDefaultSharedPreferences(getActivity())
.registerOnSharedPreferenceChangeListener(this);
super.onResume();
}
@Override
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getActivity())
.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_map) {
openPreferredLocationInMap();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateWeather() {
SunshineSyncAdapter.syncImmediately(getActivity());
}
private void openPreferredLocationInMap() {
// Using the URI scheme for showing a location found on a map. This super-handy
// intent can is detailed in the "Common Intents" page of Android's developer site:
// http://developer.android.com/guide/components/intents-common.html#Maps
if ( null != mForecastAdapter ) {
Cursor c = mForecastAdapter.getCursor();
if ( null != c ) {
c.moveToPosition(0);
String posLat = c.getString(COL_COORD_LAT);
String posLong = c.getString(COL_COORD_LONG);
Uri geoLocation = Uri.parse("geo:" + posLat + "," + posLong);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(LOG_TAG, "Couldn't call " + geoLocation.toString() + ", no receiving apps installed!");
}
}
}
}
public void onLocationChanged() {
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER, null, this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
mForecastAdapter.setUseTodayLayout(mUseTodayLayout);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
mListView = (ListView) rootView.findViewById(R.id.listview_forecast);
mListView.setEmptyView(rootView.findViewById(R.id.listview_forecast_empty));
mListView.setAdapter(mForecastAdapter);
// We'll call our MainActivity
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
((Callback) getActivity()).onItemSelected(WeatherContract.WeatherEntry
.buildWeatherLocationWithDate(locationSetting,
cursor.getLong(COL_WEATHER_DATE)));
}
mPosition = position;
}
});
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
mPosition = savedInstanceState.getInt(SELECTED_KEY);
}
mForecastAdapter.setUseTodayLayout(mUseTodayLayout);
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (mPosition != ListView.INVALID_POSITION) {
outState.putInt(SELECTED_KEY, mPosition);
}
super.onSaveInstanceState(outState);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry
.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());
return new CursorLoader(
getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
private void setListItemSelected() {
if (!mUseTodayLayout) {
int position = mPosition == ListView.INVALID_POSITION ? 0 : mPosition;
Cursor cursor = (Cursor) mForecastAdapter.getItem(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
long date = cursor.getLong(COL_WEATHER_DATE);
((Callback) getActivity()).onItemSelected(WeatherContract.WeatherEntry
.buildWeatherLocationWithDate(locationSetting, date));
}
if (mPosition != ListView.INVALID_POSITION) {
mListView.smoothScrollToPosition(mPosition);
}
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
if (cursor == null) {
updateEmptyView();
}
mHandler.sendEmptyMessage(SET_LIST_ITEM_SELECTED);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mForecastAdapter.swapCursor(null);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.pref_location_status_key))) {
updateEmptyView();
}
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
void onItemSelected(Uri dateUri);
}
public void setUseTodayLayout(boolean useTodayLayout) {
mUseTodayLayout = useTodayLayout;
if (mForecastAdapter != null) {
mForecastAdapter.setUseTodayLayout(mUseTodayLayout);
}
}
private void updateEmptyView() {
if (mForecastAdapter.getCount() == 0) {
TextView emptyView = (TextView) getView().findViewById(R.id.listview_forecast_empty);
if (null != emptyView) {
int message = R.string.empty_forecast_list;
@SunshineSyncAdapter.LocationStatus int location =
Utility.getLocationStatus(getActivity());
switch (location) {
case SunshineSyncAdapter.LOCATION_STATUS_SERVER_DOWN:
message = R.string.empty_forecast_list_server_down;
break;
case SunshineSyncAdapter.LOCATION_STATUS_SERVER_INVALID:
message = R.string.empty_forecast_list_server_error;
break;
case SunshineSyncAdapter.LOCATION_STATUS_INVALID:
message = R.string.empty_forecast_list_invalid_location;
break;
default:
if (!Utility.isNetworkAvaille(getActivity())) {
message = R.string.empty_forecast_list_no_network;
}
}
emptyView.setText(message);
}
}
}
}
|
7odri9o/Sunshine
|
app/src/main/java/com/dreamdevs/sunshine/fragment/ForecastFragment.java
|
Java
|
mit
| 12,550 |
package TankWarGame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public class EnergyBar extends GameObject {
int energy;
int defaultEnergy = 5000/30;
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public EnergyBar(int x,int y,int width,int weight,Image[] images,int energy) {
// TODO Auto-generated constructor stub
super(x, y, width, weight, images);
this.energy = energy;
}
void draw(Graphics g) {
g.setColor(Color.RED);
g.fillRect(x, y, energy *40 /defaultEnergy, height);
energy--;
}
}
|
TakeshiTseng/JavaTankWarGame
|
src/TankWarGame/EnergyBar.java
|
Java
|
mit
| 633 |
package com.amee.domain.data.builder.v2;
import com.amee.base.utils.XMLUtils;
import com.amee.domain.Builder;
import com.amee.domain.ItemBuilder;
import com.amee.domain.ItemService;
import com.amee.domain.TimeZoneHolder;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.NumberValue;
import com.amee.platform.science.StartEndDate;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ItemValueBuilder implements Builder {
private BaseItemValue itemValue;
private ItemBuilder itemBuilder;
private ItemService itemService;
public ItemValueBuilder(BaseItemValue itemValue, ItemService itemService) {
this.itemValue = itemValue;
this.itemService = itemService;
}
public ItemValueBuilder(BaseItemValue itemValue, ItemBuilder itemBuilder, ItemService itemService) {
this(itemValue, itemService);
this.itemBuilder = itemBuilder;
}
public JSONObject getJSONObject() throws JSONException {
return getJSONObject(true);
}
public JSONObject getJSONObject(boolean detailed) throws JSONException {
JSONObject obj = new JSONObject();
obj.put("uid", itemValue.getUid());
obj.put("path", itemValue.getPath());
obj.put("name", itemValue.getName());
obj.put("value", itemValue.getValueAsString());
if (NumberValue.class.isAssignableFrom(itemValue.getClass())) {
NumberValue numberValue = (NumberValue) itemValue;
obj.put("unit", numberValue.getUnit());
obj.put("perUnit", numberValue.getPerUnit());
} else {
obj.put("unit", "");
obj.put("perUnit", "");
}
obj.put("startDate",
StartEndDate.getLocalStartEndDate(itemService.getStartDate(itemValue), TimeZoneHolder.getTimeZone()).toString());
obj.put("itemValueDefinition", itemValue.getItemValueDefinition().getJSONObject(false));
obj.put("displayName", itemValue.getDisplayName());
obj.put("displayPath", itemValue.getDisplayPath());
if (detailed) {
obj.put("created", itemValue.getCreated());
obj.put("modified", itemValue.getModified());
obj.put("item", itemBuilder.getJSONObject(true));
}
return obj;
}
public Element getElement(Document document) {
return getElement(document, true);
}
public Element getElement(Document document, boolean detailed) {
Element element = document.createElement("ItemValue");
element.setAttribute("uid", itemValue.getUid());
element.appendChild(XMLUtils.getElement(document, "Path", itemValue.getPath()));
element.appendChild(XMLUtils.getElement(document, "Name", itemValue.getName()));
element.appendChild(XMLUtils.getElement(document, "Value", itemValue.getValueAsString()));
if (NumberValue.class.isAssignableFrom(itemValue.getClass())) {
NumberValue numberValue = (NumberValue) itemValue;
element.appendChild(XMLUtils.getElement(document, "Unit", numberValue.getUnit().toString()));
element.appendChild(XMLUtils.getElement(document, "PerUnit", numberValue.getPerUnit().toString()));
} else {
element.appendChild(XMLUtils.getElement(document, "Unit", ""));
element.appendChild(XMLUtils.getElement(document, "PerUnit", ""));
}
element.appendChild(XMLUtils.getElement(document, "StartDate",
StartEndDate.getLocalStartEndDate(itemService.getStartDate(itemValue), TimeZoneHolder.getTimeZone()).toString()));
element.appendChild(itemValue.getItemValueDefinition().getElement(document, false));
if (detailed) {
element.setAttribute("Created", itemValue.getCreated().toString());
element.setAttribute("Modified", itemValue.getModified().toString());
element.appendChild(itemBuilder.getIdentityElement(document));
}
return element;
}
public JSONObject getIdentityJSONObject() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("uid", itemValue.getUid());
obj.put("path", itemValue.getPath());
return obj;
}
public Element getIdentityElement(Document document) {
return XMLUtils.getIdentityElement(document, "ItemValue", itemValue);
}
}
|
OpenAMEE/amee.platform.api
|
amee-platform-domain/src/main/java/com/amee/domain/data/builder/v2/ItemValueBuilder.java
|
Java
|
mit
| 4,429 |
package cvut.fit.borrowsystem.domain.entity;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by Jakub Tuček on 03/06/16.
*/
@Document(collection = "item")
public class Book extends Item {
private int isbn;
public Book() {
}
public Book(String itemName, int count, int isbn) {
super(itemName, count);
this.isbn = isbn;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
}
|
jakub-tucek/simple-spring-borrow-system
|
src/main/java/cvut/fit/borrowsystem/domain/entity/Book.java
|
Java
|
mit
| 521 |
package com.jim.portal.controller;
import com.jim.portal.entity.BooksEntity;
import com.jim.portal.hibernate.BookManagementRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by jim on 2017/1/5.
* This class is ...
*/
@Controller
@RequestMapping(value = "/book")
public class BookController extends BaseController {
@Autowired
private BookManagementRepository bookManagementRepository;
@RequestMapping(value = "/updateBook", method = RequestMethod.GET)
public String updateBook(){
return "system/book/update-book";
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(BooksEntity booksEntity, String id){
result.clear();
try {
bookManagementRepository.update(booksEntity, id);
result.put("result", 0);
}catch (Exception ex){
result.put("result", 1);
result.put("msg", ex.toString());
}
return gson.toJson(result);
}
@RequestMapping(value = "/createBook", method = RequestMethod.GET)
public String createBook(){
return "system/book/create-book";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(BooksEntity booksEntity){
result.clear();
try {
BooksEntity book = bookManagementRepository.create(booksEntity);
result.put("result", 0);
result.put("msg", book);
}catch (Exception ex){
result.put("result", 1);
result.put("msg", ex.toString());
}
return gson.toJson(result);
}
}
|
liu1084/springmvc-cookbook
|
cloudstreetmarket-parent/cloudstreetmarket-webapp/src/main/java/com/jim/portal/controller/BookController.java
|
Java
|
mit
| 1,630 |
/* Copyright (c) 2015 Pozirk Games
* http://www.pozirk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.pozirk.ads;
//import android.util.Log;
import com.amazon.device.ads.*;
import org.haxe.lime.HaxeObject;
public class AmazonAdsListener implements AdListener
{
protected HaxeObject _callback = null;
protected String _who = null;
public AmazonAdsListener(HaxeObject callback, String who)
{
_callback = callback;
_who = who;
}
public void onAdLoaded(Ad ad, AdProperties adProperties)
{
//Log.d("amazonads", "onAdLoaded");
_callback.call("onStatus", new Object[] {"AD_LOADED", _who, "type: "+_who});
}
public void onAdFailedToLoad(Ad ad, AdError error)
{
//Log.d("amazonads", "onAdFailedToLoad: "+error.getMessage());
_callback.call("onStatus", new Object[] {"AD_FAILED_TO_LOAD", _who, "type: "+_who+", "+error.getCode()+": "+error.getMessage()});
}
public void onAdExpanded(Ad ad)
{
_callback.call("onStatus", new Object[] {"AD_EXPANDED", _who, "type: "+_who});
}
public void onAdCollapsed(Ad ad)
{
_callback.call("onStatus", new Object[] {"AD_COLLAPSED", _who, "type: "+_who});
}
public void onAdDismissed(Ad ad)
{
_callback.call("onStatus", new Object[] {"AD_DISMISSED", _who, "type: "+_who});
}
}
|
openfl/extension-amazonads
|
dependencies/amazonads/src/com/pozirk/ads/AmazonAdsListener.java
|
Java
|
mit
| 2,319 |
package com.codepoetics.protonpack.selectors;
import java.util.Comparator;
import java.util.Objects;
import java.util.stream.Stream;
public final class Selectors {
private Selectors() {
}
public static <T> Selector<T> roundRobin() {
return new Selector<T>() {
private int startIndex = 0;
@Override
public Integer apply(T[] options) {
int result = startIndex;
while (options[result] == null) {
result = (result + 1) % options.length;
}
startIndex = (result + 1) % options.length;
return result;
}
};
}
public static <T extends Comparable<T>> Selector<T> takeMin() {
return takeMin(Comparator.naturalOrder());
}
public static <T> Selector<T> takeMin(Comparator<? super T> comparator) {
return new Selector<T>() {
private int startIndex = 0;
@Override
public Integer apply(T[] options) {
T smallest = Stream.of(options).filter(Objects::nonNull).min(comparator).get();
int result = startIndex;
while (options[result] == null || comparator.compare(smallest, options[result]) != 0) {
result = (result + 1) % options.length;
}
startIndex = (result + 1) % options.length;
return result;
}
};
}
public static <T extends Comparable<T>> Selector<T> takeMax() {
return takeMax(Comparator.naturalOrder());
}
public static <T> Selector<T> takeMax(Comparator<? super T> comparator) {
return takeMin(comparator.reversed());
}
}
|
poetix/protonpack
|
src/main/java/com/codepoetics/protonpack/selectors/Selectors.java
|
Java
|
mit
| 1,740 |
package me.xwang1024.sifResExplorer.model;
public class UnitSkill {
}
|
xwang1024/SIF-Resource-Explorer
|
src/main/java/me/xwang1024/sifResExplorer/model/UnitSkill.java
|
Java
|
mit
| 77 |
/*
Sample code file for CPJ2e.
All code has been pasted directly from the camera-ready copy, and
then modified in the smallest possible way to ensure that it will
compile -- adding import statements or full package qualifiers for
some class names, adding stand-ins for classes and methods that are
referred to but not listed, and supplying dummy arguments instead of
"...").
They are presented in page-number order.
*/
import com.sun.corba.se.impl.orbutil.concurrent.CondVar;
import com.sun.corba.se.impl.orbutil.concurrent.Sync;
import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.locks.ReadWriteLock;
class Helper { // Dummy standin for referenced generic "Helper" classes
void handle() {}
void operation() {}
}
class Particle {
protected int x;
protected int y;
protected final Random rng = new Random();
public Particle(int initialX, int initialY) {
x = initialX;
y = initialY;
}
public synchronized void move() {
x += rng.nextInt(10) - 5;
y += rng.nextInt(20) - 10;
}
public void draw(Graphics g) {
int lx, ly;
synchronized (this) { lx = x; ly = y; }
g.drawRect(lx, ly, 10, 10);
}
}
class ParticleCanvas extends Canvas {
private Particle[] particles = new Particle[0];
ParticleCanvas(int size) {
setSize(new Dimension(size, size));
}
// Intended to be called by applet
synchronized void setParticles(Particle[] ps) {
if (ps == null)
throw new IllegalArgumentException("Cannot set null");
particles = ps;
}
protected synchronized Particle[] getParticles() {
return particles;
}
public void paint(Graphics g) { // override Canvas.paint
Particle[] ps = getParticles();
for (int i = 0; i < ps.length; ++i)
ps[i].draw(g);
}
}
class ParticleApplet extends Applet {
protected Thread[] threads; // null when not running
protected final ParticleCanvas canvas
= new ParticleCanvas(100);
public void init() { add(canvas); }
protected Thread makeThread(final Particle p) { // utility
Runnable runloop = new Runnable() {
public void run() {
try {
for(;;) {
p.move();
canvas.repaint();
Thread.sleep(100); // 100msec is arbitrary
}
}
catch (InterruptedException e) { return; }
}
};
return new Thread(runloop);
}
public synchronized void start() {
int n = 10; // just for demo
if (threads == null) { // bypass if already started
Particle[] particles = new Particle[n];
for (int i = 0; i < n; ++i)
particles[i] = new Particle(50, 50);
canvas.setParticles(particles);
threads = new Thread[n];
for (int i = 0; i < n; ++i) {
threads[i] = makeThread(particles[i]);
threads[i].start();
}
}
}
public synchronized void stop() {
if (threads != null) { // bypass if already stopped
for (int i = 0; i < threads.length; ++i)
threads[i].interrupt();
threads = null;
}
}
}
class AssertionError extends java.lang.Error {
public AssertionError() { super(); }
public AssertionError(String message) { super(message); }
}
interface Tank {
float getCapacity();
float getVolume();
void transferWater(float amount)
throws OverflowException, UnderflowException;
}
class OverflowException extends Exception {}
class UnderflowException extends Exception {}
class TankImpl {
public float getCapacity() { return 1.0f; }
public float getVolume() { return 1.0f; }
public void transferWater(float amount)
throws OverflowException, UnderflowException {}
}
class Performer { public void perform() {} }
class AdaptedPerformer implements Runnable {
private final Performer adaptee;
public AdaptedPerformer(Performer p) { adaptee = p; }
public void run() { adaptee.perform(); }
}
class AdaptedTank implements Tank {
protected final Tank delegate;
public AdaptedTank(Tank t) { delegate = t; }
public float getCapacity() { return delegate.getCapacity(); }
public float getVolume() { return delegate.getVolume(); }
protected void checkVolumeInvariant() throws AssertionError {
float v = getVolume();
float c = getCapacity();
if ( !(v >= 0.0 && v <= c) )
throw new AssertionError();
}
public synchronized void transferWater(float amount)
throws OverflowException, UnderflowException {
checkVolumeInvariant(); // before-check
try {
delegate.transferWater(amount);
}
// postpone rethrows until after-check
catch (OverflowException ex) { throw ex; }
catch (UnderflowException ex) { throw ex; }
finally {
checkVolumeInvariant(); // after-check
}
}
}
abstract class AbstractTank implements Tank {
protected void checkVolumeInvariant() throws AssertionError {
// ... identical to AdaptedTank version ...
}
protected abstract void doTransferWater(float amount)
throws OverflowException, UnderflowException;
public synchronized void transferWater(float amount)
throws OverflowException, UnderflowException {
// identical to AdaptedTank version except for inner call:
// ...
try {
doTransferWater(amount);
}
finally {}
// ...
}
}
class ConcreteTank extends AbstractTank {
protected final float capacity = 10.f;
protected float volume;
// ...
public float getVolume() { return volume; }
public float getCapacity() { return capacity; }
protected void doTransferWater(float amount)
throws OverflowException, UnderflowException {
// ... implementation code ...
}
}
interface TankOp {
void op() throws OverflowException, UnderflowException;
}
class TankWithMethodAdapter {
// ...
protected void checkVolumeInvariant() throws AssertionError {
// ... identical to AdaptedTank version ...
}
protected void runWithinBeforeAfterChecks(TankOp cmd)
throws OverflowException, UnderflowException {
// identical to AdaptedTank.transferWater
// except for inner call:
// ...
try {
cmd.op();
}
finally {}
// ...
}
protected void doTransferWater(float amount)
throws OverflowException, UnderflowException {
// ... implementation code ...
}
public synchronized void transferWater(final float amount)
throws OverflowException, UnderflowException {
runWithinBeforeAfterChecks(new TankOp() {
public void op()
throws OverflowException, UnderflowException {
doTransferWater(amount);
}
});
}
}
class StatelessAdder {
public int add(int a, int b) { return a + b; }
}
class ImmutableAdder {
private final int offset;
public ImmutableAdder(int a) { offset = a; }
public int addOffset(int b) { return offset + b; }
}
class Fraction { // Fragments
protected final long numerator;
protected final long denominator;
public Fraction(long num, long den) {
// normalize:
boolean sameSign = (num >= 0) == (den >= 0);
long n = (num >= 0)? num : -num;
long d = (den >= 0)? den : -den;
long g = gcd(n, d);
numerator = (sameSign)? n / g : -n / g;
denominator = d / g;
}
static long gcd(long a, long b) {
// ... compute greatest common divisor ...
return 1;
}
public Fraction plus(Fraction f) {
return new Fraction(numerator * f.denominator +
f.numerator * denominator,
denominator * f.denominator);
}
public boolean equals(Object other) { // override default
if (! (other instanceof Fraction) ) return false;
Fraction f = (Fraction)(other);
return numerator * f.denominator ==
denominator * f.numerator;
}
public int hashCode() { // override default
return (int) (numerator ^ denominator);
}
}
class Server { void doIt() {} }
class Relay {
protected final Server server;
Relay(Server s) { server = s; }
void doIt() { server.doIt(); }
}
class Even { // Do not use
private int n = 0;
public int next(){ // POST?: next is always even
++n;
++n;
return n;
}
}
class ExpandableArray {
protected Object[] data; // the elements
protected int size = 0; // the number of array slots used
// INV: 0 <= size <= data.length
public ExpandableArray(int cap) {
data = new Object[cap];
}
public synchronized int size() {
return size;
}
public synchronized Object get(int i) // subscripted access
throws NoSuchElementException {
if (i < 0 || i >= size )
throw new NoSuchElementException();
return data[i];
}
public synchronized void add(Object x) { // add at end
if (size == data.length) { // need a bigger array
Object[] olddata = data;
data = new Object[3 * (size + 1) / 2];
System.arraycopy(olddata, 0, data, 0, olddata.length);
}
data[size++] = x;
}
public synchronized void removeLast()
throws NoSuchElementException {
if (size == 0)
throw new NoSuchElementException();
data[--size] = null;
}
}
interface Procedure {
void apply(Object obj);
}
class ExpandableArrayWithApply extends ExpandableArray {
public ExpandableArrayWithApply(int cap) { super(cap); }
synchronized void applyToAll(Procedure p) {
for (int i = 0; i < size; ++i)
p.apply(data[i]);
}
}
class ExpandableArrayWithIterator extends ExpandableArray {
protected int version = 0;
public ExpandableArrayWithIterator(int cap) { super(cap); }
public synchronized void removeLast()
throws NoSuchElementException {
super.removeLast();
++version; // advertise update
}
public synchronized void add(Object x) {
super.add(x);
++version;
}
public synchronized Iterator iterator() {
return new EAIterator();
}
protected class EAIterator implements Iterator {
protected final int currentVersion;
protected int currentIndex = 0;
EAIterator() { currentVersion = version; }
public Object next() {
synchronized(ExpandableArrayWithIterator.this) {
if (currentVersion != version)
throw new ConcurrentModificationException();
else if (currentIndex == size)
throw new NoSuchElementException();
else
return data[currentIndex++];
}
}
public boolean hasNext() {
synchronized(ExpandableArrayWithIterator.this) {
return (currentIndex < size);
}
}
public void remove() {
// similar
}
}
}
class LazySingletonCounter {
private final long initial;
private long count;
private LazySingletonCounter() {
initial = Math.abs(new java.util.Random().nextLong() / 2);
count = initial;
}
private static LazySingletonCounter s = null;
private static final Object classLock =
LazySingletonCounter.class;
public static LazySingletonCounter instance() {
synchronized(classLock) {
if (s == null)
s = new LazySingletonCounter();
return s;
}
}
public long next() {
synchronized(classLock) { return count++; }
}
public void reset() {
synchronized(classLock) { count = initial; }
}
}
class EagerSingletonCounter {
private final long initial;
private long count;
private EagerSingletonCounter() {
initial = Math.abs(new java.util.Random().nextLong() / 2);
count = initial;
}
private static final EagerSingletonCounter s =
new EagerSingletonCounter();
public static EagerSingletonCounter instance() { return s; }
public synchronized long next() { return count++; }
public synchronized void reset() { count = initial; }
}
class StaticCounter {
private static final long initial =
Math.abs(new java.util.Random().nextLong() / 2);
private static long count = initial;
private StaticCounter() { } // disable instance construction
public static synchronized long next() { return count++; }
public static synchronized void reset() { count = initial; }
}
class Cell { // Do not use
private long value;
synchronized long getValue() { return value; }
synchronized void setValue(long v) { value = v; }
synchronized void swapValue(Cell other) {
long t = getValue();
long v = other.getValue();
setValue(v);
other.setValue(t);
}
}
class Cell2 { // Do not use
private long value;
synchronized long getValue() { return value; }
synchronized void setValue(long v) { value = v; }
public void swapValue(Cell2 other) {
if (other == this) // alias check
return;
else if (System.identityHashCode(this) <
System.identityHashCode(other))
this.doSwapValue(other);
else
other.doSwapValue(this);
}
protected synchronized void doSwapValue(Cell2 other) {
// same as original public version:
long t = getValue();
long v = other.getValue();
setValue(v);
other.setValue(t);
}
protected synchronized void doSwapValueV2(Cell2 other) {
synchronized(other) {
long t = value;
value = other.value;
other.value = t;
}
}
}
final class SetCheck {
private int a = 0;
private long b = 0;
void set() {
a = 1;
b = -1;
}
boolean check() {
return ((b == 0) ||
(b == -1 && a == 1));
}
}
final class VFloat {
private float value;
final synchronized void set(float f) { value = f; }
final synchronized float get() { return value; }
}
class Plotter { // fragments
// ...
public void showNextPoint() {
Point p = new Point();
p.x = computeX();
p.y = computeY();
display(p);
}
int computeX() { return 1; }
int computeY() { return 1; }
protected void display(Point p) {
// somehow arrange to show p.
}
}
class SessionBasedService { // Fragments
// ...
public void service() {
OutputStream output = null;
try {
output = new FileOutputStream("...");
doService(output);
}
catch (IOException e) {
handleIOFailure();
}
finally {
try { if (output != null) output.close(); }
catch (IOException ignore) {} // ignore exception in close
}
}
void handleIOFailure() {}
void doService(OutputStream s) throws IOException {
s.write(0);
// ... possibly more handoffs ...
}
}
class ThreadPerSessionBasedService { // fragments
// ...
public void service() {
Runnable r = new Runnable() {
public void run() {
OutputStream output = null;
try {
output = new FileOutputStream("...");
doService(output);
}
catch (IOException e) {
handleIOFailure();
}
finally {
try { if (output != null) output.close(); }
catch (IOException ignore) {}
}
}
};
new Thread(r).start();
}
void handleIOFailure() {}
void doService(OutputStream s) throws IOException {
s.write(0);
// ... possibly more hand-offs ...
}
}
class ThreadWithOutputStream extends Thread {
private OutputStream output;
ThreadWithOutputStream(Runnable r, OutputStream s) {
super(r);
output = s;
}
static ThreadWithOutputStream current()
throws ClassCastException {
return (ThreadWithOutputStream) (currentThread());
}
static OutputStream getOutput() { return current().output; }
static void setOutput(OutputStream s) { current().output = s;}
}
class ServiceUsingThreadWithOutputStream { // Fragments
// ...
public void service() throws IOException {
OutputStream output = new FileOutputStream("...");
Runnable r = new Runnable() {
public void run() {
try { doService(); } catch (IOException e) { }
}
};
new ThreadWithOutputStream(r, output).start();
}
void doService() throws IOException {
ThreadWithOutputStream.current().getOutput().write(0);
}
}
class ServiceUsingThreadLocal { // Fragments
static ThreadLocal output = new ThreadLocal();
public void service() {
try {
final OutputStream s = new FileOutputStream("...");
Runnable r = new Runnable() {
public void run() {
output.set(s);
try { doService(); }
catch (IOException e) { }
finally {
try { s.close(); }
catch (IOException ignore) {}
}
}
};
new Thread(r).start();
}
catch (IOException e) {}
}
void doService() throws IOException {
((OutputStream)(output.get())).write(0);
// ...
}
}
class BarePoint {
public double x;
public double y;
}
class SynchedPoint {
protected final BarePoint delegate = new BarePoint();
public synchronized double getX() { return delegate.x;}
public synchronized double getY() { return delegate.y; }
public synchronized void setX(double v) { delegate.x = v; }
public synchronized void setY(double v) { delegate.y = v; }
}
class Address { // Fragments
protected String street;
protected String city;
public String getStreet() { return street; }
public void setStreet(String s) { street = s; }
// ...
public void printLabel(OutputStream s) { }
}
class SynchronizedAddress extends Address {
// ...
public synchronized String getStreet() {
return super.getStreet();
}
public synchronized void setStreet(String s) {
super.setStreet(s);
}
public synchronized void printLabel(OutputStream s) {
super.printLabel(s);
}
}
class Printer {
public void printDocument(byte[] doc) { /* ... */ }
// ...
}
class PrintService {
protected PrintService neighbor = null; // node to take from
protected Printer printer = null;
public synchronized void print(byte[] doc) {
getPrinter().printDocument(doc);
}
protected Printer getPrinter() { // PRE: synch lock held
if (printer == null) // need to take from neighbor
printer = neighbor.takePrinter();
return printer;
}
synchronized Printer takePrinter() { // called from others
if (printer != null) {
Printer p = printer; // implement take protocol
printer = null;
return p;
}
else
return neighbor.takePrinter(); // propagate
}
// initialization methods called only during start-up
synchronized void setNeighbor(PrintService n) {
neighbor = n;
}
synchronized void givePrinter(Printer p) {
printer = p;
}
// Sample code to initialize a ring of new services
public static void startUpServices(int nServices, Printer p)
throws IllegalArgumentException {
if (nServices <= 0 || p == null)
throw new IllegalArgumentException();
PrintService first = new PrintService();
PrintService pred = first;
for (int i = 1; i < nServices; ++i) {
PrintService s = new PrintService();
s.setNeighbor(pred);
pred = s;
}
first.setNeighbor(pred);
first.givePrinter(p);
}
}
class AnimationApplet extends Applet { // Fragments
// ...
int framesPerSecond; // default zero is illegal value
void animate() {
try {
if (framesPerSecond == 0) { // the unsynchronized check
synchronized(this) {
if (framesPerSecond == 0) { // the double-check
String param = getParameter("fps");
framesPerSecond = Integer.parseInt(param);
}
}
}
}
catch (Exception e) {}
// ... actions using framesPerSecond ...
}
}
class ServerWithStateUpdate {
private double state;
private final Helper helper = new Helper();
public synchronized void service() {
state = 2.0f; // ...; // set to some new value
helper.operation();
}
public synchronized double getState() { return state; }
}
class ServerWithOpenCall {
private double state;
private final Helper helper = new Helper();
private synchronized void updateState() {
state = 2.0f; // ...; // set to some new value
}
public void service() {
updateState();
helper.operation();
}
public synchronized double getState() { return state; }
}
class ServerWithAssignableHelper {
private double state;
private Helper helper = new Helper();
synchronized void setHelper(Helper h) { helper = h; }
public void service() {
Helper h;
synchronized(this) {
state = 2.0f; // ...
h = helper;
}
h.operation();
}
public synchronized void synchedService() { // see below
service();
}
}
class LinkedCell {
protected int value;
protected final LinkedCell next;
public LinkedCell(int v, LinkedCell t) {
value = v;
next = t;
}
public synchronized int value() { return value; }
public synchronized void setValue(int v) { value = v; }
public int sum() { // add up all element values
return (next == null) ? value() : value() + next.sum();
}
public boolean includes(int x) { // search for x
return (value() == x) ? true:
(next == null)? false : next.includes(x);
}
}
class Shape { // Incomplete
protected double x = 0.0;
protected double y = 0.0;
protected double width = 0.0;
protected double height = 0.0;
public synchronized double x() { return x;}
public synchronized double y() { return y; }
public synchronized double width() { return width;}
public synchronized double height() { return height; }
public synchronized void adjustLocation() {
x = 1; // longCalculation1();
y = 2; //longCalculation2();
}
public synchronized void adjustDimensions() {
width = 3; // longCalculation3();
height = 4; // longCalculation4();
}
// ...
}
class PassThroughShape {
protected final AdjustableLoc loc = new AdjustableLoc(0, 0);
protected final AdjustableDim dim = new AdjustableDim(0, 0);
public double x() { return loc.x(); }
public double y() { return loc.y(); }
public double width() { return dim.width(); }
public double height() { return dim.height(); }
public void adjustLocation() { loc.adjust(); }
public void adjustDimensions() { dim.adjust(); }
}
class AdjustableLoc {
protected double x;
protected double y;
public AdjustableLoc(double initX, double initY) {
x = initX;
y = initY;
}
public synchronized double x() { return x;}
public synchronized double y() { return y; }
public synchronized void adjust() {
x = longCalculation1();
y = longCalculation2();
}
protected double longCalculation1() { return 1; /* ... */ }
protected double longCalculation2() { return 2; /* ... */ }
}
class AdjustableDim {
protected double width;
protected double height;
public AdjustableDim(double initW, double initH) {
width = initW;
height = initH;
}
public synchronized double width() { return width;}
public synchronized double height() { return height; }
public synchronized void adjust() {
width = longCalculation3();
height = longCalculation4();
}
protected double longCalculation3() { return 3; /* ... */ }
protected double longCalculation4() { return 4; /* ... */ }
}
class LockSplitShape { // Incomplete
protected double x = 0.0;
protected double y = 0.0;
protected double width = 0.0;
protected double height = 0.0;
protected final Object locationLock = new Object();
protected final Object dimensionLock = new Object();
public double x() {
synchronized(locationLock) {
return x;
}
}
public double y() {
synchronized(locationLock) {
return y;
}
}
public void adjustLocation() {
synchronized(locationLock) {
x = 1; // longCalculation1();
y = 2; // longCalculation2();
}
}
// and so on
}
class SynchronizedInt {
private int value;
public SynchronizedInt(int v) { value = v; }
public synchronized int get() { return value; }
public synchronized int set(int v) { // returns previous value
int oldValue = value;
value = v;
return oldValue;
}
public synchronized int increment() { return ++value; }
// and so on
}
class Person { // Fragments
// ...
protected final SynchronizedInt age = new SynchronizedInt(0);
protected final SynchronizedBoolean isMarried =
new SynchronizedBoolean(false);
protected final SynchronizedDouble income =
new SynchronizedDouble(0.0);
public int getAge() { return age.get(); }
public void birthday() { age.increment(); }
// ...
}
class LinkedQueue {
protected Node head = new Node(null);
protected Node last = head;
protected final Object pollLock = new Object();
protected final Object putLock = new Object();
public void put(Object x) {
Node node = new Node(x);
synchronized (putLock) { // insert at end of list
synchronized (last) {
last.next = node; // extend list
last = node;
}
}
}
public Object poll() { // returns null if empty
synchronized (pollLock) {
synchronized (head) {
Object x = null;
Node first = head.next; // get to first real node
if (first != null) {
x = first.object;
first.object = null; // forget old object
head = first; // first becomes new head
}
return x;
}
}
}
static class Node { // local node class for queue
Object object;
Node next = null;
Node(Object x) { object = x; }
}
}
class InsufficientFunds extends Exception {}
interface Account {
long balance();
}
interface UpdatableAccount extends Account {
void credit(long amount) throws InsufficientFunds;
void debit(long amount) throws InsufficientFunds;
}
// Sample implementation of updatable version
class UpdatableAccountImpl implements UpdatableAccount {
private long currentBalance;
public UpdatableAccountImpl(long initialBalance) {
currentBalance = initialBalance;
}
public synchronized long balance() {
return currentBalance;
}
public synchronized void credit(long amount)
throws InsufficientFunds {
if (amount >= 0 || currentBalance >= -amount)
currentBalance += amount;
else
throw new InsufficientFunds();
}
public synchronized void debit(long amount)
throws InsufficientFunds {
credit(-amount);
}
}
final class ImmutableAccount implements Account {
private Account delegate;
public ImmutableAccount(long initialBalance) {
delegate = new UpdatableAccountImpl(initialBalance);
}
ImmutableAccount(Account acct) { delegate = acct; }
public long balance() { // forward the immutable method
return delegate.balance();
}
}
class AccountRecorder { // A logging facility
public void recordBalance(Account a) {
System.out.println(a.balance()); // or record in file
}
}
class AccountHolder {
private UpdatableAccount acct = new UpdatableAccountImpl(0);
private AccountRecorder recorder;
public AccountHolder(AccountRecorder r) {
recorder = r;
}
public synchronized void acceptMoney(long amount) {
try {
acct.credit(amount);
recorder.recordBalance(new ImmutableAccount(acct));//(*)
}
catch (InsufficientFunds ex) {
System.out.println("Cannot accept negative amount.");
}
}
}
class EvilAccountRecorder extends AccountRecorder {
private long embezzlement;
// ...
public void recordBalance(Account a) {
super.recordBalance(a);
if (a instanceof UpdatableAccount) {
UpdatableAccount u = (UpdatableAccount)a;
try {
u.debit(10);
embezzlement += 10;
}
catch (InsufficientFunds quietlyignore) {}
}
}
}
class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int initX, int initY) {
x = initX;
y = initY;
}
public int x() { return x; }
public int y() { return y; }
}
class Dot {
protected ImmutablePoint loc;
public Dot(int x, int y) {
loc = new ImmutablePoint(x, y);
}
public synchronized ImmutablePoint location() { return loc; }
protected synchronized void updateLoc(ImmutablePoint newLoc) {
loc = newLoc;
}
public void moveTo(int x, int y) {
updateLoc(new ImmutablePoint(x, y));
}
public synchronized void shiftX(int delta) {
updateLoc(new ImmutablePoint(loc.x() + delta,
loc.y()));
}
}
class CopyOnWriteArrayList { // Incomplete
protected Object[] array = new Object[0];
protected synchronized Object[] getArray() { return array; }
public synchronized void add(Object element) {
int len = array.length;
Object[] newArray = new Object[len+1];
System.arraycopy(array, 0, newArray, 0, len);
newArray[len] = element;
array = newArray;
}
public Iterator iterator() {
return new Iterator() {
protected final Object[] snapshot = getArray();
protected int cursor = 0;
public boolean hasNext() {
return cursor < snapshot.length;
}
public Object next() {
try {
return snapshot[cursor++];
}
catch (IndexOutOfBoundsException ex) {
throw new NoSuchElementException();
}
}
public void remove() {}
};
}
}
class State {}
class Optimistic { // Generic code sketch
private State state; // reference to representation object
private synchronized State getState() { return state; }
private synchronized boolean commit(State assumed,
State next) {
if (state == assumed) {
state = next;
return true;
}
else
return false;
}
}
class OptimisticDot {
protected ImmutablePoint loc;
public OptimisticDot(int x, int y) {
loc = new ImmutablePoint(x, y);
}
public synchronized ImmutablePoint location() { return loc; }
protected synchronized boolean commit(ImmutablePoint assumed,
ImmutablePoint next) {
if (loc == assumed) {
loc = next;
return true;
}
else
return false;
}
public synchronized void moveTo(int x, int y) {
// bypass commit since unconditional
loc = new ImmutablePoint(x, y);
}
public void shiftX(int delta) {
boolean success = false;
do {
ImmutablePoint old = location();
ImmutablePoint next = new ImmutablePoint(old.x() + delta,
old.y());
success = commit(old, next);
} while (!success);
}
}
class ParticleUsingMutex {
protected int x;
protected int y;
protected final Random rng = new Random();
protected final Mutex mutex = new Mutex();
public ParticleUsingMutex(int initialX, int initialY) {
x = initialX;
y = initialY;
}
public void move() {
try {
mutex.acquire();
try {
x += rng.nextInt(10) - 5;
y += rng.nextInt(20) - 10;
}
finally { mutex.release(); }
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
public void draw(Graphics g) {
int lx, ly;
try {
mutex.acquire();
try {
lx = x; ly = y;
}
finally { mutex.release(); }
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
g.drawRect(lx, ly, 10, 10);
}
}
class WithMutex {
private final Mutex mutex;
public WithMutex(Mutex m) { mutex = m; }
public void perform(Runnable r) throws InterruptedException {
mutex.acquire();
try { r.run(); }
finally { mutex.release(); }
}
}
class ParticleUsingWrapper { // Incomplete
protected int x;
protected int y;
protected final Random rng = new Random();
protected final WithMutex withMutex =
new WithMutex(new Mutex());
protected void doMove() {
x += rng.nextInt(10) - 5;
y += rng.nextInt(20) - 10;
}
public void move() {
try {
withMutex.perform(new Runnable() {
public void run() { doMove(); }
});
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
// ...
}
class CellUsingBackoff {
private long value;
private final Mutex mutex = new Mutex();
void swapValue(CellUsingBackoff other) {
if (this == other) return; // alias check required
for (;;) {
try {
mutex.acquire();
try {
if (other.mutex.attempt(0)) {
try {
long t = value;
value = other.value;
other.value = t;
return;
}
finally {
other.mutex.release();
}
}
}
finally {
mutex.release();
};
Thread.sleep(100);
}
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
}
}
}
class CellUsingReorderedBackoff {
private long value;
private final Mutex mutex = new Mutex();
private static boolean trySwap(CellUsingReorderedBackoff a,
CellUsingReorderedBackoff b)
throws InterruptedException {
boolean success = false;
if (a.mutex.attempt(0)) {
try {
if (b.mutex.attempt(0)) {
try {
long t = a.value;
a.value = b.value;
b.value = t;
success = true;
}
finally {
b.mutex.release();
}
}
}
finally {
a.mutex.release();
}
}
return success;
}
void swapValue(CellUsingReorderedBackoff other) {
if (this == other) return; // alias check required
try {
while (!trySwap(this, other) &&
!trySwap(other, this))
Thread.sleep(100);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
class ListUsingMutex {
static class Node {
Object item;
Node next;
Mutex lock = new Mutex(); // each node keeps its own lock
Node(Object x, Node n) { item = x; next = n; }
}
protected Node head; // pointer to first node of list
// Use plain synchronization to protect head field.
// (We could instead use a Mutex here too but there is no
// reason to do so.)
protected synchronized Node getHead() { return head; }
public synchronized void add(Object x) { // simple prepend
// for simplicity here, do not allow null elements
if (x == null) throw new IllegalArgumentException();
// The use of synchronized here protects only head field.
// The method does not need to wait out other traversers
// who have already made it past head node.
head = new Node(x, head);
}
boolean search(Object x) throws InterruptedException {
Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire(); // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
// throw InterruptedException now, so there is no need for
// further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try {
found = x.equals(p.item);
if (!found) {
nextp = p.next;
if (nextp != null) {
try { // Acquire next lock
// while still holding current
nextp.lock.acquire();
}
catch (InterruptedException ie) {
throw ie; // Note that finally clause will
// execute before the throw
}
}
}
}
finally {
p.lock.release();
}
if (found)
return true;
else if (nextp == null)
return false;
else
p = nextp;
}
}
// ... other similar traversal and update methods ...
}
class DataRepository { // code sketch
protected final ReadWriteLock rw = new WriterPreferenceReadWriteLock();
public void access() throws InterruptedException {
rw.readLock().acquire();
try {
/* read data */
}
finally {
rw.readLock().release();
}
}
public void modify() throws InterruptedException {
rw.writeLock().acquire();
try {
/* write data */
}
finally {
rw.writeLock().release();
}
}
}
class ClientUsingSocket { // Code sketch
int portnumber = 1234;
String server = "gee";
// ...
Socket retryUntilConnected() throws InterruptedException {
// first delay is randomly chosen between 5 and 10secs
long delayTime = 5000 + (long)(Math.random() * 5000);
for (;;) {
try {
return new Socket(server, portnumber);
}
catch (IOException ex) {
Thread.sleep(delayTime);
delayTime = delayTime * 3 / 2 + 1; // increase 50%
}
}
}
}
class ServiceException extends Exception {}
interface ServerWithException {
void service() throws ServiceException;
}
interface ServiceExceptionHandler {
void handle(ServiceException e);
}
class ServerImpl implements ServerWithException {
public void service() throws ServiceException {}
}
class HandlerImpl implements ServiceExceptionHandler {
public void handle(ServiceException e) {}
}
class HandledService implements ServerWithException {
final ServerWithException server = new ServerImpl();
final ServiceExceptionHandler handler = new HandlerImpl();
public void service() { // no throw clause
try {
server.service();
}
catch (ServiceException e) {
handler.handle(e);
}
}
}
class ExceptionEvent extends java.util.EventObject {
public final Throwable theException;
public ExceptionEvent(Object src, Throwable ex) {
super(src);
theException = ex;
}
}
class ExceptionEventListener { // Incomplete
public void exceptionOccured(ExceptionEvent ee) {
// ... respond to exception...
}
}
class ServiceIssuingExceptionEvent { // Incomplete
// ...
private final CopyOnWriteArrayList handlers =
new CopyOnWriteArrayList();
public void addHandler(ExceptionEventListener h) {
handlers.add(h);
}
public void service() {
// ...
boolean failed = true;
if (failed) {
Throwable ex = new ServiceException();
ExceptionEvent ee = new ExceptionEvent(this, ex);
for (Iterator it = handlers.iterator(); it.hasNext();) {
ExceptionEventListener l =
(ExceptionEventListener)(it.next());
l.exceptionOccured(ee);
}
}
}
}
class CancellableReader { // Incomplete
private Thread readerThread; // only one at a time supported
private FileInputStream dataFile;
public synchronized void startReaderThread()
throws IllegalStateException, FileNotFoundException {
if (readerThread != null) throw new IllegalStateException();
dataFile = new FileInputStream("data");
readerThread = new Thread(new Runnable() {
public void run() { doRead(); }
});
readerThread.start();
}
protected synchronized void closeFile() { // utility method
if (dataFile != null) {
try { dataFile.close(); }
catch (IOException ignore) {}
dataFile = null;
}
}
void process(int b) {}
private void doRead() {
try {
while (!Thread.interrupted()) {
try {
int c = dataFile.read();
if (c == -1) break;
else process(c);
}
catch (IOException ex) {
break; // perhaps first do other cleanup
}
}
}
finally {
closeFile();
synchronized(this) { readerThread = null; }
}
}
public synchronized void cancelReaderThread() {
if (readerThread != null) readerThread.interrupt();
closeFile();
}
}
class ReaderWithTimeout { // Generic code sketch
// ...
void process(int b) {}
void attemptRead(InputStream stream, long timeout) throws Exception {
long startTime = System.currentTimeMillis();
try {
for (;;) {
if (stream.available() > 0) {
int c = stream.read();
if (c != -1) process(c);
else break; // eof
}
else {
try {
Thread.sleep(100); // arbitrary back-off time
}
catch (InterruptedException ie) {
/* ... quietly wrap up and return ... */
}
long now = System.currentTimeMillis();
if (now - startTime >= timeout) {
/* ... fail ...*/
}
}
}
}
catch (IOException ex) { /* ... fail ... */ }
}
}
class C { // Fragments
private int v; // invariant: v >= 0
synchronized void f() {
v = -1 ; // temporarily set to illegal value as flag
compute(); // possible stop point (*)
v = 1; // set to legal value
}
synchronized void g() {
while (v != 0) {
--v;
something();
}
}
void compute() {}
void something() {}
}
class Terminator {
// Try to kill; return true if known to be dead
static boolean terminate(Thread t, long maxWaitToDie) {
if (!t.isAlive()) return true; // already dead
// phase 1 -- graceful cancellation
t.interrupt();
try { t.join(maxWaitToDie); }
catch(InterruptedException e){} // ignore
if (!t.isAlive()) return true; // success
// phase 2 -- trap all security checks
// theSecurityMgr.denyAllChecksFor(t); // a made-up method
try { t.join(maxWaitToDie); }
catch(InterruptedException ex) {}
if (!t.isAlive()) return true;
// phase 3 -- minimize damage
t.setPriority(Thread.MIN_PRIORITY);
return false;
}
}
interface BoundedCounter {
static final long MIN = 0; // minimum allowed value
static final long MAX = 10; // maximum allowed value
long count(); // INV: MIN <= count() <= MAX
// INIT: count() == MIN
void inc(); // only allowed when count() < MAX
void dec(); // only allowed when count() > MIN
}
class X {
synchronized void w() throws InterruptedException {
before(); wait(); after();
}
synchronized void n() { notifyAll(); }
void before() {}
void after() {}
}
class GuardedClass { // Generic code sketch
protected boolean cond = false;
// PRE: lock held
protected void awaitCond() throws InterruptedException{
while (!cond) wait();
}
public synchronized void guardedAction() {
try {
awaitCond();
}
catch (InterruptedException ie) {
// fail
}
// actions
}
}
class SimpleBoundedCounter {
static final long MIN = 0; // minimum allowed value
static final long MAX = 10; // maximum allowed value
protected long count = MIN;
public synchronized long count() { return count; }
public synchronized void inc() throws InterruptedException {
awaitUnderMax();
setCount(count + 1);
}
public synchronized void dec() throws InterruptedException {
awaitOverMin();
setCount(count - 1);
}
protected void setCount(long newValue) { // PRE: lock held
count = newValue;
notifyAll(); // wake up any thread depending on new value
}
protected void awaitUnderMax() throws InterruptedException {
while (count == MAX) wait();
}
protected void awaitOverMin() throws InterruptedException {
while (count == MIN) wait();
}
}
class GuardedClassUsingNotify {
protected boolean cond = false;
protected int nWaiting = 0; // count waiting threads
protected synchronized void awaitCond()
throws InterruptedException {
while (!cond) {
++nWaiting; // record fact that a thread is waiting
try {
wait();
}
catch (InterruptedException ie) {
notify();
throw ie;
}
finally {
--nWaiting; // no longer waiting
}
}
}
protected synchronized void signalCond() {
if (cond) { // simulate notifyAll
for (int i = nWaiting; i > 0; --i) {
notify();
}
}
}
}
class GamePlayer implements Runnable { // Incomplete
protected GamePlayer other;
protected boolean myturn = false;
protected synchronized void setOther(GamePlayer p) {
other = p;
}
synchronized void giveTurn() { // called by other player
myturn = true;
notify(); // unblock thread
}
void releaseTurn() {
GamePlayer p;
synchronized(this) {
myturn = false;
p = other;
}
p.giveTurn(); // open call
}
synchronized void awaitTurn() throws InterruptedException {
while (!myturn) wait();
}
void move() { /*... perform one move ... */ }
public void run() {
try {
for (;;) {
awaitTurn();
move();
releaseTurn();
}
}
catch (InterruptedException ie) {} // die
}
public static void main(String[] args) {
GamePlayer one = new GamePlayer();
GamePlayer two = new GamePlayer();
one.setOther(two);
two.setOther(one);
one.giveTurn();
new Thread(one).start();
new Thread(two).start();
}
}
//class TimeoutException extends InterruptedException { ... }
class TimeOutBoundedCounter {
static final long MIN = 0; // minimum allowed value
static final long MAX = 10; // maximum allowed value
protected long count = 0;
protected long TIMEOUT = 5000; // for illustration
// ...
synchronized void inc() throws InterruptedException {
if (count >= MAX) {
long start = System.currentTimeMillis();
long waitTime = TIMEOUT;
for (;;) {
if (waitTime <= 0)
throw new TimeoutException(TIMEOUT);
else {
try {
wait(waitTime);
}
catch (InterruptedException ie) {
throw ie; // coded this way just for emphasis
}
if (count < MAX)
break;
else {
long now = System.currentTimeMillis();
waitTime = TIMEOUT - (now - start);
}
}
}
}
++count;
notifyAll();
}
synchronized void dec() throws InterruptedException {
// ... similar ...
}
}
class SpinLock { // Avoid needing to use this
private volatile boolean busy = false;
synchronized void release() { busy = false; }
void acquire() throws InterruptedException {
int itersBeforeYield = 100; // 100 is arbitrary
int itersBeforeSleep = 200; // 200 is arbitrary
long sleepTime = 1; // 1msec is arbitrary
int iters = 0;
for (;;) {
if (!busy) { // test-and-test-and-set
synchronized(this) {
if (!busy) {
busy = true;
return;
}
}
}
if (iters < itersBeforeYield) { // spin phase
++iters;
}
else if (iters < itersBeforeSleep) { // yield phase
++iters;
Thread.yield();
}
else { // back-off phase
Thread.sleep(sleepTime);
sleepTime = 3 * sleepTime / 2 + 1; // 50% is arbitrary
}
}
}
}
class BoundedBufferWithStateTracking {
protected final Object[] array; // the elements
protected int putPtr = 0; // circular indices
protected int takePtr = 0;
protected int usedSlots = 0; // the count
public BoundedBufferWithStateTracking(int capacity)
throws IllegalArgumentException {
if (capacity <= 0) throw new IllegalArgumentException();
array = new Object[capacity];
}
public synchronized int size() { return usedSlots; }
public int capacity() { return array.length; }
public synchronized void put(Object x)
throws InterruptedException {
while (usedSlots == array.length) // wait until not full
wait();
array[putPtr] = x;
putPtr = (putPtr + 1) % array.length; // cyclically inc
if (usedSlots++ == 0) // signal if was empty
notifyAll();
}
public synchronized Object take()
throws InterruptedException{
while (usedSlots == 0) // wait until not empty
wait();
Object x = array[takePtr];
array[takePtr] = null;
takePtr = (takePtr + 1) % array.length;
if (usedSlots-- == array.length) // signal if was full
notifyAll();
return x;
}
}
class BoundedCounterWithStateVariable {
static final long MIN = 0; // minimum allowed value
static final long MAX = 10; // maximum allowed value
static final int BOTTOM = 0, MIDDLE = 1, TOP = 2;
protected int state = BOTTOM; // the state variable
protected long count = MIN;
protected void updateState() { // PRE: synch lock held
int oldState = state;
if (count == MIN) state = BOTTOM;
else if (count == MAX) state = TOP;
else state = MIDDLE;
if (state != oldState && oldState != MIDDLE)
notifyAll(); // notify on transition
}
public synchronized long count() { return count; }
public synchronized void inc() throws InterruptedException {
while (state == TOP) wait();
++count;
updateState();
}
public synchronized void dec() throws InterruptedException {
while (state == BOTTOM) wait();
--count;
updateState();
}
}
class Inventory {
protected final Hashtable items = new Hashtable();
protected final Hashtable suppliers = new Hashtable();
// execution state tracking variables:
protected int storing = 0; // number of in-progress stores
protected int retrieving = 0; // number of retrieves
// ground actions:
protected void doStore(String description, Object item,
String supplier) {
items.put(description, item);
suppliers.put(supplier, description);
}
protected Object doRetrieve(String description) {
Object x = items.get(description);
if (x != null)
items.remove(description);
return x;
}
public void store(String description,
Object item,
String supplier)
throws InterruptedException {
synchronized(this) { // Before-action
while (retrieving != 0) // don't overlap with retrieves
wait();
++storing; // record exec state
}
try {
doStore(description, item, supplier); // Ground action
}
finally { // After-action
synchronized(this) { // signal retrieves
if (--storing == 0) // only necessary when hit zero
notifyAll();
}
}
}
public Object retrieve(String description)
throws InterruptedException {
synchronized(this) { // Before-action
// wait until no stores or retrieves
while (storing != 0 || retrieving != 0)
wait();
++retrieving;
}
try {
return doRetrieve(description); // ground action
}
finally {
synchronized(this) { // After-action
if (--retrieving == 0)
notifyAll();
}
}
}
}
abstract class ReadWrite {
protected int activeReaders = 0; // threads executing read
protected int activeWriters = 0; // always zero or one
protected int waitingReaders = 0; // threads not yet in read
protected int waitingWriters = 0; // same for write
protected abstract void doRead(); // implement in subclasses
protected abstract void doWrite();
public void read() throws InterruptedException {
beforeRead();
try { doRead(); }
finally { afterRead(); }
}
public void write() throws InterruptedException {
beforeWrite();
try { doWrite(); }
finally { afterWrite(); }
}
protected boolean allowReader() {
return waitingWriters == 0 && activeWriters == 0;
}
protected boolean allowWriter() {
return activeReaders == 0 && activeWriters == 0;
}
protected synchronized void beforeRead()
throws InterruptedException {
++waitingReaders;
while (!allowReader()) {
try { wait(); }
catch (InterruptedException ie) {
--waitingReaders; // roll back state
throw ie;
}
}
--waitingReaders;
++activeReaders;
}
protected synchronized void afterRead() {
--activeReaders;
notifyAll();
}
protected synchronized void beforeWrite()
throws InterruptedException {
++waitingWriters;
while (!allowWriter()) {
try { wait(); }
catch (InterruptedException ie) {
--waitingWriters;
throw ie;
}
}
--waitingWriters;
++activeWriters;
}
protected synchronized void afterWrite() {
--activeWriters;
notifyAll();
}
}
class RWLock extends ReadWrite implements ReadWriteLock { // Incomplete
class RLock implements Sync {
public void acquire() throws InterruptedException {
beforeRead();
}
public void release() {
afterRead();
}
public boolean attempt(long msecs)
throws InterruptedException{
return beforeRead(msecs);
}
}
class WLock implements Sync {
public void acquire() throws InterruptedException {
beforeWrite();
}
public void release() {
afterWrite();
}
public boolean attempt(long msecs)
throws InterruptedException{
return beforeWrite(msecs);
}
}
protected final RLock rlock = new RLock();
protected final WLock wlock = new WLock();
public Sync readLock() { return rlock; }
public Sync writeLock() { return wlock; }
public boolean beforeRead(long msecs)
throws InterruptedException {
return true;
// ... time-out version of beforeRead ...
}
public boolean beforeWrite(long msecs)
throws InterruptedException {
return true;
// ... time-out version of beforeWrite ...
}
protected void doRead() {}
protected void doWrite() {}
}
class StackEmptyException extends Exception { }
class Stack { // Fragments
public synchronized boolean isEmpty() { return false; /* ... */ }
public synchronized void push(Object x) { /* ... */ }
public synchronized Object pop() throws StackEmptyException {
if (isEmpty())
throw new StackEmptyException();
else return null;
}
}
class WaitingStack extends Stack {
public synchronized void push(Object x) {
super.push(x);
notifyAll();
}
public synchronized Object waitingPop()
throws InterruptedException {
while (isEmpty()) {
wait();
}
try {
return super.pop();
}
catch (StackEmptyException cannothappen) {
// only possible if pop contains a programming error
throw new Error("Internal implementation error");
}
}
}
class PartWithGuard {
protected boolean cond = false;
synchronized void await() throws InterruptedException {
while (!cond)
wait();
// any other code
}
synchronized void signal(boolean c) {
cond = c;
notifyAll();
}
}
class Host {
protected final PartWithGuard part = new PartWithGuard();
synchronized void rely() throws InterruptedException {
part.await();
}
synchronized void set(boolean c) {
part.signal(c);
}
}
class OwnedPartWithGuard { // Code sketch
protected boolean cond = false;
final Object lock;
OwnedPartWithGuard(Object owner) { lock = owner; }
void await() throws InterruptedException {
synchronized(lock) {
while (!cond)
lock.wait();
// ...
}
}
void signal(boolean c) {
synchronized(lock) {
cond = c;
lock.notifyAll();
}
}
}
class Pool { // Incomplete
protected java.util.ArrayList items = new ArrayList();
protected java.util.HashSet busy = new HashSet();
protected final Semaphore available;
public Pool(int n) {
available = new Semaphore(n);
initializeItems(n);
}
public Object getItem() throws InterruptedException {
available.acquire();
return doGet();
}
public void returnItem(Object x) {
if (doReturn(x))
available.release();
}
protected synchronized Object doGet() {
Object x = items.remove(items.size()-1);
busy.add(x); // put in set to check returns
return x;
}
protected synchronized boolean doReturn(Object x) {
if (busy.remove(x)) {
items.add(x); // put back into available item list
return true;
}
else return false;
}
protected void initializeItems(int n) {
// Somehow create the resource objects
// and place them in items list.
}
}
class BufferArray {
protected final Object[] array; // the elements
protected int putPtr = 0; // circular indices
protected int takePtr = 0;
BufferArray(int n) { array = new Object[n]; }
synchronized void insert(Object x) { // put mechanics
array[putPtr] = x;
putPtr = (putPtr + 1) % array.length;
}
synchronized Object extract() { // take mechanics
Object x = array[takePtr];
array[takePtr] = null;
takePtr = (takePtr + 1) % array.length;
return x;
}
}
class BoundedBufferWithSemaphores {
protected final BufferArray buff;
protected final Semaphore putPermits;
protected final Semaphore takePermits;
public BoundedBufferWithSemaphores(int capacity)
throws IllegalArgumentException {
if (capacity <= 0) throw new IllegalArgumentException();
buff = new BufferArray(capacity);
putPermits = new Semaphore(capacity);
takePermits = new Semaphore(0);
}
public void put(Object x) throws InterruptedException {
putPermits.acquire();
buff.insert(x);
takePermits.release();
}
public Object take() throws InterruptedException {
takePermits.acquire();
Object x = buff.extract();
putPermits.release();
return x;
}
public Object poll(long msecs) throws InterruptedException {
if (!takePermits.attempt(msecs)) return null;
Object x = buff.extract();
putPermits.release();
return x;
}
public boolean offer(Object x, long msecs)
throws InterruptedException {
if (!putPermits.attempt(msecs)) return false;
buff.insert(x);
takePermits.release();
return true;
}
}
class SynchronousChannel /* implements Channel */ {
protected Object item = null; // to hold while in transit
protected final Semaphore putPermit;
protected final Semaphore takePermit;
protected final Semaphore taken;
public SynchronousChannel() {
putPermit = new Semaphore(1);
takePermit = new Semaphore(0);
taken = new Semaphore(0);
}
public void put(Object x) throws InterruptedException {
putPermit.acquire();
item = x;
takePermit.release();
// Must wait until signalled by taker
InterruptedException caught = null;
for (;;) {
try {
taken.acquire();
break;
}
catch(InterruptedException ie) { caught = ie; }
}
if (caught != null) throw caught; // can now rethrow
}
public Object take() throws InterruptedException {
takePermit.acquire();
Object x = item;
item = null;
putPermit.release();
taken.release();
return x;
}
}
class Player implements Runnable { // Code sketch
// ...
protected final Latch startSignal;
Player(Latch l) { startSignal = l; }
public void run() {
try {
startSignal.acquire();
play();
}
catch(InterruptedException ie) { return; }
}
void play() {}
// ...
}
class Game {
// ...
void begin(int nplayers) {
Latch startSignal = new Latch();
for (int i = 0; i < nplayers; ++i)
new Thread(new Player(startSignal)).start();
startSignal.release();
}
}
class LatchingThermometer { // Seldom useful
private volatile boolean ready; // latching
private volatile float temperature;
public double getReading() {
while (!ready)
Thread.yield();
return temperature;
}
void sense(float t) { // called from sensor
temperature = t;
ready = true;
}
}
class FillAndEmpty { // Incomplete
static final int SIZE = 1024; // buffer size, for demo
protected Rendezvous exchanger = new Rendezvous(2);
protected byte readByte() { return 1; /* ... */; }
protected void useByte(byte b) { /* ... */ }
public void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
class FillingLoop implements Runnable { // inner class
public void run() {
byte[] buffer = new byte[SIZE];
int position = 0;
try {
for (;;) {
if (position == SIZE) {
buffer = (byte[])(exchanger.rendezvous(buffer));
position = 0;
}
buffer[position++] = readByte();
}
}
catch (BrokenBarrierException ex) {} // die
catch (InterruptedException ie) {} // die
}
}
class EmptyingLoop implements Runnable { // inner class
public void run() {
byte[] buffer = new byte[SIZE];
int position = SIZE; // force exchange first time through
try {
for (;;) {
if (position == SIZE) {
buffer = (byte[])(exchanger.rendezvous(buffer));
position = 0;
}
useByte(buffer[position++]);
}
}
catch (BrokenBarrierException ex) {} // die
catch (InterruptedException ex) {} // die
}
}
}
class PThreadsStyleBuffer {
private final Mutex mutex = new Mutex();
private final CondVar notFull = new CondVar(mutex);
private final CondVar notEmpty = new CondVar(mutex);
private int count = 0;
private int takePtr = 0;
private int putPtr = 0;
private final Object[] array;
public PThreadsStyleBuffer(int capacity) {
array = new Object[capacity];
}
public void put(Object x) throws InterruptedException {
mutex.acquire();
try {
while (count == array.length)
notFull.await();
array[putPtr] = x;
putPtr = (putPtr + 1) % array.length;
++count;
notEmpty.signal();
}
finally {
mutex.release();
}
}
public Object take() throws InterruptedException {
Object x = null;
mutex.acquire();
try {
while (count == 0)
notEmpty.await();
x = array[takePtr];
array[takePtr] = null;
takePtr = (takePtr + 1) % array.length;
--count;
notFull.signal();
}
finally {
mutex.release();
}
return x;
}
}
class BankAccount {
protected long balance = 0;
public synchronized long balance() {
return balance;
}
public synchronized void deposit(long amount)
throws InsufficientFunds {
if (balance + amount < 0)
throw new InsufficientFunds();
else
balance += amount;
}
public void withdraw(long amount) throws InsufficientFunds {
deposit(-amount);
}
}
class TSBoolean {
private boolean value = false;
// set to true; return old value
public synchronized boolean testAndSet() {
boolean oldValue = value;
value = true;
return oldValue;
}
public synchronized void clear() {
value = false;
}
}
class ATCheckingAccount extends BankAccount {
protected ATSavingsAccount savings;
protected long threshold;
protected TSBoolean transferInProgress = new TSBoolean();
public ATCheckingAccount(long t) { threshold = t; }
// called only upon initialization
synchronized void initSavings(ATSavingsAccount s) {
savings = s;
}
protected boolean shouldTry() { return balance < threshold; }
void tryTransfer() { // called internally or from savings
if (!transferInProgress.testAndSet()) { // if not busy ...
try {
synchronized(this) {
if (shouldTry()) balance += savings.transferOut();
}
}
finally { transferInProgress.clear(); }
}
}
public synchronized void deposit(long amount)
throws InsufficientFunds {
if (balance + amount < 0)
throw new InsufficientFunds();
else {
balance += amount;
tryTransfer();
}
}
}
class ATSavingsAccount extends BankAccount {
protected ATCheckingAccount checking;
protected long maxTransfer;
public ATSavingsAccount(long max) {
maxTransfer = max;
}
// called only upon initialization
synchronized void initChecking(ATCheckingAccount c) {
checking = c;
}
synchronized long transferOut() { // called only from checking
long amount = balance;
if (amount > maxTransfer)
amount = maxTransfer;
if (amount >= 0)
balance -= amount;
return amount;
}
public synchronized void deposit(long amount)
throws InsufficientFunds {
if (balance + amount < 0)
throw new InsufficientFunds();
else {
balance += amount;
checking.tryTransfer();
}
}
}
class Subject {
protected double val = 0.0; // modeled state
protected final EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList observers =
new EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList();
public synchronized double getValue() { return val; }
protected synchronized void setValue(double d) { val = d; }
public void attach(Observer o) { observers.add(o); }
public void detach(Observer o) { observers.remove(o); }
public void changeValue(double newstate) {
setValue(newstate);
for (Iterator it = observers.iterator(); it.hasNext();)
((Observer)(it.next())).changed(this);
}
}
class Observer {
protected double cachedState; // last known state
protected final Subject subj; // only one allowed here
Observer(Subject s) {
subj = s;
cachedState = s.getValue();
display();
}
synchronized void changed(Subject s){
if (s != subj) return; // only one subject
double oldState = cachedState;
cachedState = subj.getValue(); // probe
if (oldState != cachedState)
display();
}
protected void display() {
// somehow display subject state; for example just:
System.out.println(cachedState);
}
}
class Failure extends Exception {}
interface Transactor {
// Enter a new transaction and return true, if can do so
public boolean join(Transaction t);
// Return true if this transaction can be committed
public boolean canCommit(Transaction t);
// Update state to reflect current transaction
public void commit(Transaction t) throws Failure;
// Roll back state (No exception; ignore if inapplicable)
public void abort(Transaction t);
}
class Transaction {
// add anything you want here
}
interface TransBankAccount extends Transactor {
public long balance(Transaction t) throws Failure;
public void deposit(Transaction t, long amount)
throws InsufficientFunds, Failure;
public void withdraw(Transaction t, long amount)
throws InsufficientFunds, Failure;
}
class SimpleTransBankAccount implements TransBankAccount {
protected long balance = 0;
protected long workingBalance = 0; // single shadow copy
protected Transaction currentTx = null; // single transaction
public synchronized long balance(Transaction t) throws Failure {
if (t != currentTx) throw new Failure();
return workingBalance;
}
public synchronized void deposit(Transaction t, long amount)
throws InsufficientFunds, Failure {
if (t != currentTx) throw new Failure();
if (workingBalance < -amount)
throw new InsufficientFunds();
workingBalance += amount;
}
public synchronized void withdraw(Transaction t, long amount)
throws InsufficientFunds, Failure {
deposit(t, -amount);
}
public synchronized boolean join(Transaction t) {
if (currentTx != null) return false;
currentTx = t;
workingBalance = balance;
return true;
}
public synchronized boolean canCommit(Transaction t) {
return (t == currentTx);
}
public synchronized void abort(Transaction t) {
if (t == currentTx)
currentTx = null;
}
public synchronized void commit(Transaction t) throws Failure{
if (t != currentTx) throw new Failure();
balance = workingBalance;
currentTx = null;
}
}
class ProxyAccount /* implements TransBankAccount */ {
private TransBankAccount delegate;
public boolean join(Transaction t) {
return delegate.join(t);
}
public long balance(Transaction t) throws Failure {
return delegate.balance(t);
}
// and so on...
}
class FailedTransferException extends Exception {}
class RetryableTransferException extends Exception {}
class TransactionLogger {
void cancelLogEntry(Transaction t, long amount,
TransBankAccount src, TransBankAccount dst) {}
void logTransfer(Transaction t, long amount,
TransBankAccount src, TransBankAccount dst) {}
void logCompletedTransfer(Transaction t, long amount,
TransBankAccount src, TransBankAccount dst) {}
}
class AccountUser {
TransactionLogger log; // a made-up class
// helper method called on any failure
void rollback(Transaction t, long amount,
TransBankAccount src, TransBankAccount dst) {
log.cancelLogEntry(t, amount, src, dst);
src.abort(t);
dst.abort(t);
}
public boolean transfer(long amount,
TransBankAccount src,
TransBankAccount dst)
throws FailedTransferException, RetryableTransferException {
if (src == null || dst == null) // screen arguments
throw new IllegalArgumentException();
if (src == dst) return true; // avoid aliasing
Transaction t = new Transaction();
log.logTransfer(t, amount, src, dst); // record
if (!src.join(t) || !dst.join(t)) { // cannot join
rollback(t, amount, src, dst);
throw new RetryableTransferException();
}
try {
src.withdraw(t, amount);
dst.deposit(t, amount);
}
catch (InsufficientFunds ex) { // semantic failure
rollback(t, amount, src, dst);
return false;
}
catch (Failure k) { // transaction error
rollback(t, amount, src, dst);
throw new RetryableTransferException();
}
if (!src.canCommit(t) || !dst.canCommit(t)) { // interference
rollback(t, amount, src, dst);
throw new RetryableTransferException();
}
try {
src.commit(t);
dst.commit(t);
log.logCompletedTransfer(t, amount, src, dst);
return true;
}
catch(Failure k) { // commitment failure
rollback(t, amount, src, dst);
throw new FailedTransferException();
}
}
}
class ColoredThing {
protected Color myColor = Color.red; // the sample property
protected boolean changePending;
// vetoable listeners:
protected final VetoableChangeMulticaster vetoers =
new VetoableChangeMulticaster(this);
// also some ordinary listeners:
protected final PropertyChangeMulticaster listeners =
new PropertyChangeMulticaster(this);
// registration methods, including:
void addVetoer(VetoableChangeListener l) {
vetoers.addVetoableChangeListener(l);
}
public synchronized Color getColor() { // property accessor
return myColor;
}
// internal helper methods
protected synchronized void commitColor(Color newColor) {
myColor = newColor;
changePending = false;
}
protected synchronized void abortSetColor() {
changePending = false;
}
public void setColor(Color newColor)
throws PropertyVetoException {
Color oldColor = null;
boolean completed = false;
synchronized (this) {
if (changePending) { // allow only one transaction at a time
throw new PropertyVetoException(
"Concurrent modification", null);
}
else if (newColor == null) { // Argument screening
throw new PropertyVetoException(
"Cannot change color to Null", null);
}
else {
changePending = true;
oldColor = myColor;
}
}
try {
vetoers.fireVetoableChange("color", oldColor, newColor);
// fall through if no exception:
commitColor(newColor);
completed = true;
// notify other listeners that change is committed
listeners.firePropertyChange("color", oldColor, newColor);
}
catch(PropertyVetoException ex) { // abort on veto
abortSetColor();
completed = true;
throw ex;
}
finally { // trap any unchecked exception
if (!completed) abortSetColor();
}
}
}
class Semaphore implements Sync {
protected long permits; // current number of available permits
public Semaphore(long initialPermits) {
permits = initialPermits;
}
public synchronized void release() {
++permits;
notify();
}
public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
synchronized(this) {
try {
while (permits <= 0) wait();
--permits;
}
catch (InterruptedException ie) {
notify();
throw ie;
}
}
}
public boolean attempt(long msecs)throws InterruptedException{
if (Thread.interrupted()) throw new InterruptedException();
synchronized(this) {
if (permits > 0) { // Same as acquire but messier
--permits;
return true;
}
else if (msecs <= 0) // avoid timed wait if not needed
return false;
else {
try {
long startTime = System.currentTimeMillis();
long waitTime = msecs;
for (;;) {
wait(waitTime);
if (permits > 0) {
--permits;
return true;
}
else { // Check for time-out
long now = System.currentTimeMillis();
waitTime = msecs - (now - startTime);
if (waitTime <= 0)
return false;
}
}
}
catch(InterruptedException ie) {
notify();
throw ie;
}
}
}
}
}
final class BoundedBufferWithDelegates {
private Object[] array;
private Exchanger putter;
private Exchanger taker;
public BoundedBufferWithDelegates(int capacity)
throws IllegalArgumentException {
if (capacity <= 0) throw new IllegalArgumentException();
array = new Object[capacity];
putter = new Exchanger(capacity);
taker = new Exchanger(0);
}
public void put(Object x) throws InterruptedException {
putter.exchange(x);
}
public Object take() throws InterruptedException {
return taker.exchange(null);
}
void removedSlotNotification(Exchanger h) { // relay
if (h == putter) taker.addedSlotNotification();
else putter.addedSlotNotification();
}
protected class Exchanger { // Inner class
protected int ptr = 0; // circular index
protected int slots; // number of usable slots
protected int waiting = 0; // number of waiting threads
Exchanger(int n) { slots = n; }
synchronized void addedSlotNotification() {
++slots;
if (waiting > 0) // unblock a single waiting thread
notify();
}
Object exchange(Object x) throws InterruptedException {
Object old = null; // return value
synchronized(this) {
while (slots <= 0) { // wait for slot
++waiting;
try {
wait();
}
catch(InterruptedException ie) {
notify();
throw ie;
}
finally {
--waiting;
}
}
--slots; // use slot
old = array[ptr];
array[ptr] = x;
ptr = (ptr + 1) % array.length; // advance position
}
removedSlotNotification(this); // notify of change
return old;
}
}
}
final class BoundedBufferWithMonitorObjects {
private final Object[] array; // the elements
private int putPtr = 0; // circular indices
private int takePtr = 0;
private int emptySlots; // slot counts
private int usedSlots = 0;
private int waitingPuts = 0; // counts of waiting threads
private int waitingTakes = 0;
private final Object putMonitor = new Object();
private final Object takeMonitor = new Object();
public BoundedBufferWithMonitorObjects(int capacity)
throws IllegalArgumentException {
if (capacity <= 0)
throw new IllegalArgumentException();
array = new Object[capacity];
emptySlots = capacity;
}
public void put(Object x) throws InterruptedException {
synchronized(putMonitor) {
while (emptySlots <= 0) {
++waitingPuts;
try { putMonitor.wait(); }
catch(InterruptedException ie) {
putMonitor.notify();
throw ie;
}
finally { --waitingPuts; }
}
--emptySlots;
array[putPtr] = x;
putPtr = (putPtr + 1) % array.length;
}
synchronized(takeMonitor) { // directly notify
++usedSlots;
if (waitingTakes > 0)
takeMonitor.notify();
}
}
public Object take() throws InterruptedException {
Object old = null;
synchronized(takeMonitor) {
while (usedSlots <= 0) {
++waitingTakes;
try { takeMonitor.wait(); }
catch(InterruptedException ie) {
takeMonitor.notify();
throw ie;
}
finally { --waitingTakes; }
}
--usedSlots;
old = array[takePtr];
array[takePtr] = null;
takePtr = (takePtr + 1) % array.length;
}
synchronized(putMonitor) {
++emptySlots;
if (waitingPuts > 0)
putMonitor.notify();
}
return old;
}
}
class FIFOSemaphore extends Semaphore {
protected final WaitQueue queue = new WaitQueue();
public FIFOSemaphore(long initialPermits) {
super(initialPermits);
}
public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
WaitNode node = null;
synchronized(this) {
if (permits > 0) { // no need to queue
--permits;
return;
}
else {
node = new WaitNode();
queue.enq(node);
}
}
// must release lock before node wait
node.doWait();
}
public synchronized void release() {
for (;;) { // retry until success
WaitNode node = queue.deq();
if (node == null) { // queue is empty
++permits;
return;
}
else if (node.doNotify())
return;
// else node was already released due to
// interruption or time-out, so must retry
}
}
// Queue node class. Each node serves as a monitor.
protected static class WaitNode {
boolean released = false;
WaitNode next = null;
synchronized void doWait() throws InterruptedException {
try {
while (!released)
wait();
}
catch (InterruptedException ie) {
if (!released) { // Interrupted before notified
// Suppress future notifications:
released = true;
throw ie;
}
else { // Interrupted after notified
// Ignore exception but propagate status:
Thread.currentThread().interrupt();
}
}
}
synchronized boolean doNotify() { // return true if notified
if (released) // was interrupted or timed out
return false;
else {
released = true;
notify();
return true;
}
}
synchronized boolean doTimedWait(long msecs)
throws InterruptedException {
return true;
// similar
}
}
// Standard linked queue class.
// Used only when holding Semaphore lock.
protected static class WaitQueue {
protected WaitNode head = null;
protected WaitNode last = null;
protected void enq(WaitNode node) {
if (last == null)
head = last = node;
else {
last.next = node;
last = node;
}
}
protected WaitNode deq() {
WaitNode node = head;
if (node != null) {
head = node.next;
if (head == null) last = null;
node.next = null;
}
return node;
}
}
}
class WebService implements Runnable {
static final int PORT = 1040; // just for demo
Handler handler = new Handler();
public void run() {
try {
ServerSocket socket = new ServerSocket(PORT);
for (;;) {
final Socket connection = socket.accept();
new Thread(new Runnable() {
public void run() {
handler.process(connection);
}}).start();
}
}
catch(Exception e) { } // die
}
public static void main(String[] args) {
new Thread(new WebService()).start();
}
}
class Handler {
void process(Socket s) {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(s.getInputStream());
out = new DataOutputStream(s.getOutputStream());
int request = in.readInt();
int result = -request; // return negation to client
out.writeInt(result);
}
catch(IOException ex) {} // fall through
finally { // clean up
try { if (in != null) in.close(); }
catch (IOException ignore) {}
try { if (out != null) out.close(); }
catch (IOException ignore) {}
try { s.close(); }
catch (IOException ignore) {}
}
}
}
class OpenCallHost { // Generic code sketch
protected long localState;
protected final Helper helper = new Helper();
protected synchronized void updateState() {
localState = 2; // ...;
}
public void req() {
updateState();
helper.handle();
}
}
class ThreadPerMessageHost { // Generic code sketch
protected long localState;
protected final Helper helper = new Helper();
protected synchronized void updateState() {
localState = 2; // ...;
}
public void req() {
updateState();
new Thread(new Runnable() {
public void run() {
helper.handle();
}
}).start();
}
}
interface Executor {
void execute(Runnable r);
}
class HostWithExecutor { // Generic code sketch
protected long localState;
protected final Helper helper = new Helper();
protected final Executor executor;
public HostWithExecutor(Executor e) { executor = e; }
protected synchronized void updateState() {
localState = 2; // ...;
}
public void req() {
updateState();
executor.execute(new Runnable() {
public void run() {
helper.handle();
}
});
}
}
class PlainWorkerPool implements Executor {
protected final Channel workQueue;
public void execute(Runnable r) {
try {
workQueue.put(r);
}
catch (InterruptedException ie) { // postpone response
Thread.currentThread().interrupt();
}
}
public PlainWorkerPool(Channel ch, int nworkers) {
workQueue = ch;
for (int i = 0; i < nworkers; ++i) activate();
}
protected void activate() {
Runnable runLoop = new Runnable() {
public void run() {
try {
for (;;) {
Runnable r = (Runnable)(workQueue.take());
r.run();
}
}
catch (InterruptedException ie) {} // die
}
};
new Thread(runLoop).start();
}
}
class TimerDaemon { // Fragments
static class TimerTask implements Comparable {
final Runnable command;
final long execTime; // time to run at
public int compareTo(Object x) {
long otherExecTime = ((TimerTask)(x)).execTime;
return (execTime < otherExecTime) ? -1 :
(execTime == otherExecTime)? 0 : 1;
}
TimerTask(Runnable r, long t) { command = r; execTime = t; }
}
// a heap or list with methods that preserve
// ordering with respect to TimerTask.compareTo
static class PriorityQueue {
void put(TimerTask t) {}
TimerTask least() { return null; }
void removeLeast() {}
boolean isEmpty() { return true; }
}
protected final PriorityQueue pq = new PriorityQueue();
public synchronized void executeAfterDelay(Runnable r,long t){
pq.put(new TimerTask(r, t + System.currentTimeMillis()));
notifyAll();
}
public synchronized void executeAt(Runnable r, Date time) {
pq.put(new TimerTask(r, time.getTime()));
notifyAll();
}
// wait for and then return next task to run
protected synchronized Runnable take()
throws InterruptedException {
for (;;) {
while (pq.isEmpty())
wait();
TimerTask t = pq.least();
long now = System.currentTimeMillis();
long waitTime = now - t.execTime;
if (waitTime <= 0) {
pq.removeLeast();
return t.command;
}
else
wait(waitTime);
}
}
public TimerDaemon() { activate(); } // only one
void activate() {
// same as PlainWorkerThread except using above take method
}
}
class SessionTask implements Runnable { // generic code sketch
static final int BUFFSIZE = 1024;
protected final Socket socket;
protected final InputStream input;
SessionTask(Socket s) throws IOException {
socket = s; input = socket.getInputStream();
}
void processCommand(byte[] b, int n) {}
void cleanup() {}
public void run() { // Normally run in a new thread
byte[] commandBuffer = new byte[BUFFSIZE];
try {
for (;;) {
int bytes = input.read(commandBuffer, 0, BUFFSIZE);
if (bytes != BUFFSIZE) break;
processCommand(commandBuffer, bytes);
}
}
catch (IOException ex) {
cleanup();
}
finally {
try { input.close(); socket.close(); }
catch(IOException ignore) {}
}
}
}
class IOEventTask implements Runnable { // generic code sketch
static final int BUFFSIZE = 1024;
protected final Socket socket;
protected final InputStream input;
protected volatile boolean done = false; // latches true
IOEventTask(Socket s) throws IOException {
socket = s; input = socket.getInputStream();
}
void processCommand(byte[] b, int n) {}
void cleanup() {}
public void run() { // trigger only when input available
if (done) return;
byte[] commandBuffer = new byte[BUFFSIZE];
try {
int bytes = input.read(commandBuffer, 0, BUFFSIZE);
if (bytes != BUFFSIZE) done = true;
else processCommand(commandBuffer, bytes);
}
catch (IOException ex) {
cleanup();
done = true;
}
finally {
if (!done) return;
try { input.close(); socket.close(); }
catch(IOException ignore) {}
}
}
// Accessor methods needed by triggering agent:
boolean done() { return done; }
InputStream input() { return input; }
}
class PollingWorker implements Runnable { // Incomplete
private java.util.List tasks = new LinkedList(); // ...;
private long sleepTime = 100; // ...;
void register(IOEventTask t) { tasks.add(t); }
void deregister(IOEventTask t) { tasks.remove(t); }
public void run() {
try {
for (;;) {
for (Iterator it = tasks.iterator(); it.hasNext();) {
IOEventTask t = (IOEventTask)(it.next());
if (t.done())
deregister(t);
else {
boolean trigger;
try {
trigger = t.input().available() > 0;
}
catch (IOException ex) {
trigger = true; // trigger if exception on check
}
if (trigger)
t.run();
}
}
Thread.sleep(sleepTime);
}
}
catch (InterruptedException ie) {}
}
}
abstract class Box {
protected Color color = Color.white;
public synchronized Color getColor() { return color; }
public synchronized void setColor(Color c) { color = c; }
public abstract java.awt.Dimension size();
public abstract Box duplicate(); // clone
public abstract void show(Graphics g, Point origin);// display
}
class BasicBox extends Box {
protected Dimension size;
public BasicBox(int xdim, int ydim) {
size = new Dimension(xdim, ydim);
}
public synchronized Dimension size() { return size; }
public void show(Graphics g, Point origin) {
g.setColor(getColor());
g.fillRect(origin.x, origin.y, size.width, size.height);
}
public synchronized Box duplicate() {
Box p = new BasicBox(size.width, size.height);
p.setColor(getColor());
return p;
}
}
abstract class JoinedPair extends Box {
protected Box fst; // one of the boxes
protected Box snd; // the other one
protected JoinedPair(Box a, Box b) {
fst = a;
snd = b;
}
public synchronized void flip() { // swap fst/snd
Box tmp = fst; fst = snd; snd = tmp;
}
public void show(Graphics g, Point p) {}
public Dimension size() { return new Dimension(0,0); }
public Box duplicate() { return null; }
// other internal helper methods
}
class HorizontallyJoinedPair extends JoinedPair {
public HorizontallyJoinedPair(Box l, Box r) {
super(l, r);
}
public synchronized Box duplicate() {
HorizontallyJoinedPair p =
new HorizontallyJoinedPair(fst.duplicate(),
snd.duplicate());
p.setColor(getColor());
return p;
}
// ... other implementations of abstract Box methods
}
class VerticallyJoinedPair extends JoinedPair {
public VerticallyJoinedPair(Box l, Box r) {
super(l, r);
}
// similar
}
class WrappedBox extends Box {
protected Dimension wrapperSize;
protected Box inner;
public WrappedBox(Box innerBox, Dimension size) {
inner = innerBox;
wrapperSize = size;
}
public void show(Graphics g, Point p) {}
public Dimension size() { return new Dimension(0,0); }
public Box duplicate() { return null; }
// ... other implementations of abstract Box methods
}
interface PushSource {
void start();
}
interface PushStage {
void putA(Box p);
}
interface DualInputPushStage extends PushStage {
void putB(Box p);
}
class DualInputAdapter implements PushStage {
protected final DualInputPushStage stage;
public DualInputAdapter(DualInputPushStage s) { stage = s; }
public void putA(Box p) { stage.putB(p); }
}
class DevNull implements PushStage {
public void putA(Box p) { }
}
class SingleOutputPushStage {
private PushStage next1 = null;
protected synchronized PushStage next1() { return next1; }
public synchronized void attach1(PushStage s) { next1 = s; }
}
class DualOutputPushStage extends SingleOutputPushStage {
private PushStage next2 = null;
protected synchronized PushStage next2() { return next2; }
public synchronized void attach2(PushStage s) { next2 = s; }
}class Painter extends SingleOutputPushStage
implements PushStage {
protected final Color color; // the color to paint things
public Painter(Color c) { color = c; }
public void putA(Box p) {
p.setColor(color);
next1().putA(p);
}
}
class Wrapper extends SingleOutputPushStage
implements PushStage {
protected final int thickness;
public Wrapper(int t) { thickness = t; }
public void putA(Box p) {
Dimension d = new Dimension(thickness, thickness);
next1().putA(new WrappedBox(p, d));
}
}
class Flipper extends SingleOutputPushStage
implements PushStage {
public void putA(Box p) {
if (p instanceof JoinedPair)
((JoinedPair) p).flip();
next1().putA(p);
}
}
abstract class Joiner extends SingleOutputPushStage
implements DualInputPushStage {
protected Box a = null; // incoming from putA
protected Box b = null; // incoming from putB
protected abstract Box join(Box p, Box q);
protected synchronized Box joinFromA(Box p) {
while (a != null) // wait until last consumed
try { wait(); }
catch (InterruptedException e) { return null; }
a = p;
return tryJoin();
}
protected synchronized Box joinFromB(Box p) { // symmetrical
while (b != null)
try { wait(); }
catch (InterruptedException ie) { return null; }
b = p;
return tryJoin();
}
protected synchronized Box tryJoin() {
if (a == null || b == null) return null; // cannot join
Box joined = join(a, b); // make combined box
a = b = null; // forget old boxes
notifyAll(); // allow new puts
return joined;
}
public void putA(Box p) {
Box j = joinFromA(p);
if (j != null) next1().putA(j);
}
public void putB(Box p) {
Box j = joinFromB(p);
if (j != null) next1().putA(j);
}
}
class HorizontalJoiner extends Joiner {
protected Box join(Box p, Box q) {
return new HorizontallyJoinedPair(p, q);
}
}
class VerticalJoiner extends Joiner {
protected Box join(Box p, Box q) {
return new VerticallyJoinedPair(p, q);
}
}
class Collector extends SingleOutputPushStage
implements DualInputPushStage {
public void putA(Box p) { next1().putA(p);}
public void putB(Box p) { next1().putA(p); }
}
class Alternator extends DualOutputPushStage
implements PushStage {
protected boolean outTo2 = false; // control alternation
protected synchronized boolean testAndInvert() {
boolean b = outTo2;
outTo2 = !outTo2;
return b;
}
public void putA(final Box p) {
if (testAndInvert())
next1().putA(p);
else {
new Thread(new Runnable() {
public void run() { next2().putA(p); }
}).start();
}
}
}
class Cloner extends DualOutputPushStage
implements PushStage {
public void putA(Box p) {
final Box p2 = p.duplicate();
next1().putA(p);
new Thread(new Runnable() {
public void run() { next2().putA(p2); }
}).start();
}
}
interface BoxPredicate {
boolean test(Box p);
}
class MaxSizePredicate implements BoxPredicate {
protected final int max; // max size to let through
public MaxSizePredicate(int maximum) { max = maximum; }
public boolean test(Box p) {
return p.size().height <= max && p.size().width <= max;
}
}
class Screener extends DualOutputPushStage
implements PushStage {
protected final BoxPredicate predicate;
public Screener(BoxPredicate p) { predicate = p; }
public void putA(final Box p) {
if (predicate.test(p)) {
new Thread(new Runnable() {
public void run() { next1().putA(p); }
}).start();
}
else
next2().putA(p);
}
}
class BasicBoxSource extends SingleOutputPushStage
implements PushSource, Runnable {
protected final Dimension size; // maximum sizes
protected final int productionTime; // simulated delay
public BasicBoxSource(Dimension s, int delay) {
size = s;
productionTime = delay;
}
protected Box produce() {
return new BasicBox((int)(Math.random() * size.width) + 1,
(int)(Math.random() * size.height) + 1);
}
public void start() {
next1().putA(produce());
}
public void run() {
try {
for (;;) {
start();
Thread.sleep((int)(Math.random() * 2* productionTime));
}
}
catch (InterruptedException ie) { } // die
}
}
interface FileReader {
void read(String filename, FileReaderClient client);
}
interface FileReaderClient {
void readCompleted(String filename, byte[] data);
void readFailed(String filename, IOException ex);
}
class FileReaderApp implements FileReaderClient { // Fragments
protected FileReader reader = new AFileReader();
public void readCompleted(String filename, byte[] data) {
// ... use data ...
}
public void readFailed(String filename, IOException ex){
// ... deal with failure ...
}
public void actionRequiringFile() {
reader.read("AppFile", this);
}
public void actionNotRequiringFile() { }
}
class AFileReader implements FileReader {
public void read(final String fn, final FileReaderClient c) {
new Thread(new Runnable() {
public void run() { doRead(fn, c); }
}).start();
}
protected void doRead(String fn, FileReaderClient client) {
byte[] buffer = new byte[1024]; // just for illustration
try {
FileInputStream s = new FileInputStream(fn);
s.read(buffer);
if (client != null) client.readCompleted(fn, buffer);
}
catch (IOException ex) {
if (client != null) client.readFailed(fn, ex);
}
}
}
class FileApplication implements FileReaderClient {
private String[] filenames;
private int currentCompletion; // index of ready file
public synchronized void readCompleted(String fn, byte[] d) {
// wait until ready to process this callback
while (!fn.equals(filenames[currentCompletion])) {
try { wait(); }
catch(InterruptedException ex) { return; }
}
// ... process data...
// wake up any other thread waiting on this condition:
++currentCompletion;
notifyAll();
}
public synchronized void readFailed(String fn, IOException e){
// similar...
}
public synchronized void readfiles() {
AFileReader reader = new AFileReader();
currentCompletion = 0;
for (int i = 0; i < filenames.length; ++i)
reader.read(filenames[i],this);
}
}
interface Pic {
byte[] getImage();
}
interface Renderer {
Pic render(URL src);
}
class StandardRenderer implements Renderer {
public Pic render(URL src) { return null ; }
}
class PictureApp { // Code sketch
// ...
private final Renderer renderer = new StandardRenderer();
void displayBorders() {}
void displayCaption() {}
void displayImage(byte[] b) {}
void cleanup() {}
public void show(final URL imageSource) {
class Waiter implements Runnable {
private Pic result = null;
Pic getResult() { return result; }
public void run() {
result = renderer.render(imageSource);
}
};
Waiter waiter = new Waiter();
Thread t = new Thread(waiter);
t.start();
displayBorders(); // do other things
displayCaption(); // while rendering
try {
t.join();
}
catch(InterruptedException e) {
cleanup();
return;
}
Pic pic = waiter.getResult();
if (pic != null)
displayImage(pic.getImage());
else {}
// ... deal with assumed rendering failure
}
}
class AsynchRenderer implements Renderer {
private final Renderer renderer = new StandardRenderer();
static class FuturePic implements Pic { // inner class
private Pic pic = null;
private boolean ready = false;
synchronized void setPic(Pic p) {
pic = p;
ready = true;
notifyAll();
}
public synchronized byte[] getImage() {
while (!ready)
try { wait(); }
catch (InterruptedException e) { return null; }
return pic.getImage();
}
}
public Pic render(final URL src) {
final FuturePic p = new FuturePic();
new Thread(new Runnable() {
public void run() { p.setPic(renderer.render(src)); }
}).start();
return p;
}
}
class PicturAppWithFuture { // Code sketch
private final Renderer renderer = new AsynchRenderer();
void displayBorders() {}
void displayCaption() {}
void displayImage(byte[] b) {}
void cleanup() {}
public void show(final URL imageSource) {
Pic pic = renderer.render(imageSource);
displayBorders(); // do other things ...
displayCaption();
byte[] im = pic.getImage();
if (im != null)
displayImage(im);
else {} // deal with assumed rendering failure
}
}
class FutureResult { // Fragments
protected Object value = null;
protected boolean ready = false;
protected InvocationTargetException exception = null;
public synchronized Object get()
throws InterruptedException, InvocationTargetException {
while (!ready) wait();
if (exception != null)
throw exception;
else
return value;
}
public Runnable setter(final Callable function) {
return new Runnable() {
public void run() {
try {
set(function.call());
}
catch(Throwable e) {
setException(e);
}
}
};
}
synchronized void set(Object result) {
value = result;
ready = true;
notifyAll();
}
synchronized void setException(Throwable e) {
exception = new InvocationTargetException(e);
ready = true;
notifyAll();
}
// ... other auxiliary and convenience methods ...
}
class PictureDisplayWithFutureResult { // Code sketch
void displayBorders() {}
void displayCaption() {}
void displayImage(byte[] b) {}
void cleanup() {}
private final Renderer renderer = new StandardRenderer();
// ...
public void show(final URL imageSource) {
try {
FutureResult futurePic = new FutureResult();
Runnable command = futurePic.setter(new Callable() {
public Object call() {
return renderer.render(imageSource);
}
});
new Thread(command).start();
displayBorders();
displayCaption();
displayImage(((Pic)(futurePic.get())).getImage());
}
catch (InterruptedException ex) {
cleanup();
return;
}
catch (InvocationTargetException ex) {
cleanup();
return;
}
}
}
interface Disk {
void read(int cylinderNumber, byte[] buffer) throws Failure;
void write(int cylinderNumber, byte[] buffer) throws Failure;
}
abstract class DiskTask implements Runnable {
protected final int cylinder; // read/write parameters
protected final byte[] buffer;
protected Failure exception = null; // to relay out
protected DiskTask next = null; // for use in queue
protected final Latch done = new Latch(); // status indicator
DiskTask(int c, byte[] b) { cylinder = c; buffer = b; }
abstract void access() throws Failure; // read or write
public void run() {
try { access(); }
catch (Failure ex) { setException(ex); }
finally { done.release(); }
}
void awaitCompletion() throws InterruptedException {
done.acquire();
}
synchronized Failure getException() { return exception; }
synchronized void setException(Failure f) { exception = f; }
}
class DiskReadTask extends DiskTask {
DiskReadTask(int c, byte[] b) { super(c, b); }
void access() throws Failure { /* ... raw read ... */ }
}
class DiskWriteTask extends DiskTask {
DiskWriteTask(int c, byte[] b) { super(c, b); }
void access() throws Failure { /* ... raw write ... */ }
}
class ScheduledDisk implements Disk {
protected final DiskTaskQueue tasks = new DiskTaskQueue();
public void read(int c, byte[] b) throws Failure {
readOrWrite(new DiskReadTask(c, b));
}
public void write(int c, byte[] b) throws Failure {
readOrWrite(new DiskWriteTask(c, b));
}
protected void readOrWrite(DiskTask t) throws Failure {
tasks.put(t);
try {
t.awaitCompletion();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt(); // propagate
throw new Failure(); // convert to failure exception
}
Failure f = t.getException();
if (f != null) throw f;
}
public ScheduledDisk() { // construct worker thread
new Thread(new Runnable() {
public void run() {
try {
for (;;) {
tasks.take().run();
}
}
catch (InterruptedException ex) {} // die
}
}).start();
}
}
class DiskTaskQueue {
protected DiskTask thisSweep = null;
protected DiskTask nextSweep = null;
protected int currentCylinder = 0;
protected final Semaphore available = new Semaphore(0);
void put(DiskTask t) {
insert(t);
available.release();
}
DiskTask take() throws InterruptedException {
available.acquire();
return extract();
}
synchronized void insert(DiskTask t) {
DiskTask q;
if (t.cylinder >= currentCylinder) { // determine queue
q = thisSweep;
if (q == null) { thisSweep = t; return; }
}
else {
q = nextSweep;
if (q == null) { nextSweep = t; return; }
}
DiskTask trail = q; // ordered linked list insert
q = trail.next;
for (;;) {
if (q == null || t.cylinder < q.cylinder) {
trail.next = t; t.next = q;
return;
}
else {
trail = q; q = q.next;
}
}
}
synchronized DiskTask extract() { // PRE: not empty
if (thisSweep == null) { // possibly swap queues
thisSweep = nextSweep;
nextSweep = null;
}
DiskTask t = thisSweep;
thisSweep = t.next;
currentCylinder = t.cylinder;
return t;
}
}
class Fib extends FJTask {
static final int sequentialThreshold = 13; // for tuning
volatile int number; // argument/result
Fib(int n) { number = n; }
int seqFib(int n) {
if (n <= 1)
return n;
else
return seqFib(n-1) + seqFib(n-2);
}
int getAnswer() {
if (!isDone())
throw new IllegalStateException("Not yet computed");
return number;
}
public void run() {
int n = number;
if (n <= sequentialThreshold) // base case
number = seqFib(n);
else {
Fib f1 = new Fib(n - 1); // create subtasks
Fib f2 = new Fib(n - 2);
coInvoke(f1, f2); // fork then join both
number = f1.number + f2.number; // combine results
}
}
public static void main(String[] args) { // sample driver
try {
int groupSize = 2; // 2 worker threads
int num = 35; // compute fib(35)
FJTaskRunnerGroup group = new FJTaskRunnerGroup(groupSize);
Fib f = new Fib(num);
group.invoke(f);
int result = f.getAnswer();
System.out.println("Answer: " + result);
}
catch (InterruptedException ex) {} // die
}
}
class FibVL extends FJTask {
static final int sequentialThreshold = 13; // for tuning
volatile int number; // as before
final FibVL next; // embedded linked list of sibling tasks
FibVL(int n, FibVL list) { number = n; next = list; }
int seqFib(int n) {
if (n <= 1)
return n;
else
return seqFib(n-1) + seqFib(n-2);
}
public void run() {
int n = number;
if (n <= sequentialThreshold)
number = seqFib(n);
else {
FibVL forked = null; // list of subtasks
forked = new FibVL(n - 1, forked); // prepends to list
forked.fork();
forked = new FibVL(n - 2, forked);
forked.fork();
number = accumulate(forked);
}
}
// Traverse list, joining each subtask and adding to result
int accumulate(FibVL list) {
int r = 0;
for (FibVL f = list; f != null; f = f.next) {
f.join();
r += f.number;
}
return r;
}
}
class FibVCB extends FJTask {
static final int sequentialThreshold = 13; // for tuning
// ...
volatile int number = 0; // as before
final FibVCB parent; // Is null for outermost call
int callbacksExpected = 0;
volatile int callbacksReceived = 0;
FibVCB(int n, FibVCB p) { number = n; parent = p; }
int seqFib(int n) {
if (n <= 1)
return n;
else
return seqFib(n-1) + seqFib(n-2);
}
// Callback method invoked by subtasks upon completion
synchronized void addToResult(int n) {
number += n;
++callbacksReceived;
}
public void run() { // same structure as join-based version
int n = number;
if (n <= sequentialThreshold)
number = seqFib(n);
else {
// clear number so subtasks can fill in
number = 0;
// establish number of callbacks expected
callbacksExpected = 2;
new FibVCB(n - 1, this).fork();
new FibVCB(n - 2, this).fork();
// Wait for callbacks from children
while (callbacksReceived < callbacksExpected) yield();
}
// Call back parent
if (parent != null) parent.addToResult(number);
}
}
class NQueens extends FJTask {
static int boardSize; // fixed after initialization in main
// Boards are arrays where each cell represents a row,
// and holds the column number of the queen in that row
static class Result { // holder for ultimate result
private int[] board = null; // non-null when solved
synchronized boolean solved() { return board != null; }
synchronized void set(int[] b) { // Support use by non-Tasks
if (board == null) { board = b; notifyAll(); }
}
synchronized int[] await() throws InterruptedException {
while (board == null) wait();
return board;
}
}
static final Result result = new Result();
public static void main(String[] args) {
try {
boardSize = 8; // ...;
FJTaskRunnerGroup tasks = new FJTaskRunnerGroup(4);
int[] initialBoard = new int[0]; // start with empty board
tasks.execute(new NQueens(initialBoard));
int[] board = result.await();
}
catch (InterruptedException ie) {}
// ...
}
final int[] sofar; // initial configuration
NQueens(int[] board) { this.sofar = board; }
public void run() {
if (!result.solved()) { // skip if already solved
int row = sofar.length;
if (row >= boardSize) // done
result.set(sofar);
else { // try all expansions
for (int q = 0; q < boardSize; ++q) {
// Check if queen can be placed in column q of next row
boolean attacked = false;
for (int i = 0; i < row; ++i) {
int p = sofar[i];
if (q == p || q == p - (row-i) || q == p + (row-i)) {
attacked = true;
break;
}
}
// If so, fork to explore moves from new configuration
if (!attacked) {
// build extended board representation
int[] next = new int[row+1];
for (int k = 0; k < row; ++k) next[k] = sofar[k];
next[row] = q;
new NQueens(next).fork();
}
}
}
}
}
}
abstract class JTree extends FJTask {
volatile double maxDiff; // for convergence check
}
class Interior extends JTree {
private final JTree[] quads;
Interior(JTree q1, JTree q2, JTree q3, JTree q4) {
quads = new JTree[] { q1, q2, q3, q4 };
}
public void run() {
coInvoke(quads);
double md = 0.0;
for (int i = 0; i < quads.length; ++i) {
md = Math.max(md,quads[i].maxDiff);
quads[i].reset();
}
maxDiff = md;
}
}
class Leaf extends JTree {
private final double[][] A; private final double[][] B;
private final int loRow; private final int hiRow;
private final int loCol; private final int hiCol;
private int steps = 0;
Leaf(double[][] A, double[][] B,
int loRow, int hiRow, int loCol, int hiCol) {
this.A = A; this.B = B;
this.loRow = loRow; this.hiRow = hiRow;
this.loCol = loCol; this.hiCol = hiCol;
}
public synchronized void run() {
boolean AtoB = (steps++ % 2) == 0;
double[][] a = (AtoB)? A : B;
double[][] b = (AtoB)? B : A;
double md = 0.0;
for (int i = loRow; i <= hiRow; ++i) {
for (int j = loCol; j <= hiCol; ++j) {
b[i][j] = 0.25 * (a[i-1][j] + a[i][j-1] +
a[i+1][j] + a[i][j+1]);
md = Math.max(md, Math.abs(b[i][j] - a[i][j]));
}
}
maxDiff = md;
}
}
class Jacobi extends FJTask {
static final double EPSILON = 0.001; // convergence criterion
final JTree root;
final int maxSteps;
Jacobi(double[][] A, double[][] B,
int firstRow, int lastRow, int firstCol, int lastCol,
int maxSteps, int leafCells) {
this.maxSteps = maxSteps;
root = build(A, B, firstRow, lastRow, firstCol, lastCol,
leafCells);
}
public void run() {
for (int i = 0; i < maxSteps; ++i) {
invoke(root);
if (root.maxDiff < EPSILON) {
System.out.println("Converged");
return;
}
else root.reset();
}
}
static JTree build(double[][] a, double[][] b,
int lr, int hr, int lc, int hc, int size) {
if ((hr - lr + 1) * (hc - lc + 1) <= size)
return new Leaf(a, b, lr, hr, lc, hc);
int mr = (lr + hr) / 2; // midpoints
int mc = (lc + hc) / 2;
return new Interior(build(a, b, lr, mr, lc, mc, size),
build(a, b, lr, mr, mc+1, hc, size),
build(a, b, mr+1, hr, lc, mc, size),
build(a, b, mr+1, hr, mc+1, hc, size));
}
}
class CyclicBarrier {
protected final int parties;
protected int count; // parties currently being waited for
protected int resets = 0; // times barrier has been tripped
CyclicBarrier(int c) { count = parties = c; }
synchronized int barrier() throws InterruptedException {
int index = --count;
if (index > 0) { // not yet tripped
int r = resets; // wait until next reset
do { wait(); } while (resets == r);
}
else { // trip
count = parties; // reset count for next time
++resets;
notifyAll(); // cause all other parties to resume
}
return index;
}
}
class Segment implements Runnable { // Code sketch
final CyclicBarrier bar; // shared by all segments
Segment(CyclicBarrier b) { bar = b; }
void update() { }
public void run() {
// ...
try {
for (int i = 0; i < 10 /* iterations */; ++i) {
update();
bar.barrier();
}
}
catch (InterruptedException ie) {}
// ...
}
}
class Problem { int size; }
class Driver {
// ...
int granularity = 1;
void compute(Problem problem) throws Exception {
int n = problem.size / granularity;
CyclicBarrier barrier = new CyclicBarrier(n);
Thread[] threads = new Thread[n];
// create
for (int i = 0; i < n; ++i)
threads[i] = new Thread(new Segment(barrier));
// trigger
for (int i = 0; i < n; ++i) threads[i].start();
// await termination
for (int i = 0; i < n; ++i) threads[i].join();
}
}
class JacobiSegment implements Runnable { // Incomplete
// These are same as in Leaf class version:
static final double EPSILON = 0.001;
double[][] A; double[][] B;
final int firstRow; final int lastRow;
final int firstCol; final int lastCol;
volatile double maxDiff;
int steps = 0;
void update() { /* Nearly same as Leaf.run */ }
final CyclicBarrier bar;
final JacobiSegment[] allSegments; // needed for convergence check
volatile boolean converged = false;
JacobiSegment(double[][] A, double[][] B,
int firstRow, int lastRow,
int firstCol, int lastCol,
CyclicBarrier b, JacobiSegment[] allSegments) {
this.A = A; this.B = B;
this.firstRow = firstRow; this.lastRow = lastRow;
this.firstCol = firstCol; this.lastCol = lastCol;
this.bar = b;
this.allSegments = allSegments;
}
public void run() {
try {
while (!converged) {
update();
int myIndex = bar.barrier(); // wait for all to update
if (myIndex == 0) convergenceCheck();
bar.barrier(); // wait for convergence check
}
}
catch(Exception ex) {
// clean up ...
}
}
void convergenceCheck() {
for (int i = 0; i < allSegments.length; ++i)
if (allSegments[i].maxDiff > EPSILON) return;
for (int i = 0; i < allSegments.length; ++i)
allSegments[i].converged = true;
}
}
class ActiveRunnableExecutor extends Thread {
Channel me = null; // ... // used for all incoming messages
public void run() {
try {
for (;;) {
((Runnable)(me.take())).run();
}
}
catch (InterruptedException ie) {} // die
}
}
//import jcsp.lang.*;
class Fork implements jcsp.lang.CSProcess {
private final jcsp.lang.AltingChannelInput[] fromPhil;
Fork(jcsp.lang.AltingChannelInput l, jcsp.lang.AltingChannelInput r) {
fromPhil = new jcsp.lang.AltingChannelInput[] { l, r };
}
public void run() {
jcsp.lang.Alternative alt = new jcsp.lang.Alternative(fromPhil);
for (;;) {
int i = alt.select(); // await message from either
fromPhil[i].read(); // pick up
fromPhil[i].read(); // put down
}
}
}
class Butler implements jcsp.lang.CSProcess {
private final jcsp.lang.AltingChannelInput[] enters;
private final jcsp.lang.AltingChannelInput[] exits;
Butler(jcsp.lang.AltingChannelInput[] e, jcsp.lang.AltingChannelInput[] x) {
enters = e;
exits = x;
}
public void run() {
int seats = enters.length;
int nseated = 0;
// set up arrays for select
jcsp.lang.AltingChannelInput[] chans = new jcsp.lang.AltingChannelInput[2*seats];
for (int i = 0; i < seats; ++i) {
chans[i] = exits[i];
chans[seats + i] = enters[i];
}
jcsp.lang.Alternative either = new jcsp.lang.Alternative(chans);
jcsp.lang.Alternative exit = new jcsp.lang.Alternative(exits);
for (;;) {
// if max number are seated, only allow exits
jcsp.lang.Alternative alt = (nseated < seats-1)? either : exit;
int i = alt.fairSelect();
chans[i].read();
// if i is in first half of array, it is an exit message
if (i < seats) --nseated; else ++nseated;
}
}
}
class Philosopher implements jcsp.lang.CSProcess {
private final jcsp.lang.ChannelOutput leftFork;
private final jcsp.lang.ChannelOutput rightFork;
private final jcsp.lang.ChannelOutput enter;
private final jcsp.lang.ChannelOutput exit;
Philosopher(jcsp.lang.ChannelOutput l, jcsp.lang.ChannelOutput r,
jcsp.lang.ChannelOutput e, jcsp.lang.ChannelOutput x) {
leftFork = l;
rightFork = r;
enter = e;
exit = x;
}
public void run() {
for (;;) {
think();
enter.write(null); // get seat
leftFork.write(null); // pick up left
rightFork.write(null); // pick up right
eat();
leftFork.write(null); // put down left
rightFork.write(null); // put down right
exit.write(null); // leave seat
}
}
private void eat() {}
private void think() {}
}
class College implements jcsp.lang.CSProcess {
final static int N = 5;
private final jcsp.lang.CSProcess action;
College() {
jcsp.lang.One2OneChannel[] lefts = jcsp.lang.One2OneChannel.create(N);
jcsp.lang.One2OneChannel[] rights = jcsp.lang.One2OneChannel.create(N);
jcsp.lang.One2OneChannel[] enters = jcsp.lang.One2OneChannel.create(N);
jcsp.lang.One2OneChannel[] exits = jcsp.lang.One2OneChannel.create(N);
Butler butler = new Butler(enters, exits);
Philosopher[] phils = new Philosopher[N];
for (int i = 0; i < N; ++i)
phils[i] = new Philosopher(lefts[i], rights[i],
enters[i], exits[i]);
Fork[] forks = new Fork[N];
for (int i = 0; i < N; ++i)
forks[i] = new Fork(rights[(i + 1) % N], lefts[i]);
action = new jcsp.lang.Parallel(
new jcsp.lang.CSProcess[] {
butler,
new jcsp.lang.Parallel(phils),
new jcsp.lang.Parallel(forks)
});
}
public void run() { action.run(); }
public static void main(String[] args) {
new College().run();
}
}
|
Ericliu001/BigBangJava
|
src/main/resources/DougLea.java
|
Java
|
mit
| 121,587 |
package armored.g12matrickapp.Activities;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import armored.g12matrickapp.Adapters.ChooserArrayAdapter;
import armored.g12matrickapp.Fragments.Choose_Subject_Fragment;
import armored.g12matrickapp.Fragments.Quizzi_Fragment;
import armored.g12matrickapp.R;
import armored.g12matrickapp.Utils.Functions;
import armored.g12matrickapp.Widgets.ExpandableGridView;
import static android.view.View.GONE;
public class Subject_Choose extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
/**
* The {@link ViewPager} that will host the section contents.
*/
private View navHeader;
private AppCompatImageView imgNavProfile , imgNavBackground;
private TextView txtName , txtWebsite;
private int navItemIndex = 0;
private NavigationView navigationView;
private Toolbar primaryToolbar;
private Toolbar secondaryToolbar;
private TextView detailsToolbarTextView;
private NestedScrollView container_one;
private NestedScrollView container_two;
private Handler mHandler;
private String[] activityTitles;
private static final String TAG_CHANGE_SUBJECT = "chsub";
private static final String TAG_QUIZZI = "quizzi";
private static final String TAG_MY_PROGRESS = "mprogress";
private static final String TAG_CHALLENGES = "challenge";
private static final String TAG_EUEE_RESULT = "eueer";
public static String CURRENT_TAG = TAG_CHANGE_SUBJECT;
ExpandableGridView catGrid;
View fragment;
void loadNavHeader(){
txtName.setText("Brook Mezgebu");
txtWebsite.setText("Bole Kale Hiwot School");
try{ Drawable drawable = ContextCompat.getDrawable(this , R.drawable.male);
Bitmap b = Functions.getHexagonShape(Functions.drawableToBitmap(drawable));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG , 100 , stream);
byte[] bitmapdata = stream.toByteArray();
Glide.with(this)
.load(bitmapdata)
.crossFade()
.override(150 , 150)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavProfile);
Glide.with(this)
.load(R.drawable.lib_background)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgNavBackground);
}
catch (Exception a){
a.printStackTrace();
}
}
private FragmentManager.OnBackStackChangedListener getListener(){
FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
FragmentManager manager = getSupportFragmentManager();
if(manager != null){
int backstackentrycount = manager.getBackStackEntryCount();
if(backstackentrycount == 0){
finish();
} else{
Fragment frag = manager.getFragments().get(backstackentrycount - 1);
frag.onResume();
}
}
}
};
return result;
}
public void hide_container_one(){
container_one.setVisibility(GONE);
container_two.setVisibility(View.VISIBLE);
}
public void hide_container_two(){
container_one.setVisibility(View.VISIBLE);
container_two.setVisibility(View.GONE);
}
public void hide_second_toolbar(){
secondaryToolbar.setVisibility(GONE);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)secondaryToolbar.getLayoutParams();
AppBarLayout.LayoutParams paramsp = (AppBarLayout.LayoutParams)primaryToolbar.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
paramsp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
primaryToolbar.setLayoutParams(paramsp);
secondaryToolbar.setLayoutParams(params);
}
public void show_second_toolbar(){
secondaryToolbar.setVisibility(View.VISIBLE);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)secondaryToolbar.getLayoutParams();
AppBarLayout.LayoutParams paramsp = (AppBarLayout.LayoutParams)primaryToolbar.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
paramsp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
primaryToolbar.setLayoutParams(paramsp);
secondaryToolbar.setLayoutParams(params);
}
int alsoGoTo = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_be_removed);
primaryToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(primaryToolbar);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
mHandler = new Handler();
getSupportFragmentManager().addOnBackStackChangedListener(getListener());
secondaryToolbar = (Toolbar) findViewById(R.id.secondaryTab);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, primaryToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
detailsToolbarTextView = (TextView) findViewById(R.id.detailToolbarTextView);
detailsToolbarTextView.setText("Subjects");
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.userName);
txtWebsite = (TextView) navHeader.findViewById(R.id.userSchool);
imgNavProfile = (AppCompatImageView) navHeader.findViewById(R.id.profilePic);
imgNavBackground = (AppCompatImageView) navHeader. findViewById(R.id.libBackgroundNav);
fragment = (View) findViewById(R.id.fragment);
loadNavHeader();
try {
alsoGoTo = getIntent().getExtras().getInt("alsoGoTo" , 0);
} catch (Exception e){
alsoGoTo = 0;
e.printStackTrace();
}
if(alsoGoTo == 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_CHANGE_SUBJECT;
navigationView.getMenu().getItem(0).setChecked(true);
loadChoosedFragment();
} else {
navItemIndex = alsoGoTo;
CURRENT_TAG = getTagFromIndex(alsoGoTo);
navigationView.getMenu().getItem(alsoGoTo).setChecked(true);
loadChoosedFragment();
}
container_one = (NestedScrollView) findViewById(R.id.container_one);
container_two = (NestedScrollView) findViewById(R.id.container_two);
}
DrawerLayout drawer;
public void SetTitleFromFragment(String title){
getSupportActionBar().setTitle(title);
}
private String getTagFromIndex(int index){
switch (index){
case 0:
return TAG_CHANGE_SUBJECT;
case 1:
return TAG_QUIZZI;
case 2:
return TAG_MY_PROGRESS;
case 3:
return TAG_CHALLENGES;
case 4:
return TAG_EUEE_RESULT;
default:
return TAG_CHANGE_SUBJECT;
}
}
public void SetSubTitleFromFragment(String title){
getSupportActionBar().setSubtitle(title);
}
public void SetTitleOfDetailFromFragment(String title){ detailsToolbarTextView.setText(title);}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_subject__choose, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadChoosedFragment(){
selectNavMenu();
setToolbarTitle();
if(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null){
drawer.closeDrawers();
return;
}
Runnable mPendingRunnable = new Runnable() {
@Override
public void run() {
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
try{
if(getSupportFragmentManager().findFragmentById(R.id.fragment) != null)
fragmentTransaction.remove(getSupportFragmentManager().findFragmentById(R.id.fragment));
if(getSupportFragmentManager().findFragmentById(R.id.fragment2) != null)
fragmentTransaction.remove(getSupportFragmentManager().findFragmentById(R.id.fragment2));
} catch (NullPointerException a){
a.printStackTrace();
}
fragmentTransaction.replace(R.id.fragment, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if(mPendingRunnable != null){
mHandler.postDelayed(mPendingRunnable , 250);
}
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment(){
switch (navItemIndex){
case 0:
show_second_toolbar();
return new Choose_Subject_Fragment();
case 1:
hide_second_toolbar();
return new Quizzi_Fragment();
/*
case 2:
return new GraphsFragment();
case 3:
return new WhatsHotFragment();*/
default:
return new Fragment();
}
}
//This will be used inside onbackpressed to go back from years to subjects on mainPage
boolean amOnYearsPart = false;
//This will be used inside onbackpressed to go back from chapters to subjects on quizzi
boolean amOnChaptersPart = false;
private void setToolbarTitle(){
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
public void setAmOnYearsPart(boolean b) { amOnYearsPart = b; }
public void setAmOnChaptersPart(boolean b) { amOnChaptersPart = b; }
private void selectNavMenu(){
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
boolean isDOubleTOuched = false;
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if(getSupportFragmentManager().findFragmentById(R.id.fragment) != null) {
if(getSupportFragmentManager().findFragmentById(R.id.fragment).getTag().equals(TAG_CHANGE_SUBJECT)){
if (!isDOubleTOuched) {
isDOubleTOuched = true;
Snackbar snackbar = Snackbar.make(secondaryToolbar, "Press Again To Exit", Snackbar.LENGTH_SHORT)
.setAction("EXIT NOW", new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
snackbar.getView().setBackgroundColor(ContextCompat.getColor(Subject_Choose.this, R.color.colorPrimary));
snackbar.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
isDOubleTOuched = false;
}
}, 1500);
snackbar.show();
} else {
finish();
}
} else if(getSupportFragmentManager().findFragmentById(R.id.fragment).getTag().equals(TAG_QUIZZI)) {
if(amOnChaptersPart){
Quizzi_Fragment tempFrag = (Quizzi_Fragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
tempFrag.performBackButtonClick();
} else {
navItemIndex = 0;
CURRENT_TAG = TAG_CHANGE_SUBJECT;
navigationView.getMenu().getItem(0).setChecked(true);
loadChoosedFragment();
}
}
else {
if(amOnYearsPart){
navItemIndex = 0;
CURRENT_TAG = TAG_CHANGE_SUBJECT;
navigationView.getMenu().getItem(0).setChecked(true);
loadChoosedFragment();
}else {
AlertDialog.Builder exitQ = new AlertDialog.Builder(this);
exitQ.setTitle("Are you sure?");
exitQ.setMessage("Are you sure you want to exit to the homepage? All your progress will be lost.");
exitQ.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
navItemIndex = 0;
CURRENT_TAG = TAG_CHANGE_SUBJECT;
navigationView.getMenu().getItem(0).setChecked(true);
loadChoosedFragment();
}
}).setNegativeButton("No", null);
exitQ.show();
}
}
}
}
}
public void deselectNavMenu(){
int i = navigationView.getMenu().size();
for(int x = 0; x < i; x++){
navigationView.getMenu().getItem(x).setChecked(false);
}
}
public void shareDialog() {
final List<String> packages = new ArrayList<String>();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
final List<ResolveInfo> resInfosNew = new ArrayList<ResolveInfo>();
final List<ResolveInfo> resInfos = getPackageManager().queryIntentActivities(shareIntent, 0);
resInfosNew.addAll(resInfos);
if (!resInfos.isEmpty()) {
System.out.println("Have package");
int count = 0;
for (ResolveInfo resInfo : resInfos) {
String packageName = resInfo.activityInfo.packageName;
if (packageName.contains("com.facebook.katana")) {
resInfosNew.remove(count);
} else
packages.add(packageName);
count++;
}
}
if (packages.size() > 1) {
ArrayAdapter<String> adapter = new ChooserArrayAdapter(this, android.R.layout.select_dialog_item, android.R.id.text1, packages);
String title = "<b>Share via...</b>";
new AlertDialog.Builder(this)
.setTitle(Html.fromHtml(title))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
invokeApplication(packages.get(item), resInfosNew.get(item));
}
})
.show();
} else if (packages.size() == 1) {
invokeApplication(packages.get(0), resInfos.get(0));
}
}
private void invokeApplication(String packageName, ResolveInfo resolveInfo) {
// if(packageName.contains("com.twitter.android") || packageName.contains("com.facebook.katana") || packageName.contains("com.kakao.story")) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
String sharetxt = "Practice makes perfect. Exercise previous grade 12 matrick questions to do your best.\n Download our app from [zufanapps.tk/g12matrick] and Thank you.";
intent.putExtra(Intent.EXTRA_TEXT, sharetxt);
intent.putExtra(Intent.EXTRA_SUBJECT, "Share G12");
intent.setPackage(packageName);
startActivity(intent);
// }
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_change_sub) {
navItemIndex = 0;
CURRENT_TAG = TAG_CHANGE_SUBJECT;
if(item.isChecked()){
item.setChecked(false);
} else{
item.setChecked(true);
}
item.setChecked(true);
loadChoosedFragment();
return true;
} else if (id == R.id.nav_quizzi) {
navItemIndex = 1;
CURRENT_TAG = TAG_QUIZZI;
if(item.isChecked()){
item.setChecked(false);
} else{
item.setChecked(true);
}
item.setChecked(true);
loadChoosedFragment();
return true;
} else if (id == R.id.nav_my_progress) {
} else if (id == R.id.nav_challenge) {
} else if (id == R.id.euee_result) {
} else if(id == R.id.settings) {
} else if (id == R.id.nav_share) {
shareDialog();
} else if (id == R.id.nav_send) {
} else if(id == R.id.rate_us){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
RhinoSoftware/G12Matric
|
app/src/main/java/armored/g12matrickapp/Activities/subject_Choose.java
|
Java
|
mit
| 21,736 |
package panels;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class EditPanel extends JPanel {
JTextArea srcEdit;
public EditPanel() {
srcEdit = new JTextArea(20, 30);
String src = ".data\n"
+ "a: .word 1, 2, 3\n";
srcEdit.setText(src);
add(srcEdit);
}
public JTextArea getSrcEdit() {
return srcEdit;
}
public void setSrcEdit(JTextArea srcEdit) {
this.srcEdit = srcEdit;
}
public String getText() {
return getSrcEdit().getText() ;
}
}
|
mulderp/plutoasm
|
src/panels/EditPanel.java
|
Java
|
mit
| 496 |
//
// CoronaApplication.java
// TemplateApp
//
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
package com.wonhada.EnterpriseExample;
/**
* Extends the Application class to receive Corona runtime events and to extend the Lua API.
* <p>
* Only one instance of this class will be created by the Android OS. It will be created before this application's
* activity is displayed and will persist after the activity is destroyed. The name of this class must be set in the
* AndroidManifest.xml file's "application" tag or else an instance of this class will not be created on startup.
*/
public class CoronaApplication extends android.app.Application {
/** Called when your application has started. */
@Override
public void onCreate() {
// Set up a Corona runtime listener used to add custom APIs to Lua.
com.ansca.corona.CoronaEnvironment.addRuntimeListener(new CoronaApplication.CoronaRuntimeEventHandler());
}
/** Receives and handles Corona runtime events. */
private class CoronaRuntimeEventHandler implements com.ansca.corona.CoronaRuntimeListener {
/**
* Called after the Corona runtime has been created and just before executing the "main.lua" file.
* This is the application's opportunity to register custom APIs into Lua.
* <p>
* Warning! This method is not called on the main thread.
* @param runtime Reference to the CoronaRuntime object that has just been loaded/initialized.
* Provides a LuaState object that allows the application to extend the Lua API.
*/
@Override
public void onLoaded(com.ansca.corona.CoronaRuntime runtime) {
com.naef.jnlua.NamedJavaFunction[] luaFunctions;
// Fetch the Lua state from the runtime.
com.naef.jnlua.LuaState luaState = runtime.getLuaState();
// Add a module named "myTests" to Lua having the following functions.
luaFunctions = new com.naef.jnlua.NamedJavaFunction[] {
new GetSDCardPathFunction()
};
luaState.register("nativeApp", luaFunctions);
luaState.pop(1);
}
/**
* Called just after the Corona runtime has executed the "main.lua" file.
* <p>
* Warning! This method is not called on the main thread.
* @param runtime Reference to the CoronaRuntime object that has just been started.
*/
@Override
public void onStarted(com.ansca.corona.CoronaRuntime runtime) {
}
/**
* Called just after the Corona runtime has been suspended which pauses all rendering, audio, timers,
* and other Corona related operations. This can happen when another Android activity (ie: window) has
* been displayed, when the screen has been powered off, or when the screen lock is shown.
* <p>
* Warning! This method is not called on the main thread.
* @param runtime Reference to the CoronaRuntime object that has just been suspended.
*/
@Override
public void onSuspended(com.ansca.corona.CoronaRuntime runtime) {
}
/**
* Called just after the Corona runtime has been resumed after a suspend.
* <p>
* Warning! This method is not called on the main thread.
* @param runtime Reference to the CoronaRuntime object that has just been resumed.
*/
@Override
public void onResumed(com.ansca.corona.CoronaRuntime runtime) {
}
/**
* Called just before the Corona runtime terminates.
* <p>
* This happens when the Corona activity is being destroyed which happens when the user presses the Back button
* on the activity, when the native.requestExit() method is called in Lua, or when the activity's finish()
* method is called. This does not mean that the application is exiting.
* <p>
* Warning! This method is not called on the main thread.
* @param runtime Reference to the CoronaRuntime object that is being terminated.
*/
@Override
public void onExiting(com.ansca.corona.CoronaRuntime runtime) {
}
}
}
|
englekk/CoronaEnterpriseTemplate
|
src/android/src/com/wonhada/EnterpriseExample/CoronaApplication.java
|
Java
|
mit
| 3,873 |
package hu.progtech.cd2t100.asm;
import java.lang.reflect.Type;
import com.google.gson.InstanceCreator;
class LocationInstanceCreator implements
InstanceCreator<Location> {
public Location createInstance(Type type) {
return new Location(0, 0);
}
}
|
battila7/cd2t-100
|
cd2t-100-core/src/test/java/hu/progtech/cd2t100/asm/LocationInstanceCreator.java
|
Java
|
mit
| 262 |
/*
* PhraseService.java
*
* Copyright (C) 2018 [ A Legge Up ]
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.aleggeup.confagrid.content;
import java.util.List;
import java.util.UUID;
import com.aleggeup.confagrid.model.Phrase;
public interface PhraseService {
List<Phrase> findAll();
void save(Phrase phrase);
Phrase phraseFromText(String text);
long count();
Phrase findOne(UUID id);
}
|
ALeggeUp/confagrid
|
application/confagrid-webapp/src/main/java/com/aleggeup/confagrid/content/PhraseService.java
|
Java
|
mit
| 514 |
package cs2020;
public interface IMazeSolverWithPower extends IMazeSolver {
/**
* Finds the shortest path from a given starting coordinate to an
* ending coordinate with a fixed number of Powers given
*
* @param startRow
* @param startCol
* @param endRow
* @param endCol
* @param superpowers
* @return minimum moves from start to end
* @return null if there is no path from start to end
* @throws Exception
*/
Integer pathSearch(int startRow, int startCol, int endRow, int endCol, int superpowers) throws Exception;
}
|
burnflare/cs2020
|
Ps7/src/cs2020/IMazeSolverWithPower.java
|
Java
|
mit
| 569 |
package com.lms.dao;
import java.util.List;
import com.lms.jpa.Person;
public interface DAOPerson {
public boolean personExist(long personId);
public void insertPerson(Person person);
public void updatePerson(Person person);
public void deletePerson(long personId);
public Person fetchPersonInfo(long personId);
public List<Person> fetchAllPerson();
}
|
deepshah22/spring-mvc
|
src/main/java/com/lms/dao/DAOPerson.java
|
Java
|
mit
| 410 |
package com.valarion.gameengine.events.menu.battlemenu;
public interface ToolTip {
public String getToolTip();
}
|
valarion/JAGE
|
JAGEgradle/JAGEmodules/src/main/java/com/valarion/gameengine/events/menu/battlemenu/ToolTip.java
|
Java
|
mit
| 120 |
/**
* @author fengchen, Dongyun Jin, Patrick Meredith, Michael Ilseman
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package llvmmop;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import com.runtimeverification.rvmonitor.java.rvj.Main;
import llvmmop.parser.ast.MOPSpecFile;
import llvmmop.util.Tool;
import llvmmop.util.AJFileCombiner;
class JavaFileFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
}
class MOPFileFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith(".mop");
}
}
public class LLVMMOPMain {
static File outputDir = null;
public static boolean debug = false;
public static boolean noopt1 = false;
public static boolean toJavaLib = false;
public static boolean statistics = false;
public static boolean statistics2 = false;
public static String aspectname = null;
public static boolean specifiedAJName = false;
public static boolean isJarFile = false;
public static String jarFilePath = null;
public static final int NONE = 0;
public static final int HANDLERS = 1;
public static final int EVENTS = 2;
public static int logLevel = NONE;
public static boolean dacapo = false;
public static boolean dacapo2 = false;
public static boolean silent = false;
public static boolean empty_advicebody = false;
public static boolean translate2RV = true;
public static boolean merge = false;
public static boolean inline = false;
public static boolean scalable = false;
public static boolean keepRVFiles = false;
public static List<String []> listFilePairs = new ArrayList<String []>();
public static List<String> listRVMFiles = new ArrayList<String>();
static private File getTargetDir(ArrayList<File> specFiles) throws MOPException{
if(LLVMMOPMain.outputDir != null){
return outputDir;
}
boolean sameDir = true;
File parentFile = null;
for(File file : specFiles){
if(parentFile == null){
parentFile = file.getAbsoluteFile().getParentFile();
} else {
if(file.getAbsoluteFile().getParentFile().equals(parentFile)){
continue;
} else {
sameDir = false;
break;
}
}
}
if(sameDir){
return parentFile;
} else {
return new File(".");
}
}
/**
* Process a java file including mop annotations to generate an aspect file. The path argument should be an existing java file name. The location
* argument should contain the original file name, But it may have a different directory.
*
* @param path
* an absolute path of a specification file
* @param location
* an absolute path for result file
*/
public static void processJavaFile(File file, String location) throws MOPException {
MOPNameSpace.init();
String specStr = SpecExtractor.process(file);
MOPSpecFile spec = SpecExtractor.parse(specStr);
if (LLVMMOPMain.aspectname == null) {
LLVMMOPMain.aspectname = Tool.getFileName(file.getAbsolutePath());
}
MOPProcessor processor = new MOPProcessor(LLVMMOPMain.aspectname);
String aspect = processor.process(spec);
writeFile(aspect, location, "MonitorAspect.aj");
}
/**
* Process a specification file to generate an aspect file. The path argument should be an existing specification file name. The location
* argument should contain the original file name, But it may have a different directory.
*
* @param path
* an absolute path of a specification file
* @param location
* an absolute path for result file
*/
public static void processSpecFile(File file, String location) throws MOPException {
MOPNameSpace.init();
String specStr = SpecExtractor.process(file);
MOPSpecFile spec = SpecExtractor.parse(specStr);
if (LLVMMOPMain.aspectname == null) {
LLVMMOPMain.aspectname = Tool.getFileName(file.getAbsolutePath());
}
MOPProcessor processor = new MOPProcessor(LLVMMOPMain.aspectname);
String output = processor.process(spec);
if (translate2RV) {
writeFile(processor.translate2RV(spec), file.getAbsolutePath(), ".rvm");
}
if (toJavaLib) {
writeFile(output, location, "JavaLibMonitor.java");
} else {
writeFile(output, location, "MonitorAspect.aj");
}
}
public static void processMultipleFiles(ArrayList<File> specFiles) throws MOPException {
String aspectName;
if(outputDir == null){
outputDir = getTargetDir(specFiles);
}
if(LLVMMOPMain.aspectname != null) {
aspectName = LLVMMOPMain.aspectname;
} else {
if(specFiles.size() == 1) {
aspectName = Tool.getFileName(specFiles.get(0).getAbsolutePath());
} else {
int suffixNumber = 0;
// generate auto name like 'MultiMonitorApsect.aj'
File aspectFile;
do{
suffixNumber++;
aspectFile = new File(outputDir.getAbsolutePath() + File.separator + "MultiSpec_" + suffixNumber + "MonitorAspect.aj");
} while(aspectFile.exists());
aspectName = "MultiSpec_" + suffixNumber;
}
LLVMMOPMain.aspectname = aspectName;
}
MOPProcessor processor = new MOPProcessor(aspectName);
MOPNameSpace.init();
ArrayList<MOPSpecFile> specs = new ArrayList<MOPSpecFile>();
for(File file : specFiles){
String specStr = SpecExtractor.process(file);
MOPSpecFile spec = SpecExtractor.parse(specStr);
if (translate2RV) {
writeFile(processor.translate2RV(spec), file.getAbsolutePath(), ".rvm");
}
specs.add(spec);
}
MOPSpecFile combinedSpec = SpecCombiner.process(specs);
String output = processor.process(combinedSpec);
writeCombinedAspectFile(output, aspectName);
}
protected static void writeJavaFile(String javaContent, String location) throws MOPException {
if ((javaContent == null) || (javaContent.length() == 0))
throw new MOPException("Nothing to write as a java file");
if (!Tool.isJavaFile(location))
throw new MOPException(location + "should be a Java file!");
try {
FileWriter f = new FileWriter(location);
f.write(javaContent);
f.close();
} catch (Exception e) {
throw new MOPException(e.getMessage());
}
}
protected static void writeCombinedAspectFile(String aspectContent, String aspectName) throws MOPException {
if (aspectContent == null || aspectContent.length() == 0)
return;
try {
FileWriter f = new FileWriter(outputDir.getAbsolutePath() + File.separator + aspectName + "MonitorAspect.aj");
f.write(aspectContent);
f.close();
} catch (Exception e) {
throw new MOPException(e.getMessage());
}
System.out.println(" " + aspectName + "MonitorAspect.aj is generated");
}
protected static void writeFile(String content, String location, String suffix) throws MOPException {
if (content == null || content.length() == 0)
return;
int i = location.lastIndexOf(File.separator);
String filePath = "";
try {
filePath = location.substring(0, i + 1) + Tool.getFileName(location) + suffix;
FileWriter f = new FileWriter(filePath);
f.write(content);
f.close();
} catch (Exception e) {
throw new MOPException(e.getMessage());
}
if (suffix.equals(".rvm")) {
listRVMFiles.add(filePath);
}
System.out.println(" " + Tool.getFileName(location) + suffix + " is generated");
}
// PM
protected static void writePluginOutputFile(String pluginOutput, String location) throws MOPException {
int i = location.lastIndexOf(File.separator);
try {
FileWriter f = new FileWriter(location.substring(0, i + 1) + Tool.getFileName(location) + "PluginOutput.txt");
f.write(pluginOutput);
f.close();
} catch (Exception e) {
throw new MOPException(e.getMessage());
}
System.out.println(" " + Tool.getFileName(location) + "PluginOutput.txt is generated");
}
public static String polishPath(String path) {
if (path.indexOf("%20") > 0)
path = path.replaceAll("%20", " ");
return path;
}
public static ArrayList<File> collectFiles(String[] files, String path) throws MOPException {
ArrayList<File> ret = new ArrayList<File>();
for (String file : files) {
String fPath = path.length() == 0 ? file : path + File.separator + file;
File f = new File(fPath);
if (!f.exists()) {
throw new MOPException("[Error] Target file, " + file + ", doesn't exsit!");
} else if (f.isDirectory()) {
ret.addAll(collectFiles(f.list(new JavaFileFilter()), f.getAbsolutePath()));
ret.addAll(collectFiles(f.list(new MOPFileFilter()), f.getAbsolutePath()));
} else {
if (Tool.isSpecFile(file)) {
ret.add(f);
} else if (Tool.isJavaFile(file)) {
ret.add(f);
} else
throw new MOPException("Unrecognized file type! The JavaMOP specification file should have .mop as the extension.");
}
}
return ret;
}
public static void process(String[] files, String path) throws MOPException {
ArrayList<File> specFiles = collectFiles(files, path);
if(LLVMMOPMain.aspectname != null && files.length > 1){
LLVMMOPMain.merge = true;
}
if (LLVMMOPMain.merge) {
System.out.println("-Processing " + specFiles.size()
+ " specification(s)");
processMultipleFiles(specFiles);
String javaFile = outputDir.getAbsolutePath() + File.separator
+ LLVMMOPMain.aspectname + "RuntimeMonitor.java";
String ajFile = outputDir.getAbsolutePath() + File.separator
+ LLVMMOPMain.aspectname + "MonitorAspect.aj";
String combinerArgs[] = new String[2];
combinerArgs[0] = javaFile;
combinerArgs[1] = ajFile;
listFilePairs.add(combinerArgs);
} else {
for (File file : specFiles) {
boolean needResetAspectName = LLVMMOPMain.aspectname == null;
String location = outputDir == null ? file.getAbsolutePath() : outputDir.getAbsolutePath() + File.separator + file.getName();
System.out.println("-Processing " + file.getPath());
if (Tool.isSpecFile(file.getName())) {
processSpecFile(file, location);
} else if (Tool.isJavaFile(file.getName())) {
processJavaFile(file, location);
}
File combineDir = outputDir == null ? file.getAbsoluteFile()
.getParentFile() : outputDir;
String javaFile = combineDir.getAbsolutePath() + File.separator
+ LLVMMOPMain.aspectname + "RuntimeMonitor.java";
String ajFile = combineDir.getAbsolutePath() + File.separator
+ LLVMMOPMain.aspectname + "MonitorAspect.aj";
String combinerArgs[] = new String[2];
combinerArgs[0] = javaFile;
combinerArgs[1] = ajFile;
listFilePairs.add(combinerArgs);
if (needResetAspectName) {
LLVMMOPMain.aspectname = null;
}
}
}
}
public static void process(String arg) throws MOPException {
if(outputDir != null && !outputDir.exists())
throw new MOPException("The output directory, " + outputDir.getPath() + " does not exist.");
process(arg.split(";"), "");
}
// PM
public static void print_help() {
System.out.println("Usage: java [-cp javmaop_classpath] llvmmop.LLVMMOPMain [-options] files");
System.out.println("");
System.out.println("where options include:");
System.out.println(" Options enabled by default are prefixed with \'+\'");
System.out.println(" -h -help\t\t\t print this help message");
System.out.println(" -v | -verbose\t\t enable verbose output");
System.out.println(" -debug\t\t\t enable verbose error message");
System.out.println();
System.out.println(" -local\t\t\t+ use local logic engine");
System.out.println(" -remote\t\t\t use default remote logic engine");
System.out.println("\t\t\t\t " + Configuration.getServerAddr());
System.out.println("\t\t\t\t (You can change the default address");
System.out.println("\t\t\t\t in llvmmop/config/remote_server_addr.properties)");
System.out.println(" -remote:<server address>\t use remote logic engine");
System.out.println();
System.out.println(" -d <output path>\t\t select directory to store output files");
System.out.println(" -n | -aspectname <aspect name>\t use the given aspect name instead of source code name");
System.out.println();
System.out.println(" -showevents\t\t\t show every event/handler occurrence");
System.out.println(" -showhandlers\t\t\t show every handler occurrence");
System.out.println();
System.out.println(" -s | -statistics\t\t generate monitor with statistics");
System.out.println(" -noopt1\t\t\t don't use the enable set optimization");
System.out.println(" -javalib\t\t\t generate a java library rather than an AspectJ file");
System.out.println();
System.out.println(" -aspect:\"<command line>\"\t compile the result right after it is generated");
System.out.println();
}
public static void main(String[] args) {
ClassLoader loader = LLVMMOPMain.class.getClassLoader();
String mainClassPath = loader.getResource("llvmmop/LLVMMOPMain.class").toString();
if (mainClassPath.endsWith(".jar!/llvmmop/LLVMMOPMain.class") && mainClassPath.startsWith("jar:")) {
isJarFile = true;
jarFilePath = mainClassPath.substring("jar:file:".length(), mainClassPath.length() - "!/llvmmop/LLVMMOPMain.class".length());
jarFilePath = polishPath(jarFilePath);
}
int i = 0;
String files = "";
while (i < args.length) {
if (args[i].compareTo("-h") == 0 || args[i].compareTo("-help") == 0) {
print_help();
return;
}
if (args[i].compareTo("-d") == 0) {
i++;
outputDir = new File(args[i]);
} else if (args[i].compareTo("-local") == 0) {
} else if (args[i].compareTo("-remote") == 0) {
} else if (args[i].startsWith("-remote:")) {
} else if (args[i].compareTo("-v") == 0 || args[i].compareTo("-verbose") == 0) {
MOPProcessor.verbose = true;
} else if (args[i].compareTo("-javalib") == 0) {
toJavaLib = true;
} else if (args[i].compareTo("-debug") == 0) {
LLVMMOPMain.debug = true;
} else if (args[i].compareTo("-noopt1") == 0) {
LLVMMOPMain.noopt1 = true;
} else if (args[i].compareTo("-s") == 0 || args[i].compareTo("-statistics") == 0) {
LLVMMOPMain.statistics = true;
} else if (args[i].compareTo("-s2") == 0 || args[i].compareTo("-statistics2") == 0) {
LLVMMOPMain.statistics2 = true;
} else if (args[i].compareTo("-n") == 0 || args[i].compareTo("-aspectname") == 0) {
i++;
LLVMMOPMain.aspectname = args[i];
LLVMMOPMain.specifiedAJName = true;
} else if (args[i].compareTo("-showhandlers") == 0) {
if (LLVMMOPMain.logLevel < LLVMMOPMain.HANDLERS)
LLVMMOPMain.logLevel = LLVMMOPMain.HANDLERS;
} else if (args[i].compareTo("-showevents") == 0) {
if (LLVMMOPMain.logLevel < LLVMMOPMain.EVENTS)
LLVMMOPMain.logLevel = LLVMMOPMain.EVENTS;
} else if (args[i].compareTo("-dacapo") == 0) {
LLVMMOPMain.dacapo = true;
} else if (args[i].compareTo("-dacapo2") == 0) {
LLVMMOPMain.dacapo2 = true;
} else if (args[i].compareTo("-silent") == 0) {
LLVMMOPMain.silent = true;
} else if (args[i].compareTo("-merge") == 0) {
LLVMMOPMain.merge = true;
} else if (args[i].compareTo("-inline") == 0) {
LLVMMOPMain.inline = true;
} else if (args[i].compareTo("-noadvicebody") == 0) {
LLVMMOPMain.empty_advicebody = true;
} else if (args[i].compareTo("-scalable") == 0) {
LLVMMOPMain.scalable = true;
} else if (args[i].compareTo("-translate2RV") == 0) {
LLVMMOPMain.translate2RV = true;
} else if (args[i].compareTo("-keepRVFiles") == 0) {
LLVMMOPMain.keepRVFiles = true;
} else {
if (files.length() != 0)
files += ";";
files += args[i];
}
++i;
}
if (files.length() == 0) {
print_help();
return;
}
// Generate .rvm files and .aj files
try {
process(files);
} catch (Exception e) {
System.err.println(e.getMessage());
if (LLVMMOPMain.debug)
e.printStackTrace();
}
// replace mop with rvm and call rv-monitor
int length = args.length;
if (LLVMMOPMain.keepRVFiles) {
length--;
}
String rvArgs[] = new String [length];
int p = 0;
for (int j = 0; j < args.length; j++) {
if (args[j].compareTo("-keepRVFiles") == 0) {
// Don't pass keepRVFiles to rvmonitor
continue;
}
rvArgs[p] = args[j].replaceAll("\\.mop", "\\.rvm");
p++;
}
Main.main(rvArgs);
// Call AJFileCombiner here to combine these two
// TODO
for (String[] filePair : listFilePairs) {
AJFileCombiner.main(filePair);
File javaFile = new File(filePair[0]);
try {
if (!LLVMMOPMain.keepRVFiles) {
boolean deleted = javaFile.delete();
if (!deleted) {
System.err.println("Failed to delete java file: "
+ filePair[0]);
}
}
} catch (Exception e) {
}
}
for (String rvmFilePath : listRVMFiles) {
File rvmFile = new File(rvmFilePath);
try {
if (!LLVMMOPMain.keepRVFiles) {
boolean deleted = rvmFile.delete();
if (!deleted) {
System.err.println("Failed to delete java file: "
+ rvmFilePath);
}
}
} catch (Exception e) {
}
}
}
}
|
runtimeverification/llvmmop
|
src/llvmmop/LLVMMOPMain.java
|
Java
|
mit
| 17,124 |
package com.sdl.selenium.extjs6.form;
import com.sdl.selenium.InputData;
import com.sdl.selenium.TestBase;
import com.sdl.selenium.extjs6.panel.Panel;
import com.sdl.selenium.web.SearchType;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.time.Duration;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class RadioGroupIntegrationTest extends TestBase {
private Panel radioGroupPanel = new Panel(null, "Radio Group Example").setClasses("x-panel-default-framed");
private RadioGroup radioGroup = new RadioGroup(radioGroupPanel, "Auto Layout:", SearchType.DEEP_CHILD_NODE_OR_SELF);
@BeforeClass
public void startTests() {
driver.get(InputData.EXTJS_EXAMPLE_URL + "#form-radiogroup");
driver.switchTo().frame("examples-iframe");
radioGroup.setVersion(version);
radioGroup.ready(Duration.ofSeconds(20));
}
@Test
public void selectRadioGroup() {
assertThat(radioGroup.selectByLabel("Item 2"), is(true));
assertThat(radioGroup.isSelectedByLabel("Item 2"), is(true));
assertThat(radioGroup.selectByLabel("5", SearchType.CONTAINS), is(true));
assertThat(radioGroup.isSelectedByLabel("Item 5"), is(true));
assertThat(radioGroup.selectByLabel("Item 4"), is(true));
assertThat(radioGroup.isSelectedByLabel("Item 4"), is(true));
assertThat(radioGroup.selectByLabel("Item 1"), is(true));
assertThat(radioGroup.isSelectedByLabel("Item 1"), is(true));
}
@Test
public void getLabelNameRadioGroup() {
assertThat(radioGroup.getLabelName("1"), equalTo("Item 1"));
assertThat(radioGroup.getLabelName("1"), equalTo("Item 1"));
}
}
|
sdl/Testy
|
src/test/functional/java/com/sdl/selenium/extjs6/form/RadioGroupIntegrationTest.java
|
Java
|
mit
| 1,813 |
package com.kensenter.p2poolwidget;
import android.content.Context;
import android.content.SharedPreferences;
public class GetPrefs {
public static final String PREFS_NAME = "p2poolwidgetprefs";
public String GetWidget(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("servername", null);
}
public String GetServer(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("servername", "");
}
public String getPayKey(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("paykey", "");
}
public Integer getPort(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getInt("portnum", 3332);
}
public Integer getHashLevel(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getInt("hashlevel", 2);
}
public Integer getAlertRate(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getInt("alertnum", 0);
}
public Integer getDOARate(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getInt("doanum", 50);
}
public String getEfficiency(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("efficiency", "");
}
public String getUptime(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("uptime", "");
}
public String getShares(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("shares", "");
}
public String getTimeToShare(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("toshare", "");
}
public String getRoundTime(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("roundtime", "");
}
public String getTimeToBlock(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("toblock", "");
}
public String getBlockValue(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("blockvalue", "");
}
public String getPoolRate(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getString("pool_rate", "");
}
public boolean getRemoveLine(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getBoolean("removeline", false);
}
public boolean getAlertOn(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getBoolean("alerton", true);
}
public boolean getDOAOn(Context ctxt, int WidgetId){
SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0);
return settings.getBoolean("doaon", true);
}
}
|
ksenter/P2PoolWidget
|
src/com/kensenter/p2poolwidget/GetPrefs.java
|
Java
|
mit
| 3,843 |
package com.gulj.common.util;
import java.io.UnsupportedEncodingException;
public enum FeijianCode {
SAVE_SUCCESS("0001","保存成功"),
SAVE_ERROR("0002","保存失败"),
UPDATE_SUCCESS("0003","修改成功"),
UPDATE_ERROR("0004","修改失败"),
DELETE_SUCCESS("0005","删除成功"),
DELETE_ERROR("0006","删除失败"),
USERORPWD_ERROR("0007","用户名或者密码不正确"),
USEROR_ERROR("0008","账号不存在"),
USER_FIBINDDEN_ERROR("0009","账号被禁止"),
CODE_ERROR("0010","验证码不正确"),
USER_EXIST_ERROR("0011","帐号已存在"),
USEROR_LOGIN_SUCCESS("0012","登录成功"),
USEROR_NONE_TOP_MENU("0013","无顶级菜单,请联系系统管理员进行权限分配"),
USEROR_NONE_CHILD_MENU("0014","无子级菜单,请联系系统管理员进行权限分配"),
SYS_EXCEPTION("1100","系统异常"),;
/** 错误码 */
private final String code;
/** 错误吗对应描述信息 */
private final String info;
FeijianCode(String code, String info) {
this.code = code;
this.info = info;
}
public String getCode() {
return code;
}
public String getInfo() {
return info;
}
@SuppressWarnings("finally")
@Override
public String toString() {
String result = "{\"code\":"+"\""+this.code+"\""+",\"message\":"+"\""+this.info+"\""+"}";
try {
result = new String(result.getBytes("utf-8"), "utf-8");
} catch (UnsupportedEncodingException e) {
result = e.getMessage();
e.printStackTrace();
}
finally{
return result;
}
}
}
|
gulijian/joingu
|
gulj-common-util/src/main/java/com/gulj/common/util/FeijianCode.java
|
Java
|
mit
| 1,732 |
package com.creationgroundmedia.twitternator.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import com.codepath.oauth.OAuthLoginActionBarActivity;
import com.creationgroundmedia.twitternator.R;
import com.creationgroundmedia.twitternator.TwitterClient;
public class LoginActivity extends OAuthLoginActionBarActivity<TwitterClient> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
// Inflate the menu; this adds items to the action bar if it is present.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
// OAuth authenticated successfully, launch primary authenticated activity
// i.e Display application "homepage"
@Override
public void onLoginSuccess() {
Intent i = new Intent(this, TimelineActivity.class);
startActivity(i);
finish();
}
// OAuth authentication flow failed, handle the error
// i.e Display an error dialog or toast
@Override
public void onLoginFailure(Exception e) {
e.printStackTrace();
}
// Click handler method for the button used to start OAuth flow
// Uses the client to initiate OAuth authorization
// This should be tied to a button used to login
public void loginToRest(View view) {
getClient().connect();
}
}
|
geocohn/Twitternator
|
app/src/main/java/com/creationgroundmedia/twitternator/activities/LoginActivity.java
|
Java
|
mit
| 1,426 |
package uk.co.automatictester.concurrency.classes.atomic;
import org.testng.annotations.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class AtomicFieldUpdaterClass {
public volatile int v;
public volatile int b;
// all updates to volatile field through the same updater are guaranteed to be atomic
private static final AtomicIntegerFieldUpdater<AtomicFieldUpdaterClass> updater =
AtomicIntegerFieldUpdater.newUpdater(AtomicFieldUpdaterClass.class, "v");
@Test
public void test() throws InterruptedException {
int loopCount = 10_000;
int threads = 16;
CountDownLatch latch = new CountDownLatch(threads);
Runnable r = () -> {
try {
latch.countDown();
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < loopCount; i++) {
updater.incrementAndGet(this);
b++;
}
};
ExecutorService service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
service.submit(r);
}
service.shutdown();
service.awaitTermination(10, TimeUnit.SECONDS);
assertThat(v, equalTo(threads * loopCount));
assertThat(b, not(equalTo(threads * loopCount)));
}
}
|
deliverymind/useful-stuff
|
java/concurrency/src/test/java/uk/co/automatictester/concurrency/classes/atomic/AtomicFieldUpdaterClass.java
|
Java
|
mit
| 1,736 |
package com.bgstation0.android.sample.fragment_;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
//tOg1
public class Fragment1 extends Fragment implements OnClickListener{
// otB[h
static final String TAG = "Fragment1"; // TAGð"Fragment1"Åú».
public int mNumber = 0; // mNumberð0Åú».
public MainActivity mContext = null; // mContextðnullÅú».
// RXgN^
public Fragment1(){
}
// A^b`
@Override
public void onAttach(Activity activity){
// ùèÌ.
super.onAttach(activity);
Log.d(TAG, "Fragment1.onAttach"); // "Fragment1.onAttach"ÆOÉc·.
mContext = (MainActivity)activity; // activityðmContextÉn·.
mContext.func(); // funcðÄÔ.
}
// tOg¶¬
@Override
public void onCreate(Bundle savedInstanceState){
// ùèÌ.
super.onCreate(savedInstanceState); // eNXÌonCreateðÄÔ.
// FragmentÌͬð}~.
setRetainInstance(true); // setRetainInstanceðtrueÉ.
// Oðc·.
Log.d(TAG, "Fragment1.onCreate"); // "Fragment1.onCreate"ÆOÉc·.
}
// tOgjü
@Override
public void onDestroy(){
// Oðc·.
Log.d(TAG, "Fragment1.onDestroy"); // "Fragment1.onDestroy"ÆOÉc·.
// ùèÌ.
super.onDestroy(); // eNXÌonDestroyðÄÔ.
}
// r
[¶¬
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Oðc·.
Log.d(TAG, "Fragment1.onCreateView"); // "Fragment1.onCreateView"ÆOÉc·.
// ùèÌ.
View view = inflater.inflate(R.layout.fragment1_main, null); // inflater.inflateÅR.layout.fragment1_main©çr
[ðì¬.
Button button1 = (Button)view.findViewById(R.id.fragment1_button1); // Fragment1Ìbutton1ðæ¾.
button1.setOnClickListener(this); // Xi[ƵÄthisðZbg.
TextView tv = (TextView)view.findViewById(R.id.fragment1_textview);
tv.setText(Integer.toString(mNumber));
return view;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNumber++; // mNumberðâ·.
View view = getView();
TextView tv = (TextView)view.findViewById(R.id.fragment1_textview);
tv.setText(Integer.toString(mNumber));
}
// f^b`
@Override
public void onDetach(){
// Oðc·.
Log.d(TAG, "Fragment1.onDetach"); // "Fragment1.onDetach"ÆOÉc·.
// mContextðnull.
mContext = null;
// ùèÌ.
super.onDetach(); // eNXÌonDetachðÄÔ.
}
}
|
bg1bgst333/Sample
|
android/Fragment/setRetainInstance/src/Fragment/Fragment_/src/com/bgstation0/android/sample/fragment_/Fragment1.java
|
Java
|
mit
| 2,852 |
package ar.wildstyle;
import java.lang.reflect.Field;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ar.wildstyle.test.BaseTest;
import ar.wildstyle.test.ExamplePojo;
import ar.wildstyle.valuegenerator.IntegerValueGenerator;
import ar.wildstyle.valuegenerator.StringValueGenerator;
import ar.wildstyle.valuegenerator.ValueGenerator;
/**
* {@code FieldMappingEntryTests} contains tests for the {@link FieldMappingEntry} class.
*
* @author Adam Rosini
*/
public class FieldMappingEntryTests extends BaseTest {
/**
* Initializes shared test objects.
*/
@Before
public void initialize() throws Exception {
this.field = ExamplePojo.class.getDeclaredField(ExamplePojo.EXAMPLE_PRIVATE_STRING_FIELD_NAME);
this.valueGenerator = new StringValueGenerator();
this.value = "stringValue";
}
/**
* Test for creating a valid {@link FieldMappingEntry} using a {@link ValueGenerator}.
*/
@Test
public void fieldMappingEntryValueGenerator() {
final FieldMappingEntry<String> fieldMappingEntry = new FieldMappingEntry<String>(this.field, this.valueGenerator);
Assert.assertEquals(this.field, fieldMappingEntry.getField());
Assert.assertNotNull(fieldMappingEntry.getOrGenerateValue());
}
/**
* Test for creating a valid {@link FieldMappingEntry} using a value.
*/
@Test
public void fieldMappingEntryValue() {
final FieldMappingEntry<String> fieldMappingEntry = new FieldMappingEntry<String>(this.field, this.value);
Assert.assertEquals(this.field, fieldMappingEntry.getField());
Assert.assertEquals(fieldMappingEntry.getOrGenerateValue(), this.value);
}
/**
* Test for creating a valid {@link FieldMappingEntry} using a {@code null} value.
*/
@Test
public void fieldMappingEntryNullValue() {
this.value = null;
final FieldMappingEntry<String> fieldMappingEntry = new FieldMappingEntry<String>(this.field, this.value);
Assert.assertEquals(this.field, fieldMappingEntry.getField());
Assert.assertNull(fieldMappingEntry.getOrGenerateValue());
}
/**
* Test for attempting to create a {@link FieldMappingEntry} (with a value generator) using a null field parameter.
*/
@Test
public void fieldMappingEntryValueGeneratorNullField() {
this.expectedException.expect(AssertionError.class);
this.field = null;
new FieldMappingEntry<String>(this.field, this.valueGenerator);
}
/**
* Test for attempting to create a {@link FieldMappingEntry} (with a value) using a null field parameter.
*/
@Test
public void fieldMappingEntryValueNullField() {
this.expectedException.expect(AssertionError.class);
this.field = null;
new FieldMappingEntry<String>(this.field, this.value);
}
/**
* Test for attempting to create a {@link FieldMappingEntry} using a null value generator parameter.
*/
@Test
public void fieldMappingEntryNullValueGenerator() {
this.expectedException.expect(AssertionError.class);
this.valueGenerator = null;
new FieldMappingEntry<String>(this.field, this.valueGenerator);
}
/**
* Test for attempting to create a {@link FieldMappingEntry} where the value generator parameter is not compatible with the field
* parameter.
*/
@Test
public void fieldMappingEntryIncompatibleFieldAndValueGenerator() {
this.expectedException.expect(AssertionError.class);
new FieldMappingEntry<Integer>(this.field, new IntegerValueGenerator());
}
/**
* Test for attempting to create a {@link FieldMappingEntry} where the value parameter is not compatible with the field parameter.
*/
@Test
public void fieldMappingEntryIncompatibleFieldAndValue() {
this.expectedException.expect(AssertionError.class);
new FieldMappingEntry<Integer>(this.field, 1);
}
/**
* An example field to use when creating a {@link FieldMappingEntry}.
*/
private Field field;
/**
* An example value generator to use when creating a {@link FieldMappingEntry}.
*/
private ValueGenerator<String> valueGenerator;
/**
* An example value to use when creating a {@link FieldMappingEntry}.
*/
private String value;
}
|
arosini/wildstyle-generator
|
src/test/java/ar/wildstyle/FieldMappingEntryTests.java
|
Java
|
mit
| 4,283 |
package shop.main.controller.admin;
import static shop.main.controller.admin.AdminController.ADMIN_PREFIX;
import static shop.main.controller.admin.AdminController.MANAGER_PREFIX;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shop.main.data.entity.Discount;
import shop.main.data.service.DiscountService;
@Controller
@RequestMapping(value = { ADMIN_PREFIX, MANAGER_PREFIX })
public class AdminDiscountController extends AdminController {
@Autowired
DiscountService discountService;
@RequestMapping(value = "/discounts")
public String discountsList(Model model) {
loadTableData("", null, 1, PAGE_SIZE, model);
return "../admin/discounts/discounts";
}
@RequestMapping(value = "/findDiscounts", method = RequestMethod.POST)
public String findDiscounts(@RequestParam String name, @RequestParam String status,
@RequestParam(value = "current", required = false) Integer current,
@RequestParam(value = "pageSize", required = false) Integer pageSize, Model model) {
loadTableData(name, status, current, pageSize, model);
return "../admin/discounts/_table";
}
private void loadTableData(String name, String status, Integer current, Integer pageSize, Model model) {
Pageable pageable = new PageRequest(current - 1, pageSize);
model.addAttribute("discountList", discountService.findByNameAndStatus(name, status, pageable));
model.addAttribute("current", current);
model.addAttribute("pageSize", pageSize);
addPaginator(model, current, pageSize, discountService.countByNameAndStatus(name, status));
}
@RequestMapping(value = "/discount", method = RequestMethod.POST)
public String saveDiscount(@ModelAttribute("discount") @Valid Discount discount, BindingResult result, Model model,
final RedirectAttributes redirectAttributes, HttpServletRequest request) {
if (result.hasErrors()) {
model.addAttribute("errorSummary", result.getFieldErrors().stream()
.map(e -> e.getField() + " error - " + e.getDefaultMessage() + " ").collect(Collectors.toList()));
return "../admin/discounts/edit_discount";
} else {
if (discount.isNew()) {
redirectAttributes.addFlashAttribute("flashMessage", "Discount added successfully!");
if (discountService.notUniqueCoupon(discount.getCoupon())) {
model.addAttribute("errorSummary",
(new ArrayList<String>(Arrays.asList("Coupon code must be unique!"))));
return "../admin/discounts/edit_discount";
}
} else {
redirectAttributes.addFlashAttribute("flashMessage", "Discount updated successfully!");
}
discountService.save(discount);
return "redirect:" + getUrlPrefix(request) + "discounts";
}
}
@RequestMapping(value = "/discount/add", method = RequestMethod.GET)
public String addDiscount(Model model) {
model.addAttribute("discount", new Discount());
return "../admin/discounts/edit_discount";
}
@RequestMapping(value = "/discount/{id}/update", method = RequestMethod.GET)
public String editDiscount(@PathVariable("id") long id, Model model) {
model.addAttribute("discount", discountService.findById(id));
return "../admin/discounts/edit_discount";
}
@RequestMapping(value = "/discount/{id}/delete", method = RequestMethod.GET)
public String deleteDiscount(@PathVariable("id") long id, Model model, final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
discountService.deleteById(id);
redirectAttributes.addFlashAttribute("flashMessage", "Discount deleted successfully!");
return "redirect:" + getUrlPrefix(request) + "discounts";
}
}
|
spacerovka/jShop
|
src/main/java/shop/main/controller/admin/AdminDiscountController.java
|
Java
|
mit
| 4,334 |
package jkanvas.table;
import java.util.Objects;
import jkanvas.animation.GenericPaintList;
/**
* Maps rows of tables to shapes.
*
* @author Joschi <josua.krause@gmail.com>
* @param <T> The list of shapes.
*/
public abstract class ListMapper<T extends GenericPaintList<?>> {
/** The table. */
private final DataTable table;
/**
* Creates a map for the table.
*
* @param table The table.
*/
public ListMapper(final DataTable table) {
this.table = Objects.requireNonNull(table);
}
/**
* Getter.
*
* @return Creates a new list.
*/
protected abstract T createList();
/**
* Creates a shape for the given row.
*
* @param list The shape list.
* @param row The row.
* @return The index of the new shape.
*/
protected abstract int createForRow(T list, int row);
/**
* Fills the list.
*
* @return The list.
*/
private T fillList() {
final T res = createList();
final int rows = table.rows();
for(int el = 0; el < rows; ++el) {
final int i = createForRow(res, el);
// TODO allow arbitrary mappings
if(i != el) throw new IllegalStateException(
"unpredicted index: " + i + " != " + el);
}
return res;
}
/** The list. */
private T list;
/**
* Getter.
*
* @return The list.
*/
public T getList() {
if(list == null) {
list = fillList();
}
return list;
}
/**
* Getter.
*
* @return The table.
*/
public DataTable getTable() {
return table;
}
/**
* Getter.
*
* @param row The row.
* @return The index of the shape in the list.
*/
public int getIndexForRow(final int row) {
return row;
}
/**
* Getter.
*
* @param index The index of the shape.
* @return The row in the table.
*/
public int getRowForIndex(final int index) {
return index;
}
}
|
JosuaKrause/JKanvas
|
src/main/java/jkanvas/table/ListMapper.java
|
Java
|
mit
| 1,891 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.compute;
import com.azure.core.http.HttpPipeline;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineScaleSetInner;
import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage;
import com.azure.resourcemanager.compute.models.VirtualMachineScaleSet;
import com.azure.resourcemanager.compute.models.VirtualMachineScaleSetSkuTypes;
import com.azure.resourcemanager.network.models.LoadBalancer;
import com.azure.resourcemanager.network.models.LoadBalancerSkuType;
import com.azure.resourcemanager.network.models.Network;
import com.azure.resourcemanager.resources.models.ResourceGroup;
import com.azure.core.management.Region;
import com.azure.resourcemanager.resources.fluentcore.model.Creatable;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.storage.models.StorageAccount;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class VirtualMachineScaleSetBootDiagnosticsTests extends ComputeManagementTest {
private String rgName = "";
private final Region region = locationOrDefault(Region.US_SOUTH_CENTRAL);
private final String vmName = "javavm";
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
rgName = generateRandomResourceName("javacsmrg", 15);
super.initializeClients(httpPipeline, profile);
}
@Override
protected void cleanUpResources() {
resourceManager.resourceGroups().beginDeleteByName(rgName);
}
@Test
public void canEnableBootDiagnosticsWithImplicitStorageOnManagedVMSSCreation() throws Exception {
final String vmssName = generateRandomResourceName("vmss", 10);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withBootDiagnostics()
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
}
@Test
public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMSSCreation() throws Exception {
final String vmssName = generateRandomResourceName("vmss", 10);
final String storageName = generateRandomResourceName("st", 14);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
Creatable<StorageAccount> creatableStorageAccount =
storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName);
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withBootDiagnostics(creatableStorageAccount)
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
Assertions.assertTrue(virtualMachineScaleSet.bootDiagnosticsStorageUri().contains(storageName));
}
@Test
public void canEnableBootDiagnosticsWithExplicitStorageOnManagedVMSSCreation() throws Exception {
final String vmssName = generateRandomResourceName("vmss", 10);
final String storageName = generateRandomResourceName("st", 14);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withBootDiagnostics(storageAccount)
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
Assertions.assertTrue(virtualMachineScaleSet.bootDiagnosticsStorageUri().contains(storageName));
}
@Test
public void canDisableVMSSBootDiagnostics() throws Exception {
final String vmssName = generateRandomResourceName("vmss", 10);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withBootDiagnostics()
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
virtualMachineScaleSet.update().withoutBootDiagnostics().apply();
Assertions.assertFalse(virtualMachineScaleSet.isBootDiagnosticsEnabled());
// Disabling boot diagnostics will not remove the storage uri from the vm payload.
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
}
@Test
public void bootDiagnosticsShouldUsesVMSSOSUnManagedDiskImplicitStorage() throws Exception {
final String vmssName = generateRandomResourceName("vmss", 10);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withBootDiagnostics()
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
VirtualMachineScaleSetInner inner = virtualMachineScaleSet.innerModel();
Assertions.assertNotNull(inner);
Assertions.assertNotNull(inner.virtualMachineProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile().osDisk());
List<String> containers = inner.virtualMachineProfile().storageProfile().osDisk().vhdContainers();
Assertions.assertFalse(containers.isEmpty());
// Boot diagnostics should share storage used for os/disk containers
boolean found = false;
for (String containerStorageUri : containers) {
if (containerStorageUri
.toLowerCase()
.startsWith(virtualMachineScaleSet.bootDiagnosticsStorageUri().toLowerCase())) {
found = true;
break;
}
}
Assertions.assertTrue(found);
}
@Test
public void bootDiagnosticsShouldUseVMSSUnManagedDisksExplicitStorage() throws Exception {
final String storageName = generateRandomResourceName("st", 14);
final String vmssName = generateRandomResourceName("vmss", 10);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
StorageAccount storageAccount =
storageManager
.storageAccounts()
.define(storageName)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withBootDiagnostics()
.withExistingStorageAccount(
storageAccount) // This storage account must be shared by disk and boot diagnostics
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
Assertions.assertTrue(virtualMachineScaleSet.bootDiagnosticsStorageUri().contains(storageName));
VirtualMachineScaleSetInner inner = virtualMachineScaleSet.innerModel();
Assertions.assertNotNull(inner);
Assertions.assertNotNull(inner.virtualMachineProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile().osDisk());
List<String> containers = inner.virtualMachineProfile().storageProfile().osDisk().vhdContainers();
Assertions.assertFalse(containers.isEmpty());
}
@Test
public void canEnableBootDiagnosticsWithCreatableStorageOnUnManagedVMSSCreation() throws Exception {
final String storageName = generateRandomResourceName("st", 14);
final String vmssName = generateRandomResourceName("vmss", 10);
ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(rgName).withRegion(region).create();
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
LoadBalancer publicLoadBalancer =
createInternetFacingLoadBalancer(region, resourceGroup, "1", LoadBalancerSkuType.BASIC);
List<String> backends = new ArrayList<>();
for (String backend : publicLoadBalancer.backends().keySet()) {
backends.add(backend);
}
Assertions.assertTrue(backends.size() == 2);
Creatable<StorageAccount> creatableStorageAccount =
storageManager.storageAccounts().define(storageName).withRegion(region).withExistingResourceGroup(rgName);
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmssName)
.withRegion(region)
.withExistingResourceGroup(resourceGroup)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer)
.withPrimaryInternetFacingLoadBalancerBackends(backends.get(0), backends.get(1))
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withUnmanagedDisks()
.withBootDiagnostics(
creatableStorageAccount) // This storage account should be used for BDiagnostics not OS disk storage
// account
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNotNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
Assertions.assertTrue(virtualMachineScaleSet.bootDiagnosticsStorageUri().contains(storageName));
// There should be a different storage account created for VMSS OS Disk
VirtualMachineScaleSetInner inner = virtualMachineScaleSet.innerModel();
Assertions.assertNotNull(inner);
Assertions.assertNotNull(inner.virtualMachineProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile());
Assertions.assertNotNull(inner.virtualMachineProfile().storageProfile().osDisk());
List<String> containers = inner.virtualMachineProfile().storageProfile().osDisk().vhdContainers();
Assertions.assertFalse(containers.isEmpty());
boolean notFound = true;
for (String containerStorageUri : containers) {
if (containerStorageUri
.toLowerCase()
.startsWith(virtualMachineScaleSet.bootDiagnosticsStorageUri().toLowerCase())) {
notFound = false;
break;
}
}
Assertions.assertTrue(notFound);
}
@Test
public void canEnableBootDiagnosticsOnManagedStorageAccount() {
Network network =
this
.networkManager
.networks()
.define("vmssvnet")
.withRegion(region)
.withNewResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.withSubnet("subnet1", "10.0.0.0/28")
.create();
VirtualMachineScaleSet virtualMachineScaleSet =
this
.computeManager
.virtualMachineScaleSets()
.define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0)
.withExistingPrimaryNetworkSubnet(network, "subnet1")
.withoutPrimaryInternetFacingLoadBalancer()
.withoutPrimaryInternalLoadBalancer()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername("jvuser")
.withSsh(sshPublicKey())
.withBootDiagnosticsOnManagedStorageAccount()
.create();
Assertions.assertNotNull(virtualMachineScaleSet);
Assertions.assertTrue(virtualMachineScaleSet.isBootDiagnosticsEnabled());
Assertions.assertNull(virtualMachineScaleSet.bootDiagnosticsStorageUri());
}
}
|
Azure/azure-sdk-for-java
|
sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/VirtualMachineScaleSetBootDiagnosticsTests.java
|
Java
|
mit
| 23,110 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//
package uk.org.siri.siri;
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.XmlType;
/**
* Type for list of effects.
*
* <p>Java class for PtConsequencesStructure complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PtConsequencesStructure">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Consequence" type="{http://www.siri.org.uk/siri}PtConsequenceStructure" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PtConsequencesStructure", propOrder = {
"consequence"
})
public class PtConsequencesStructure {
@XmlElement(name = "Consequence", required = true)
protected List<PtConsequenceStructure> consequence;
/**
* Gets the value of the consequence 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 consequence property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getConsequence().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PtConsequenceStructure }
*
*
*/
public List<PtConsequenceStructure> getConsequence() {
if (consequence == null) {
consequence = new ArrayList<PtConsequenceStructure>();
}
return this.consequence;
}
}
|
laidig/siri-20-java
|
src/uk/org/siri/siri/PtConsequencesStructure.java
|
Java
|
mit
| 2,372 |
package Thread;
/**
* Created by cnkaptan on 5/8/15.
*/
public class KarisikSayma {
public static void main(String[] args){
ThreadTest thrd = new ThreadTest("Thread");
Thread runnableThread = new Thread(new RunnableTest("Runnable"));
thrd.start();
runnableThread.start();
}
}
class RunnableTest implements Runnable{
String name;
public RunnableTest(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 21 ; i++){
System.out.println(name+"\t"+i);
}
}
}
class ThreadTest extends Thread{
String name;
public ThreadTest(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 21 ; i++){
System.out.println(this.getName()+"\t"+i);
}
}
}
|
cnkaptan/JavaVariousSamples
|
src/Thread/KarisikSayma.java
|
Java
|
mit
| 861 |
package com.humooooour.kit.screen;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.humooooour.kit.HSApp;
import com.humooooour.kit.geom.HSRect;
import processing.core.PApplet;
import processing.core.PGraphics;
public class HSScreen {
private HSApp mApp;
private HSRect mBounds;
public HSScreen(HSApp app, HSRect bounds) {
mApp = app;
mBounds =bounds;
}
public void dispose() {
}
public void update(float dt) {
}
public void draw(PGraphics g) {
}
public boolean handleTouch(MotionEvent touch) {
return false;
}
public boolean handleKey(KeyEvent key) {
return false;
}
protected HSApp getApp() {
return mApp;
}
protected PApplet getPApplet() {
return mApp.getPApplet();
}
protected Activity getActivity() {
return mApp.getActivity();
}
protected PGraphics getPGraphics() {
return mApp.getPGraphics();
}
protected HSRect getBounds() {
return mBounds;
}
protected HSRect getContentBounds() {
HSRect cBounds = new HSRect(mBounds);
cBounds.offsetTo(0.0f, 0.0f);
return cBounds;
}
}
|
thedoritos/HumourKit
|
src/com/humooooour/kit/screen/HSScreen.java
|
Java
|
mit
| 1,120 |
package ls;
import java.util.*;
import javax.swing.table.AbstractTableModel;
public class DirectoryTableModel extends AbstractTableModel {
private final List<DirOpt> dirs = new ArrayList<>();
public List<DirOpt> getDirs () {
return new ArrayList<>(dirs);
}
public void add (DirOpt dir) {
dirs.add(dir);
Collections.sort(dirs);
fireTableDataChanged();
}
public void addAll (List<DirOpt> dirs) {
this.dirs.addAll(dirs);
Collections.sort(this.dirs);
fireTableDataChanged();
}
public void remove (int row) {
dirs.remove(row);
fireTableDataChanged();
}
public void setDir (int row, DirOpt dir) {
dirs.set(row, dir);
Collections.sort(dirs);
fireTableDataChanged();
}
public DirOpt getDir (int row) {
return dirs.get(row);
}
@Override
public int getRowCount () {
return dirs.size();
}
@Override
public int getColumnCount () {
return 3;
}
@Override
public String getColumnName (int column) {
switch (column) {
case 0:
return "Enabled";
case 1:
return "Dir";
case 2:
return "Recursive";
default:
throw new RuntimeException();
}
}
@Override
public Class<?> getColumnClass (int columnIndex) {
switch (columnIndex) {
case 0:
case 2:
return Boolean.class;
case 1:
return String.class;
default:
throw new RuntimeException();
}
}
@Override
public boolean isCellEditable (int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
case 2:
return true;
case 1:
return false;
default:
throw new RuntimeException();
}
}
@Override
public Object getValueAt (int row, int col) {
DirOpt d = dirs.get(row);
switch (col) {
case 0:
return d.enabled;
case 1:
return d.dir;
case 2:
return d.recursive;
default:
throw new RuntimeException();
}
}
@Override
public void setValueAt (Object val, int row, int col) {
DirOpt d = dirs.get(row);
switch (col) {
case 0:
d = new DirOpt(d.dir, (Boolean) val, d.recursive);
case 2:
d = new DirOpt(d.dir, d.enabled, (Boolean) val);
break;
default:
throw new RuntimeException();
}
dirs.set(row, d);
}
}
|
alexyz/logsearch
|
src/ls/DirectoryTableModel.java
|
Java
|
mit
| 2,287 |
package com.teamunify.i18n.com.teamunify.i18n.webapp;
import com.teamunify.i18n.I;
import com.teamunify.i18n.webapp.AbstractLocaleFilter;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.*;
import static org.mockito.Mockito.*;
import javax.servlet.*;
import java.io.IOException;
import java.util.Locale;
public class ServletLocaleFilterTests {
private static Locale computedLocale;
private static Locale defaultLocale;
Filter f = new AbstractLocaleFilter() {
@Override
public Locale getLocale(ServletRequest req) {
return computedLocale;
}
@Override
public Locale getDefaultLocale() {
return defaultLocale;
}
};
private ServletRequest req;
private FilterChain chain;
private ServletResponse resp;
@Before
public void setup() {
computedLocale = Locale.US;
defaultLocale = Locale.US;
req = mock(ServletRequest.class);
resp = mock(ServletResponse.class);
chain = mock(FilterChain.class);
}
@Test
public void chains_the_filters() throws IOException, ServletException {
f.doFilter(req, resp, chain);
verify(chain).doFilter(eq(req), eq(resp));
}
@Test
public void uses_the_computed_locale_if_available() throws IOException, ServletException {
computedLocale = Locale.CHINA;
f.doFilter(req, resp, chain);
assertEquals(I.getCurrentLanguage().locale, computedLocale);
}
@Test
public void uses_the_filter_default_locale_if_compute_fails() throws IOException, ServletException {
computedLocale = null;
defaultLocale = Locale.KOREA;
f.doFilter(req, resp, chain);
assertEquals(I.getCurrentLanguage().locale, defaultLocale);
}
@Test
public void uses_the_system_locale_if_no_computed_or_default_available() throws IOException, ServletException {
computedLocale = null;
defaultLocale = null;
f.doFilter(req, resp, chain);
assertEquals(I.getCurrentLanguage().locale, Locale.getDefault());
}
}
|
awkay/easy-i18n
|
src/test/java/com/teamunify/i18n/com/teamunify/i18n/webapp/ServletLocaleFilterTests.java
|
Java
|
mit
| 1,982 |
/*
The MIT License (MIT)
Copyright (c) 2016 EMC Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.emc.ecs.metadata.dao.elasticsearch;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map.Entry;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.ReceiveTimeoutTransportException;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.emc.ecs.metadata.dao.EcsCollectionType;
import com.emc.ecs.metadata.dao.ObjectDAO;
import com.emc.ecs.metadata.utils.Constants;
import com.emc.object.s3.bean.AbstractVersion;
import com.emc.object.s3.bean.DeleteMarker;
import com.emc.object.s3.bean.ListObjectsResult;
import com.emc.object.s3.bean.ListVersionsResult;
import com.emc.object.s3.bean.QueryMetadata;
import com.emc.object.s3.bean.QueryObject;
import com.emc.object.s3.bean.QueryObjectsResult;
import com.emc.object.s3.bean.S3Object;
import com.emc.object.s3.bean.Version;
public class ElasticS3ObjectDAO implements ObjectDAO {
private final static String CLIENT_SNIFFING_CONFIG = "client.transport.sniff";
private final static String CLIENT_TRANSPORT_PING_TIMEOUT = "client.transport.ping_timeout";
private final static String CLIENT_CLUSTER_NAME_CONFIG = "cluster.name";
public final static String S3_OBJECT_INDEX_NAME = "ecs-s3-object";
public final static String S3_OBJECT_VERSION_INDEX_NAME = "ecs-object-version";
public final static String S3_OBJECT_INDEX_TYPE = "object-info";
public final static String S3_OBJECT_VERSION_INDEX_TYPE = "object-version-info";
public final static String COLLECTION_TIME = "collection_time";
public final static String ANALYZED_TAG = "_analyzed";
public final static String NOT_ANALYZED_INDEX = "not_analyzed";
public final static String ANALYZED_INDEX = "analyzed";
public final static String LAST_MODIFIED_TAG = "last_modified";
public final static String SIZE_TAG = "size";
public final static String KEY_TAG = "key";
public final static String OWNER_ID_TAG = "owner_id";
public final static String OWNER_NAME_TAG = "owner_name";
public final static String NAMESPACE_TAG = "namespace";
public final static String BUCKET_TAG = "bucket";
public final static String ETAG_TAG = "e_tag";
public final static String VERSION_ID_TAG = "version_id";
public final static String IS_LATEST_TAG = "is_latest";
public final static String CUSTOM_GID_TAG = "x-amz-meta-x-emc-posix-group-owner-name";
public final static String CUSTOM_UID_TAG = "x-amz-meta-x-emc-posix-owner-name";
public final static String CUSTOM_MODIFIED_TIME_TAG = "mtime";
//=========================
// Private members
//=========================
private TransportClient elasticClient;
private static Logger LOGGER = LoggerFactory.getLogger(ElasticS3ObjectDAO.class);
private static final String DATA_DATE_PATTERN = "yyyy-MM-dd";
private static final String DATA_DATE_PATTERN_SEC = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat DATA_DATE_FORMAT = new SimpleDateFormat(DATA_DATE_PATTERN);
private static final SimpleDateFormat DATA_DATE_FORMAT_SEC = new SimpleDateFormat(DATA_DATE_PATTERN_SEC);
private static String s3ObjectVersionIndexDayName;
private static String s3ObjectIndexDayName;
private ElasticDAOConfig config;
//=========================
// Public methods
//=========================
public ElasticS3ObjectDAO( ElasticDAOConfig config ) {
try {
this.config = config;
Builder builder = Settings.builder();
// Check for new hosts within the cluster
builder.put(CLIENT_SNIFFING_CONFIG, true);
builder.put(CLIENT_TRANSPORT_PING_TIMEOUT, "15s");
if (config.getXpackUser() != null) {
builder.put(Constants.XPACK_SECURITY_USER, config.getXpackUser() + ":" + config.getXpackPassword());
builder.put(Constants.XPACK_SSL_KEY, config.getXpackSslKey());
builder.put(Constants.XPACK_SSL_CERTIFICATE, config.getXpackSslCertificate());
builder.put(Constants.XPACK_SSL_CERTIFICATE_AUTH, config.getXpackSslCertificateAuthorities());
builder.put(Constants.XPACK_SECURITY_TRANPORT_ENABLED, "true");
}
// specify cluster name
if( config.getClusterName() != null ) {
builder.put(CLIENT_CLUSTER_NAME_CONFIG, config.getClusterName());
}
Settings settings = builder.build();
// create client
// create client
if (config.getXpackUser() != null) {
elasticClient = new PreBuiltXPackTransportClient(settings);
} else {
elasticClient = new PreBuiltTransportClient(settings);
}
// add hosts
for( String elasticHost : config.getHosts()) {
elasticClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(elasticHost), config.getPort()));
}
} catch (UnknownHostException e) {
throw new RuntimeException(e.getLocalizedMessage());
} catch (ReceiveTimeoutTransportException re) {
LOGGER.error("An error occured while connecting to ElasticSearch Cluster ", re);
System.exit(1);
}
}
/**
* Init indexes
* @param collectionTime - collection time
*/
@Override
public void initIndexes(Date collectionTime) {
// init S3 Object Index
if( config.getCollectionType().equals(EcsCollectionType.object) ) {
initS3ObjectIndex( collectionTime );
}
// init S3 Object Version Index
if( config.getCollectionType().equals(EcsCollectionType.object_version) ) {
initS3ObjectVersionIndex( collectionTime );
}
}
/**
* {@inheritDoc}
*/
@Override
public void insert(ListObjectsResult listObjectsResult, String namespace, String bucket, Date collectionTime) {
if( listObjectsResult == null ||
listObjectsResult.getObjects() == null ||
listObjectsResult.getObjects().isEmpty() ) {
// nothing to insert
return;
}
BulkRequestBuilder requestBuilder = elasticClient.prepareBulk();
// Generate JSON for object buckets info
for( S3Object s3Object : listObjectsResult.getObjects() ) {
XContentBuilder s3ObjectBuilder = toJsonFormat(s3Object, namespace, bucket, collectionTime);
IndexRequestBuilder request = elasticClient.prepareIndex()
.setIndex(s3ObjectIndexDayName)
.setType(S3_OBJECT_INDEX_TYPE)
.setSource(s3ObjectBuilder);
requestBuilder.add(request);
}
BulkResponse bulkResponse = requestBuilder.execute().actionGet();
int items = bulkResponse.getItems().length;
LOGGER.info( "Took " + bulkResponse.getTookInMillis() + " ms to index [" + items + "] items in Elasticsearch " + "index: " +
s3ObjectIndexDayName + " index type: " + S3_OBJECT_INDEX_TYPE );
if( bulkResponse.hasFailures() ) {
LOGGER.error( "Failure(s) occured while items in Elasticsearch " + "index: " +
s3ObjectIndexDayName + " index type: " + S3_OBJECT_INDEX_TYPE );
}
}
/**
* {@inheritDoc}
*/
@Override
public void insert( QueryObjectsResult queryObjectsResult, String namespace,
String bucketName, Date collectionTime ) {
if( queryObjectsResult == null ||
queryObjectsResult.getObjects() == null ||
queryObjectsResult.getObjects().isEmpty() ) {
// nothing to insert
return;
}
BulkRequestBuilder requestBuilder = elasticClient.prepareBulk();
// Generate JSON for object buckets info
for( QueryObject queryObject : queryObjectsResult.getObjects() ) {
XContentBuilder s3ObjectBuilder = toJsonFormat(queryObject, namespace, bucketName, collectionTime);
IndexRequestBuilder request = elasticClient.prepareIndex()
.setIndex(s3ObjectIndexDayName)
.setType(S3_OBJECT_INDEX_TYPE)
.setSource(s3ObjectBuilder);
requestBuilder.add(request);
}
BulkResponse bulkResponse = requestBuilder.execute().actionGet();
int items = bulkResponse.getItems().length;
LOGGER.info( "Took " + bulkResponse.getTookInMillis() + " ms to index [" + items + "] items in Elasticsearch " + "index: " +
s3ObjectIndexDayName + " index type: " + S3_OBJECT_INDEX_TYPE );
if( bulkResponse.hasFailures() ) {
LOGGER.error( "Failure(s) occured while items in Elasticsearch " + "index: " +
s3ObjectIndexDayName + " index type: " + S3_OBJECT_INDEX_TYPE );
}
}
/**
* {@inheritDoc}
*/
@Override
public void insert(ListVersionsResult listVersionsResult, String namespace,
String bucketName, Date collectionTime) {
if( listVersionsResult == null ||
listVersionsResult.getVersions() == null ||
listVersionsResult.getVersions().isEmpty() ) {
// nothing to insert
return;
}
BulkRequestBuilder requestBuilder = elasticClient.prepareBulk();
// Generate JSON for object version info
for( AbstractVersion abstractVersion : listVersionsResult.getVersions() ) {
if(abstractVersion instanceof Version) {
XContentBuilder s3ObjectVersionBuilder = toJsonFormat((Version)abstractVersion, namespace, bucketName, collectionTime);
IndexRequestBuilder request = elasticClient.prepareIndex()
.setIndex(s3ObjectVersionIndexDayName)
.setType(S3_OBJECT_VERSION_INDEX_TYPE)
.setSource(s3ObjectVersionBuilder);
requestBuilder.add(request);
} else if(abstractVersion instanceof DeleteMarker) {
XContentBuilder s3ObjectVersionBuilder = toJsonFormat((DeleteMarker)abstractVersion, namespace, bucketName, collectionTime);
IndexRequestBuilder request = elasticClient.prepareIndex()
.setIndex(s3ObjectVersionIndexDayName)
.setType(S3_OBJECT_VERSION_INDEX_TYPE)
.setSource(s3ObjectVersionBuilder);
requestBuilder.add(request);
}
}
BulkResponse bulkResponse = requestBuilder.execute().actionGet();
int items = bulkResponse.getItems().length;
LOGGER.info( "Took " + bulkResponse.getTookInMillis() + " ms to index [" + items + "] items in Elasticsearch " + "index: " +
s3ObjectVersionIndexDayName + " index type: " + S3_OBJECT_VERSION_INDEX_TYPE );
if( bulkResponse.hasFailures() ) {
LOGGER.error( "Failure(s) occured while items in Elasticsearch " + "index: " +
s3ObjectVersionIndexDayName + " index type: " + S3_OBJECT_VERSION_INDEX_TYPE );
}
}
/**
* {@inheritDoc}
*/
@Override
public Long purgeOldData(ObjectDataType type, Date thresholdDate) {
switch(type) {
case object:
// Purge old S3 Objects
ElasticIndexCleaner.truncateOldIndexes( elasticClient, thresholdDate,
S3_OBJECT_INDEX_NAME, S3_OBJECT_INDEX_TYPE);
return 0L;
case object_versions:
// Purge old S3 Object Versions
ElasticIndexCleaner.truncateOldIndexes( elasticClient, thresholdDate,
S3_OBJECT_VERSION_INDEX_NAME,
S3_OBJECT_VERSION_INDEX_TYPE );
return 0L;
default:
return 0L;
}
}
/**
* Converts Object data in JSON format for Elasticsearch
*
* @param s3Object - S3 Object
* @param namespace - namespace
* @param bucket - bucket name
* @param collectionTime - collection time
* @return XContentBuilder
*/
public static XContentBuilder toJsonFormat( S3Object s3Object, String namespace, String bucket, Date collectionTime ) {
return toJsonFormat(s3Object, namespace, bucket,collectionTime, null);
}
/**
* Converts Object data in JSON format for Elasticsearch
*
* @param version - version
* @param namespace - namespace
* @param bucketName - bucket name
* @param collectionTime - collectionTime
* @return XContentBuilder
*/
public XContentBuilder toJsonFormat(Version version,
String namespace, String bucketName, Date collectionTime) {
return toJsonFormat( version, namespace, bucketName, collectionTime, null);
}
/**
* Converts Object data in JSON format for Elasticsearch
*
* @param deleteMarker - deleteMarker
* @param namespace - namespace
* @param bucketName - bucket name
* @param collectionTime - collection time
* @return XContentBuilders
*/
public XContentBuilder toJsonFormat(DeleteMarker deleteMarker,
String namespace, String bucketName, Date collectionTime) {
return toJsonFormat( deleteMarker, namespace, bucketName, collectionTime, null);
}
/**
* Converts Object data in JSON format for Elasticsearch
*
* @param s3Object - S3 Object
* @param namespace - namespace
* @param bucket - bucket
* @param collectionTime - collection time
* @return XContentBuilder
*/
public static XContentBuilder toJsonFormat( QueryObject s3Object, String namespace, String bucket, Date collectionTime ) {
return toJsonFormat(s3Object, namespace, bucket,collectionTime, null);
}
//=======================
// Private methods
//=======================
/**
* Init Object index
*/
private void initS3ObjectIndex( Date collectionTime ) {
String collectionDayString = DATA_DATE_FORMAT_SEC.format(collectionTime);
s3ObjectIndexDayName = S3_OBJECT_INDEX_NAME + "-" + collectionDayString.replaceAll(" ", "-");
if (elasticClient
.admin()
.indices()
.exists(new IndicesExistsRequest(s3ObjectIndexDayName))
.actionGet()
.isExists()) {
// Index already exists need to truncate it and recreate it
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(s3ObjectIndexDayName);
ActionFuture<DeleteIndexResponse> futureResult = elasticClient.admin().indices().delete(deleteIndexRequest);
// Wait until deletion is done
while( !futureResult.isDone() ) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
elasticClient.admin().indices().create(new CreateIndexRequest(s3ObjectIndexDayName)).actionGet();
try {
PutMappingResponse putMappingResponse = elasticClient.admin().indices()
.preparePutMapping(s3ObjectIndexDayName)
.setType(S3_OBJECT_INDEX_TYPE)
.setSource(XContentFactory.jsonBuilder().prettyPrint()
.startObject()
.startObject(S3_OBJECT_INDEX_TYPE)
// ========================================
// Define how the basic fields are defined
// ========================================
.startObject("properties")
// LAST_MODIFIED_TAG
.startObject( LAST_MODIFIED_TAG ).field("type", "date")
.field("format", "strict_date_optional_time||epoch_millis").endObject()
// SIZE_TAG
.startObject( SIZE_TAG ).field("type", "string").field("type", "long").endObject()
// KEY_TAG
.startObject( KEY_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// KEY_TAG Analyzed
.startObject( KEY_TAG + ANALYZED_TAG).field("type", "string")
.field("index", ANALYZED_INDEX).endObject()
.startObject( ETAG_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// NAMESPACE_TAG
.startObject( NAMESPACE_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// BUCKET_TAG
.startObject( BUCKET_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// OWNER_ID_TAG
.startObject( OWNER_ID_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// OWNER_NAME_TAG
.startObject( OWNER_NAME_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// COLLECTION_TIME
.startObject( COLLECTION_TIME ).field("type", "date")
.field("format", "strict_date_optional_time||epoch_millis||date_time_no_millis").endObject()
// CUSTOM_GID_TAG
.startObject( CUSTOM_GID_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// CUSTOM_UID_TAG
.startObject( CUSTOM_UID_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// CUSTOM_MODIFIED_TIME_TAG
.startObject( CUSTOM_MODIFIED_TIME_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
.endObject()
// =================================
// Dynamic fields won't be analyzed
// =================================
.startArray("dynamic_templates")
.startObject()
.startObject("notanalyzed")
.field("match", "*")
.field("match_mapping_type", "string")
.startObject( "mapping" ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
.endObject()
.endObject()
.endArray()
.endObject()
.endObject() )
.execute().actionGet();
if (putMappingResponse.isAcknowledged()) {
LOGGER.info("Index Created: " + s3ObjectIndexDayName);
} else {
LOGGER.error("Index {} did not exist. " +
"While attempting to create the index from stored ElasticSearch " +
"Templates we were unable to get an acknowledgement.", s3ObjectIndexDayName);
LOGGER.error("Error Message: {}", putMappingResponse.toString());
throw new RuntimeException("Unable to create index " + s3ObjectIndexDayName);
}
} catch (IOException e) {
throw new RuntimeException( "Unable to create index " +
s3ObjectIndexDayName + " " + e.getMessage() );
}
}
/**
* Converts Object data into JSON format
*
* @param s3Object - S3 Object
* @param namespace - namespace
* @param bucket - bucket
* @param collectionTime - collection time
* @param builder - builder
* @return XContentBuilder
*/
private static XContentBuilder toJsonFormat( S3Object s3Object,
String namespace,
String bucket,
Date collectionTime,
XContentBuilder builder) {
try {
if(builder == null) {
builder = XContentFactory.jsonBuilder();
}
// add relevant fileds
builder = builder.startObject()
.field( LAST_MODIFIED_TAG, s3Object.getLastModified() )
.field( SIZE_TAG, s3Object.getSize() )
.field( KEY_TAG, s3Object.getKey() )
.field( KEY_TAG + ANALYZED_TAG, s3Object.getKey() )
.field( ETAG_TAG , s3Object.getETag())
.field( NAMESPACE_TAG, namespace )
.field( BUCKET_TAG, bucket )
.field( OWNER_ID_TAG, (s3Object.getOwner() != null && s3Object.getOwner().getId() != null)
? s3Object.getOwner().getId() : null )
.field( OWNER_NAME_TAG, (s3Object.getOwner() != null && s3Object.getOwner().getDisplayName() != null)
? s3Object.getOwner().getDisplayName() : null )
.field( COLLECTION_TIME, collectionTime )
.endObject();
} catch (IOException e) {
throw new RuntimeException(e.getLocalizedMessage());
}
return builder;
}
/**
* Init Object version index
*/
private void initS3ObjectVersionIndex( Date collectionTime ) {
String collectionDayString = DATA_DATE_FORMAT.format(collectionTime);
s3ObjectVersionIndexDayName = S3_OBJECT_VERSION_INDEX_NAME + "-" + collectionDayString;
if (elasticClient
.admin()
.indices()
.exists(new IndicesExistsRequest(s3ObjectVersionIndexDayName))
.actionGet()
.isExists()) {
// Index already exists need to truncate it and recreate it
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(s3ObjectVersionIndexDayName);
ActionFuture<DeleteIndexResponse> futureResult = elasticClient.admin().indices().delete(deleteIndexRequest);
// Wait until deletion is done
while( !futureResult.isDone() ) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
elasticClient.admin().indices().create(new CreateIndexRequest(s3ObjectVersionIndexDayName)).actionGet();
try {
PutMappingResponse putMappingResponse = elasticClient.admin().indices()
.preparePutMapping(s3ObjectVersionIndexDayName)
.setType(S3_OBJECT_VERSION_INDEX_TYPE)
.setSource(XContentFactory.jsonBuilder().prettyPrint()
.startObject()
.startObject(S3_OBJECT_VERSION_INDEX_TYPE)
// ========================================
// Define how the basic fields are defined
// ========================================
.startObject("properties")
// LAST_MODIFIED_TAG
.startObject( LAST_MODIFIED_TAG ).field("type", "date")
.field("format", "strict_date_optional_time||epoch_millis").endObject()
// SIZE_TAG
.startObject( SIZE_TAG ).field("type", "string").field("type", "long").endObject()
// KEY_TAG
.startObject( KEY_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// KEY_TAG Analyzed
.startObject( KEY_TAG + ANALYZED_TAG).field("type", "string")
.field("index", ANALYZED_INDEX).endObject()
.startObject( ETAG_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// NAMESPACE_TAG
.startObject( NAMESPACE_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// BUCKET_TAG
.startObject( BUCKET_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// VERSION_ID_TAG
.startObject( VERSION_ID_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// IS_LATEST_TAG
.startObject( IS_LATEST_TAG ).field("type", "boolean")
.field("index", NOT_ANALYZED_INDEX).endObject()
// OWNER_ID_TAG
.startObject( OWNER_ID_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// OWNER_NAME_TAG
.startObject( OWNER_NAME_TAG ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
// COLLECTION_TIME
.startObject( COLLECTION_TIME ).field("type", "date")
.field("format", "strict_date_optional_time||epoch_millis").endObject()
.endObject()
// =================================
// Dynamic fields won't be analyzed
// =================================
.startArray("dynamic_templates")
.startObject()
.startObject("notanalyzed")
.field("match", "*")
.field("match_mapping_type", "string")
.startObject( "mapping" ).field("type", "string")
.field("index", NOT_ANALYZED_INDEX).endObject()
.endObject()
.endObject()
.endArray()
.endObject()
.endObject() )
.execute().actionGet();
if (putMappingResponse.isAcknowledged()) {
LOGGER.info("Index Created: " + s3ObjectVersionIndexDayName);
} else {
LOGGER.error("Index {} did not exist. " +
"While attempting to create the index from stored ElasticSearch " +
"Templates we were unable to get an acknowledgement.", s3ObjectVersionIndexDayName);
LOGGER.error("Error Message: {}", putMappingResponse.toString());
throw new RuntimeException("Unable to create index " + s3ObjectVersionIndexDayName);
}
} catch (IOException e) {
throw new RuntimeException( "Unable to create index " +
s3ObjectVersionIndexDayName +
" " + e.getMessage() );
}
}
/**
* Converts object version data to json
*
* @param version - version
* @param namespace - namespace
* @param bucket - bucket
* @param collectionTime - collection time
* @param builder - builder
* @return XContentBuilder
*/
private static XContentBuilder toJsonFormat( Version version,
String namespace,
String bucket,
Date collectionTime,
XContentBuilder builder) {
try {
if(builder == null) {
builder = XContentFactory.jsonBuilder();
}
// add relevant fields
builder = builder.startObject()
.field( LAST_MODIFIED_TAG, version.getLastModified() )
.field( SIZE_TAG, version.getSize() )
.field( KEY_TAG, version.getKey() )
.field( KEY_TAG + ANALYZED_TAG, version.getKey() )
.field( ETAG_TAG , version.getETag())
.field( NAMESPACE_TAG, namespace )
.field( BUCKET_TAG, bucket )
.field( VERSION_ID_TAG, version.getVersionId() )
.field( IS_LATEST_TAG, version.isLatest())
.field( OWNER_ID_TAG, (version.getOwner() != null && version.getOwner().getId() != null)
? version.getOwner().getId() : null )
.field( OWNER_NAME_TAG, (version.getOwner() != null && version.getOwner().getDisplayName() != null)
? version.getOwner().getDisplayName() : null )
.field( COLLECTION_TIME, collectionTime )
.endObject();
} catch (IOException e) {
throw new RuntimeException(e.getLocalizedMessage());
}
return builder;
}
/**
* Converts
*
* @param deleteMarker - delete marker
* @param namespace - namespace
* @param bucket - bucket
* @param collectionTime - collection time
* @param builder - builder
* @return XContentBuilder
*/
private static XContentBuilder toJsonFormat( DeleteMarker deleteMarker,
String namespace,
String bucket,
Date collectionTime,
XContentBuilder builder) {
try {
if(builder == null) {
builder = XContentFactory.jsonBuilder();
}
// add relevant fields
builder = builder.startObject()
.field( LAST_MODIFIED_TAG, deleteMarker.getLastModified() )
.field( KEY_TAG, deleteMarker.getKey() )
.field( KEY_TAG + ANALYZED_TAG, deleteMarker.getKey() )
.field( NAMESPACE_TAG, namespace )
.field( BUCKET_TAG, bucket )
.field( VERSION_ID_TAG, deleteMarker.getVersionId() )
.field( IS_LATEST_TAG, deleteMarker.isLatest())
.field( OWNER_ID_TAG, (deleteMarker.getOwner() != null && deleteMarker.getOwner().getId() != null)
? deleteMarker.getOwner().getId() : null )
.field( OWNER_NAME_TAG, (deleteMarker.getOwner() != null && deleteMarker.getOwner().getDisplayName() != null)
? deleteMarker.getOwner().getDisplayName() : null )
.field( COLLECTION_TIME, collectionTime )
.endObject();
} catch (IOException e) {
throw new RuntimeException(e.getLocalizedMessage());
}
return builder;
}
/**
* Converts Query Object data into JSON
*
* @param queryObject - Query Object
* @param namespace - Namespace
* @param bucket - Bucket
* @param collectionTime - Collection Time
* @param builder - Builder
* @return XContentBuilder
*/
private static XContentBuilder toJsonFormat( QueryObject queryObject,
String namespace,
String bucket,
Date collectionTime,
XContentBuilder builder) {
try {
if(builder == null) {
builder = XContentFactory.jsonBuilder();
}
// add known basic fields
builder = builder.startObject()
.field( KEY_TAG, queryObject.getObjectName() )
.field( KEY_TAG + ANALYZED_TAG, queryObject.getObjectName() )
.field( ETAG_TAG , queryObject.getObjectId())
.field( NAMESPACE_TAG, namespace )
.field( BUCKET_TAG, bucket )
.field( COLLECTION_TIME, collectionTime );
// Add custom MS Key values as dynamic fields
for( QueryMetadata metadata : queryObject.getQueryMds() ) {
for( Entry<String, String> entry : metadata.getMdMap().entrySet() ) {
builder.field(entry.getKey(), entry.getValue());
}
}
builder.endObject();
} catch (IOException e) {
throw new RuntimeException(e.getLocalizedMessage());
}
return builder;
}
}
|
carone1/ecs-dashboard
|
ecs-metadata-elasticsearch-dao/src/main/java/com/emc/ecs/metadata/dao/elasticsearch/ElasticS3ObjectDAO.java
|
Java
|
mit
| 29,830 |
/*
* MapsActivity
*
* Version 1.0
*
* November 12, 2017
*
* Copyright (c) 2017 Team NOTcmput301, CMPUT301, University of Alberta - All Rights Reserved
* You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta.
* You can find a copy of the license in the project wiki on github. Otherwise please contact miller4@ualberta.ca.
*/
package com.notcmput301.habitbook;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Activity to handle map related functions
*
* @author NOTcmput301
* @version 1.0
* @since 1.0
*/
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback{
private GoogleMap mMap;
private ArrayList<HabitEvent> habitEvents;
private Gson gson = new Gson();
/**
* Called when the activity is first created.
*
* @param savedInstanceState previous instance of activity
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent receiver = getIntent();
String e = receiver.getExtras().getString("events");
try{
habitEvents = gson.fromJson(e, new TypeToken<ArrayList<HabitEvent>>(){}.getType());
} catch (Exception e1){
Log.e("error", e1.toString() );
}
Integer i = habitEvents.size();
Log.e("error", i.toString() );
//finish();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
// Add a marker in Sydney and move the camera
if (habitEvents.size()>0){
for (HabitEvent e : habitEvents){
Log.e("error", e.getComment());
if (e.getLatitude() != null){
Log.e("error", e.getLatitude().toString());
}
if (e.getLatitude() != null) {
LatLng event = new LatLng(e.getLatitude(), e.getLongitude());
mMap.addMarker(new MarkerOptions().position(event).title(e.getComment()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(event));
}
}
}
}
/**
* Function for handling location button clicks
*
*/
@Override
public boolean onMyLocationButtonClick() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
}
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude, longitude))
.radius(5000)
.strokeColor(Color.RED));
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
|
CMPUT301F17T28/NOTcmput301
|
app/src/main/java/com/notcmput301/habitbook/MapsActivity.java
|
Java
|
mit
| 6,346 |
package yokohama.unit.ast;
public abstract class AstVisitor<T> {
public abstract T visitGroup(Group group);
public abstract T visitAbbreviation(Abbreviation abbreviation);
public T visitDefinition(Definition definition) {
return definition.accept(
this::visitTest,
this::visitFourPhaseTest,
this::visitTable,
this::visitCodeBlock,
this::visitHeading);
}
public abstract T visitTest(Test test);
public abstract T visitAssertion(Assertion assertion);
public abstract T visitClause(Clause clause);
public abstract T visitProposition(Proposition proposition);
public T visitPredicate(Predicate predicate) {
return predicate.accept(
this::visitIsPredicate,
this::visitIsNotPredicate,
this::visitThrowsPredicate,
this::visitMatchesPredicate,
this::visitDoesNotMatchPredicate);
};
public abstract T visitIsPredicate(IsPredicate isPredicate);
public abstract T visitIsNotPredicate(IsNotPredicate isNotPredicate);
public abstract T visitThrowsPredicate(ThrowsPredicate throwsPredicate);
public abstract T visitMatchesPredicate(MatchesPredicate matchesPredicate);
public abstract T visitDoesNotMatchPredicate(DoesNotMatchPredicate doesNotMatchPredicate);
public T visitMatcher(Matcher matcher) {
return matcher.accept(
this::visitEqualToMatcher,
this::visitInstanceOfMatcher,
this::visitInstanceSuchThatMatcher,
this::visitNullValueMatcher);
}
public abstract T visitEqualToMatcher(EqualToMatcher equalTo);
public abstract T visitInstanceOfMatcher(InstanceOfMatcher instanceOf);
public abstract T visitInstanceSuchThatMatcher(InstanceSuchThatMatcher instanceSuchThat);
public abstract T visitNullValueMatcher(NullValueMatcher nullValue);
public T visitPattern(Pattern pattern) {
return pattern.accept((java.util.function.Function<RegExpPattern, T>)(this::visitRegExpPattern));
}
public abstract T visitRegExpPattern(RegExpPattern regExpPattern);
public T visitExpr(Expr expr) {
return expr.accept(
this::visitQuotedExpr,
this::visitStubExpr,
this::visitInvocationExpr,
this::visitIntegerExpr,
this::visitFloatingPointExpr,
this::visitBooleanExpr,
this::visitCharExpr,
this::visitStringExpr,
this::visitAnchorExpr,
this::visitAsExpr,
this::visitResourceExpr,
this::visitTempFileExpr);
}
public abstract T visitQuotedExpr(QuotedExpr quotedExpr);
public abstract T visitStubExpr(StubExpr stubExpr);
public abstract T visitInvocationExpr(InvocationExpr invocationExpr);
public abstract T visitIntegerExpr(IntegerExpr integerExpr);
public abstract T visitFloatingPointExpr(FloatingPointExpr floatingPointExpr);
public abstract T visitBooleanExpr(BooleanExpr booleanExpr);
public abstract T visitCharExpr(CharExpr charExpr);
public abstract T visitStringExpr(StringExpr stringExpr);
public abstract T visitAnchorExpr(AnchorExpr anchorExpr);
public abstract T visitAsExpr(AsExpr asExpr);
public abstract T visitResourceExpr(ResourceExpr resourceExpr);
public abstract T visitTempFileExpr(TempFileExpr tempFileExpr);
public T visitStubBehavior(StubBehavior behavior) {
return behavior.accept(
this::visitStubReturns,
this::visitStubThrows);
}
public abstract T visitStubReturns(StubReturns stubReturns);
public abstract T visitStubThrows(StubThrows stubThrows);
public abstract T visitMethodPattern(MethodPattern methodPattern);
public abstract T visitType(Type type);
public T visitNonArrayType(NonArrayType nonArrayType) {
return nonArrayType.accept(
this::visitPrimitiveType,
this::visitClassType);
}
public abstract T visitPrimitiveType(PrimitiveType primitiveType);
public abstract T visitClassType(ClassType classType);
public T visitFixture(Fixture fixture) {
return fixture.accept(
this::visitNone,
this::visitTableRef,
this::visitBindings);
}
public abstract T visitNone();
public abstract T visitTableRef(TableRef tableRef);
public abstract T visitBindings(Bindings bindings);
public T visitBinding(Binding binding) {
return binding.accept(
this::visitSingleBinding,
this::visitChoiceBinding,
this::visitTableBinding);
}
public abstract T visitSingleBinding(SingleBinding singleBinding);
public abstract T visitChoiceBinding(ChoiceBinding choiceBinding);
public abstract T visitTableBinding(TableBinding tableBinding);
public abstract T visitFourPhaseTest(FourPhaseTest fourPhaseTest);
public abstract T visitPhase(Phase phase);
public abstract T visitVerifyPhase(VerifyPhase verifyPhase);
public abstract T visitLetStatement(LetStatement letStatement);
public T visitStatement(Statement statement) {
return statement.accept(
this::visitExecution,
this::visitInvoke);
}
public abstract T visitExecution(Execution execution);
public abstract T visitInvoke(Invoke invoke);
public abstract T visitTable(Table table);
public abstract T visitRow(Row row);
public T visitCell(Cell cell) {
return cell.accept(
this::visitExprCell,
this::visitPredCell);
}
public abstract T visitExprCell(ExprCell exprCell);
public abstract T visitPredCell(PredCell predCell);
public abstract T visitCodeBlock(CodeBlock codeBlock);
public abstract T visitHeading(Heading heading);
public abstract T visitIdent(Ident ident);
}
|
tkob/yokohamaunit
|
src/main/java/yokohama/unit/ast/AstVisitor.java
|
Java
|
mit
| 6,022 |
package de.gurkenlabs.litiengine.entities;
import de.gurkenlabs.litiengine.graphics.RenderEngine;
import java.awt.Graphics2D;
import java.util.EventObject;
/**
* This {@code EventObject} contains data about the rendering process of an entity.
*
* @see RenderEngine#renderEntity(Graphics2D, IEntity)
*/
public class EntityRenderEvent extends EventObject {
private static final long serialVersionUID = 6397005859146712222L;
private final transient Graphics2D graphics;
private final transient IEntity entity;
public EntityRenderEvent(final Graphics2D graphics, final IEntity entity) {
super(entity);
this.graphics = graphics;
this.entity = entity;
}
/**
* Gets the graphics object on which the entity is rendered.
*
* @return The graphics object on which the entity is rendered.
*/
public Graphics2D getGraphics() {
return this.graphics;
}
/**
* Get the entity involved with the rendering process.
*
* @return The entity involved with the rendering process.
*/
public IEntity getEntity() {
return this.entity;
}
}
|
gurkenlabs/litiengine
|
core/src/main/java/de/gurkenlabs/litiengine/entities/EntityRenderEvent.java
|
Java
|
mit
| 1,089 |
package mcjty.rftools.blocks.teleporter;
import mcjty.rftools.network.PacketListFromServer;
import io.netty.buffer.ByteBuf;
import java.util.List;
public class PacketReceiversReady extends PacketListFromServer<PacketReceiversReady,TeleportDestinationClientInfo> {
public PacketReceiversReady() {
}
public PacketReceiversReady(int x, int y, int z, String command, List<TeleportDestinationClientInfo> list) {
super(x, y, z, command, list);
}
@Override
protected TeleportDestinationClientInfo createItem(ByteBuf buf) {
return new TeleportDestinationClientInfo(buf);
}
}
|
Adaptivity/RFTools
|
src/main/java/mcjty/rftools/blocks/teleporter/PacketReceiversReady.java
|
Java
|
mit
| 617 |
package com.elderbyte.josc.api;
import com.elderbyte.josc.core.BlobObjectUtils;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
/**
* Represents a blob object
*/
public interface BlobObject {
/**
* Gets the bucket name where this object is stored
*/
String getBucket();
/**
* Gets the object key.
*
* The object key is unique inside a bucket.
* It may contain slashes '/', which are considered as virtual directory notations.
*/
String getObjectKey();
/**
* @deprecated Please switch to getObjectKey()
*/
default String getObjectName() {
return getObjectKey();
}
/**
* The blob object size in bytes
*/
long getLength();
/**
* Gets the content type (mime-type) of this object.
*/
Optional<String> getContentType();
/**
* Gets the objects server side calculated hash.
* Might not be available.
*/
Optional<String> getObjectHash();
/**
* @deprecated Please switch to getObjectHash()
*/
default String hash() {
return getObjectHash().orElse(null);
}
/**
* Last modified / creation date of this object
*/
Optional<Instant> getLastModified();
/**
* Other metadata data
*/
Map<String,String> getMetaData();
/**
* Returns true if this object is actually a directory.
*/
boolean isDirectory();
/**
* Returns the filename of this object.
* Slashes are interpreted as virtual directory indicators.
*
* @return Returns the last part after the last '/', if no '/' is found returns the input string.
*/
default String getVirtualFileName(){
return BlobObjectUtils.extractVirtualFileName(getObjectKey());
}
/**
* Extracts the extension from this object.
* Only the file name part is considered for extension scanning.
*
* @return Returns the extension with the dot, such as '.png'
*/
default String getVirtualExtension(){
return BlobObjectUtils.extractVirtualExtensionWithDot(getObjectKey());
}
}
|
ElderByte-/josc
|
josc-api/src/main/java/com/elderbyte/josc/api/BlobObject.java
|
Java
|
mit
| 2,141 |
package ch.heigvd.amt.mvcdemo.rest.resources;
import ch.heigvd.amt.mvcdemo.model.entities.Sector;
import ch.heigvd.amt.mvcdemo.rest.dto.SectorDTO;
import ch.heigvd.amt.mvcdemo.services.dao.BusinessDomainEntityNotFoundException;
import ch.heigvd.amt.mvcdemo.services.dao.SectorsDAOLocal;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;
/**
*
* @author Olivier Liechti (olivier.liechti@heig-vd.ch)
*/
@Stateless
@Path("/sectors")
public class SectorsResource {
@Context
UriInfo uriInfo;
@EJB
private SectorsDAOLocal sectorsDAO;
@GET
@Produces("application/json")
public List<SectorDTO> getSectors() {
List<SectorDTO> result = new ArrayList<>();
List<Sector> sectors = sectorsDAO.findAll();
for (Sector sector : sectors) {
long sectorId = sector.getId();
URI sectorHref = uriInfo
.getAbsolutePathBuilder()
.path(SectorsResource.class, "getSector")
.build(sectorId);
SectorDTO dto = new SectorDTO();
dto.setHref(sectorHref);
dto.setName(sector.getName());
result.add(dto);
}
return result;
}
@POST
@Consumes("application/json")
public Response createSector(SectorDTO sectorDTO) {
boolean created;
long sectorId;
try {
sectorId = sectorsDAO.findByName(sectorDTO.getName()).getId();
created = false;
} catch (BusinessDomainEntityNotFoundException ex) {
created = true;
sectorId = sectorsDAO.create(new Sector(sectorDTO.getName()));
}
URI sectorUri = uriInfo
.getBaseUriBuilder()
.path(SectorsResource.class)
.path(SectorsResource.class, "getSector")
.build(sectorId);
ResponseBuilder builder;
if (created) {
builder = Response.created(sectorUri);
} else {
builder = Response.ok().location(sectorUri);
}
return builder.build();
}
@GET
@Path("/{id}")
@Produces("application/json")
public Sector getSector(@PathParam(value = "id") long id) throws BusinessDomainEntityNotFoundException {
return sectorsDAO.findById(id);
}
@PUT
@Path("/{id}")
@Consumes("application/json")
public Response updateSector(SectorDTO sectorDTO, @PathParam(value = "id") long id) throws BusinessDomainEntityNotFoundException {
Sector sector = sectorsDAO.findById(id);
sector.setName(sectorDTO.getName());
return Response.ok().build();
}
@DELETE
@Path("/{id}")
public Response deleteSector(@PathParam(value = "id") long id) throws BusinessDomainEntityNotFoundException {
Sector sector = sectorsDAO.findById(id);
sectorsDAO.delete(sector);
return Response.ok().build();
}
}
|
SoftEng-HEIGVD/Teaching-HEIGVD-AMT-Example-MVC
|
MVCDemo/src/main/java/ch/heigvd/amt/mvcdemo/rest/resources/SectorsResource.java
|
Java
|
mit
| 3,061 |
/*
* 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 eu.diversify.ffbpg.evolution.platforms;
import eu.diversify.ffbpg.Application;
import eu.diversify.ffbpg.BPGraph;
import eu.diversify.ffbpg.Platform;
import eu.diversify.ffbpg.Service;
import eu.diversify.ffbpg.collections.SortedIntegerSet;
import eu.diversify.ffbpg.random.RandomUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
/**
* This operator selects a random platform and makes it drop one service.
* The removed services is either an unused ser
*
* @author ffl
*/
public class DropOneRandomService extends PlatformEvolutionOperator {
@Override
public boolean execute(BPGraph graph, Platform p) {
ArrayList<Integer> unused_services = PlatformSrvHelper.getValidServicesToRemove(graph, p);
if(!unused_services.isEmpty()) {
p.getProvidedServices().remove(unused_services.get(0));
p.clearAllCachedData();
return true;
}
else {
return false;
}
}
}
|
ffleurey/FFBPG
|
src/main/java/eu/diversify/ffbpg/evolution/platforms/DropOneRandomService.java
|
Java
|
mit
| 1,234 |
package org.swcraft.javase.collections.map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.junit.Test;
public class MapImplementationsTest {
@Test
public void testHashMap() throws Exception {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("C", 2);
map.put("B", 5);
map.put(null, 3);
System.out.println(map);
System.out.println(map.containsKey(null));
Integer integer = map.get(null);
System.out.println(integer);
}
@Test
public void testLinkedHashMap() throws Exception {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("C", 2);
map.put("B", 5);
map.put(null, 3);
System.out.println(map);
}
@Test
public void testTreeMap() throws Exception {
Map<String, Integer> map = new TreeMap<>();
map.put("A", 1);
map.put("C", 2);
map.put("B", 5);
// map.put(null, 3);
System.out.println(map);
}
@Test
public void testIterator() throws Exception {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("C", 2);
map.put("B", 5);
// Iterate over keys
for (String key : map.keySet()) {
System.out.println(key);
}
// Iterate over values
for (Integer value : map.values()) {
System.out.println(value);
}
// Iterate over entries
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey());
System.out.println("Value: " + entry.getValue());
}
// Iterate with foreach
map.forEach((key, value) -> {
System.out.println("Key: " + key);
System.out.println("Value: " + value);
});
}
}
|
nukesz/swcraft
|
java-se-tutorial/src/test/java/org/swcraft/javase/collections/map/MapImplementationsTest.java
|
Java
|
mit
| 1,700 |
package org.sagebionetworks.dashboard.model;
public interface AccessRecord extends Record{
String getSessionId();
String getUserId();
String getObjectId();
String getMethod();
String getUri();
String getQueryString();
String getStatus();
Long getLatency();
String getUserAgent();
String getStack();
String getHost();
String getInstance();
String getVM();
String getThreadId();
}
|
Sage-Bionetworks/dashboard-core
|
src/main/java/org/sagebionetworks/dashboard/model/AccessRecord.java
|
Java
|
mit
| 436 |
package code.template;
/**
*
* @author
*/
public class QueueArray {
int QUEUE_SIZE;
int front;
int back;
Integer[] queueArray;
public QueueArray(int size) {
queueArray = new Integer[size];
QUEUE_SIZE = size;
}
public void equeue(int putInBackArray) {
if (isFull()) {
System.out.println("Sorry the quere is full");
} else if (isEmpty()) {
front = 0;
back = 0;
} else {
back = (back + 1) % QUEUE_SIZE;
}
queueArray[back] = putInBackArray;
}
public int dequeue() {
if (isEmpty()) {
System.out.println("The queue is empty");
} else if (front == back) {
front = back - 1;
} else {
back = back + 1 % QUEUE_SIZE;
}
return queueArray[front];
}
public boolean isEmpty() {
if (front == -1 && back == -1) {
return true;
} else {
return false;
}
}
public boolean isFull() {
if ((back + 1) % QUEUE_SIZE == front) {
return true;
} else {
return false;
}
}
public int size() {
return front;
}
public void print() {
for (int i = 0; i < queueArray.length; i++) {
System.out.println(i+"/t" + queueArray[i]);
}
}
}
|
BenSaud-CS/Collage
|
Practical4_Stack&Queue/src/code/template/QueueArray.java
|
Java
|
mit
| 1,484 |
package org.fakekoji.xmlrpc.server.expensiveobjectscache;
import org.fakekoji.xmlrpc.server.xmlrpcrequestparams.XmlRpcRequestParams;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.umd.cs.findbugs.annotations.*;
public class SingleUrlResponseCache {
private final URL id;
private final Map<XmlRpcRequestParams, ResultWithTimeStamp> cache = Collections.synchronizedMap(new HashMap<>());
public SingleUrlResponseCache(final URL u) {
this.id = u;
}
public ResultWithTimeStamp get(final XmlRpcRequestParams params) {
return cache.get(params);
}
public void put(final Object result, XmlRpcRequestParams params) {
cache.put(params, new ResultWithTimeStamp(result));
}
public void remove(XmlRpcRequestParams key) {
cache.remove(key);
}
public URL getId() {
return id;
}
private static String asMinutes(long l) {
return " (" + (l / 1000 / 600) + "min)";
}
private static final Map<Class<?>, Class<?>> WRAPPER_TYPE_MAP;
static {
WRAPPER_TYPE_MAP = new HashMap<Class<?>, Class<?>>(20);
WRAPPER_TYPE_MAP.put(Integer.class, int.class);
WRAPPER_TYPE_MAP.put(Byte.class, byte.class);
WRAPPER_TYPE_MAP.put(Character.class, char.class);
WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class);
WRAPPER_TYPE_MAP.put(Double.class, double.class);
WRAPPER_TYPE_MAP.put(Float.class, float.class);
WRAPPER_TYPE_MAP.put(Long.class, long.class);
WRAPPER_TYPE_MAP.put(Short.class, short.class);
WRAPPER_TYPE_MAP.put(Void.class, void.class);
WRAPPER_TYPE_MAP.put(String.class, String.class);
}
public synchronized void dump(String preffix, BufferedWriter bw, RemoteRequestsCache validator) throws IOException {
List<Map.Entry<XmlRpcRequestParams, ResultWithTimeStamp>> entries = new ArrayList(cache.entrySet());
entries.sort((o1, o2) -> o1.getKey().getMethodName().compareTo(o2.getKey().getMethodName()));
for (Map.Entry<XmlRpcRequestParams, ResultWithTimeStamp> entry : entries) {
bw.write(preffix + XmlRpcRequestParams.toNiceString(entry.getKey()) + ": ");
bw.newLine();
bw.write(preffix + " dateCreated: " + entry.getValue().dateCreated);
bw.newLine();
bw.write(preffix + " notBeingRepalced: " + entry.getValue().notBeingRepalced);
bw.newLine();
bw.write(preffix + " validity: " + validator.isValid(entry.getValue(), entry.getKey().getMethodName(), id.getHost()));
bw.newLine();
long ttl = validator.getPerMethodValidnesMilis(entry.getKey().getMethodName(), id.getHost());
bw.write(preffix + " original ttl: " + ttl + "ms" + asMinutes(ttl));
bw.newLine();
long cttl = new Date().getTime() - entry.getValue().dateCreated.getTime();
bw.write(preffix + " time alive " + cttl + "ms" + asMinutes(cttl));
bw.newLine();
bw.write(preffix + " => ttl: " + (ttl - cttl) + "ms" + asMinutes(ttl - cttl));
bw.newLine();
if (WRAPPER_TYPE_MAP.containsKey(entry.getValue().result.getClass())) {
bw.write(preffix + " result: " + entry.getValue().result + " (" + entry.getValue().result.getClass().getName() + ")");
bw.newLine();
} else {
bw.write(preffix + " result: ");
bw.newLine();
entry.getValue().dump(preffix + " ", bw);
}
}
bw.write(preffix + "total: " + entries.size());
bw.newLine();
}
@SuppressFBWarnings(value = {"EI_EXPOSE_REP", "EI_EXPOSE_REP2"}, justification = "pure wrapper class")
public static final class ResultWithTimeStamp {
private final Date dateCreated;
private final Object result;
private boolean notBeingRepalced = true;
public ResultWithTimeStamp(final Object result) {
this.dateCreated = new Date();
this.result = result;
}
public Date getDateCreated() {
return dateCreated;
}
public Object getResult() {
return result;
}
public boolean isNotBeingReplaced() {
return notBeingRepalced;
}
public void flagBeingReplaced() {
this.notBeingRepalced = false;
}
public void dump(String preffix, BufferedWriter bw) throws IOException {
dump(preffix, result, bw);
}
private static final String FINAL_INCREMENT = " ";
public static void dump(String preffix, Object o, BufferedWriter bw) throws IOException {
if (o == null) {
bw.write(preffix + "null");
bw.newLine();
return;
}
if (o instanceof Map) {
bw.write(preffix + " map " + o.getClass().getName() + " map (size: " + ((Map) o).size());
bw.newLine();
Set<Map.Entry> entries = ((Map) o).entrySet();
for (Map.Entry e : entries) {
if (e.getKey() == null) {
bw.write(preffix + FINAL_INCREMENT + "null=");
bw.newLine();
dump(preffix + FINAL_INCREMENT + FINAL_INCREMENT, e.getValue(), bw);
} else {
bw.write(preffix + FINAL_INCREMENT + e.getKey() + "=");
bw.newLine();
dump(preffix + FINAL_INCREMENT + FINAL_INCREMENT, e.getValue(), bw);
}
}
} else if (o.getClass().isArray()) {
bw.write(preffix + " ary " + o.getClass().getName() + " ary (size: " + Array.getLength(o));
bw.newLine();
if (o instanceof Object[]) {
for (Object e : (Object[]) o) {
dump(preffix + FINAL_INCREMENT, e, bw);
}
} else if (o instanceof int[]) {
bw.write(preffix + FINAL_INCREMENT);
for (int e : (int[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof byte[]) {
bw.write(preffix + FINAL_INCREMENT);
for (byte e : (byte[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof char[]) {
bw.write(preffix + FINAL_INCREMENT);
for (char e : (char[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof boolean[]) {
bw.write(preffix + FINAL_INCREMENT);
for (boolean e : (boolean[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof double[]) {
bw.write(preffix + FINAL_INCREMENT);
for (double e : (double[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof float[]) {
bw.write(preffix + FINAL_INCREMENT);
for (float e : (float[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof long[]) {
bw.write(preffix + FINAL_INCREMENT);
for (long e : (long[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
} else if (o instanceof short[]) {
bw.write(preffix + FINAL_INCREMENT);
for (short e : (short[]) o) {
bw.write("" + e + ",");
}
bw.newLine();
}
} else if (o instanceof Collection) {
bw.write(preffix + " col " + o.getClass().getName() + " col (size: " + ((Collection) o).size());
bw.newLine();
for (Object e : (Collection) o) {
dump(preffix + FINAL_INCREMENT, e, bw);
}
} else if (o instanceof Iterable) {
bw.write(preffix + " ite " + o.getClass().getName() + " ite");
bw.newLine();
for (Object e : (Iterable) o) {
dump(preffix + FINAL_INCREMENT, e, bw);
}
} else {
bw.write(preffix + o + " (" + o.getClass().getName() + ")");
bw.newLine();
}
}
}
Set<Map.Entry<XmlRpcRequestParams, ResultWithTimeStamp>> getContent() {
return cache.entrySet();
}
}
|
judovana/jenkins-scm-koji-plugin
|
koji-scm-lib/src/main/java/org/fakekoji/xmlrpc/server/expensiveobjectscache/SingleUrlResponseCache.java
|
Java
|
mit
| 9,352 |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.item.inventory.properties;
import org.spongepowered.api.data.Property;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.inventory.InventoryProperty;
import org.spongepowered.api.util.Coerce;
import java.util.Collection;
import java.util.List;
/**
* A property type intended for use with
* {@link org.spongepowered.api.item.inventory.slots.InputSlot}s in order to
* query for slots which can accept items of the specified type. It is intended
* that the semantics of the {@link #equals} will be such that the method will
* return true if the other property contains <em>any</em> item present in this
* property's collection.
*/
public class AcceptsItems extends AbstractInventoryProperty<String, Collection<ItemType>> {
/**
* Create a new AcceptsItems property with the supplied value.
*
* @param value Item types to accept
*/
public AcceptsItems(Collection<ItemType> value) {
super(value);
}
/**
* Create a new AcceptsItems property with the supplied value and operator.
*
* @param value Item types to accept
* @param operator Logical operator to apply when comparing with other
* properties
*/
public AcceptsItems(Collection<ItemType> value, Operator operator) {
super(value, operator);
}
/**
* Create a new AcceptsItems property with the supplied value and operator.
*
* @param value Item types to accept
* @param operator Logical operator to apply when comparing with other
* properties
*/
public AcceptsItems(Object value, Operator operator) {
super(Coerce.toListOf(value, ItemType.class), operator);
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Property<?, ?> other) {
// This breaks the contract of Comparable, but we don't have a meaningful
// way of providing a natural ordering
return this.equals(other) ? 0 : this.hashCode() - this.hashCodeOf(other);
}
/**
* Returns true if <em>other</em> is also an {@link AcceptsItems} property
* and <b>any</b> item appearing in the other property's collecion appears
* in this property's collection. In formal terms, the method returns true
* if the size of the intersection between the two item type collections is
* greater than zero.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof InventoryProperty)) {
return false;
}
InventoryProperty<?, ?> other = (InventoryProperty<?, ?>) obj;
if (!other.getKey().equals(this.getKey())) {
return false;
}
List<ItemType> otherTypes = Coerce.toListOf(other.getValue(), ItemType.class);
for (ItemType t : this.value) {
if (otherTypes.contains(t)) {
return true;
}
}
return false;
}
/**
* Create an AcceptsItems property which matches AcceptsItems properties
* with containing one or more of the supplied values.
*
* @param value {@link ItemType}s to accept
* @return new property
*/
public static AcceptsItems of(Object... value) {
return new AcceptsItems(value, Operator.EQUAL);
}
}
|
frogocomics/SpongeAPI
|
src/main/java/org/spongepowered/api/item/inventory/properties/AcceptsItems.java
|
Java
|
mit
| 4,628 |
/*
* This file is part of Jiffy, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.blockartistry.world;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Used by the client renderer as well as path finding routines. Changes:
*
* + Chunk array vs. matrix
*
* + Removed unnecessary checks
*/
public class ChunkCache implements IBlockAccess {
private final int chunkX;
private final int chunkZ;
private final int dimX;
private final int dimZ;
private final Chunk[] chunkArray;
private final boolean isEmpty;
private final World worldObj;
public ChunkCache(World world, int x1, int y1, int z1, int x2, int y2, int z2, int buffer) {
this.worldObj = world;
this.chunkX = x1 - buffer >> 4;
this.chunkZ = z1 - buffer >> 4;
int l1 = x2 + buffer >> 4;
int i2 = z2 + buffer >> 4;
this.dimX = l1 - this.chunkX + 1;
this.dimZ = i2 - this.chunkZ + 1;
this.chunkArray = new Chunk[this.dimX * this.dimZ];
boolean emptyFlag = true;
for (int j2 = this.chunkX; j2 <= l1; ++j2) {
for (int k2 = this.chunkZ; k2 <= i2; ++k2) {
final int idx = j2 - this.chunkX + (k2 - this.chunkZ) * this.dimX;
final Chunk chunk = this.chunkArray[idx] = world.getChunkFromChunkCoords(j2, k2);
assert chunk != null;
if (emptyFlag && !chunk.getAreLevelsEmpty(y1, y2))
emptyFlag = false;
}
}
this.isEmpty = emptyFlag;
}
/**
* set by !chunk.getAreLevelsEmpty
*/
@SideOnly(Side.CLIENT)
public boolean extendedLevelsInChunkCache() {
return this.isEmpty;
}
public Block getBlock(final int x, final int y, final int z) {
// Seen out of range Ys come in. Haven't seen out of range
// X or Z. Relaxing range checks as not needed.
if(y < 0 || y > 255)
return Blocks.air;
final int arrayX = (x >> 4) - this.chunkX;
final int arrayZ = (z >> 4) - this.chunkZ;
assert (arrayX >= 0 && arrayX < this.dimX && arrayZ >= 0 && arrayZ < this.dimZ);
// if (l >= 0 && l < this.dimX && i1 >= 0 && i1 < this.dimZ)
return this.chunkArray[arrayX + arrayZ * this.dimX].getBlock(x & 15, y, z & 15);
}
public TileEntity getTileEntity(final int x, final int y, final int z) {
// Seen out of range Ys come in. Haven't seen out of range
// X or Z. Relaxing range checks as not needed.
if(y < 0 || y > 255)
return null;
final int arrayX = (x >> 4) - this.chunkX;
final int arrayZ = (z >> 4) - this.chunkZ;
assert (arrayX >= 0 && arrayX < this.dimX && arrayZ >= 0 && arrayZ < this.dimZ);
// if (l >= 0 && l < this.dimX && i1 >= 0 && i1 < this.dimZ)
return this.chunkArray[arrayX + arrayZ * this.dimX].func_150806_e(x & 15, y, z & 15);
}
public int getBlockMetadata(final int x, final int y, final int z) {
// Seen out of range Ys come in. Haven't seen out of range
// X or Z. Relaxing range checks as not needed.
if(y < 0 || y > 255)
return 0;
final int arrayX = (x >> 4) - this.chunkX;
final int arrayZ = (z >> 4) - this.chunkZ;
assert (arrayX >= 0 && arrayX < this.dimX && arrayZ >= 0 && arrayZ < this.dimZ);
// if (l >= 0 && l < this.dimX && i1 >= 0 && i1 < this.dimZ)
return this.chunkArray[arrayX + arrayZ * this.dimX].getBlockMetadata(x & 15, y, z & 15);
}
public boolean isAirBlock(final int x, final int y, final int z) {
return getBlock(x, y, z).getMaterial() == Material.air;
}
public int isBlockProvidingPowerTo(final int x, final int y, final int z, final int dir) {
return getBlock(x, y, z).isProvidingStrongPower(this, x, y, z, dir);
}
/**
* Any Light rendered on a 1.8 Block goes through here
*/
@SideOnly(Side.CLIENT)
public int getLightBrightnessForSkyBlocks(final int x, final int y, final int z, int p_72802_4_) {
int i1 = this.getSkyBlockTypeBrightness(EnumSkyBlock.Sky, x, y, z);
int j1 = this.getSkyBlockTypeBrightness(EnumSkyBlock.Block, x, y, z);
if (j1 < p_72802_4_) {
j1 = p_72802_4_;
}
return i1 << 20 | j1 << 4;
}
/**
* Gets the biome for a given set of x/z coordinates
*/
@SideOnly(Side.CLIENT)
public BiomeGenBase getBiomeGenForCoords(final int x, final int z) {
return this.worldObj.getBiomeGenForCoords(x, z);
}
/**
* Brightness for SkyBlock.Sky is clear white and (through color computing
* it is assumed) DEPENDENT ON DAYTIME. Brightness for SkyBlock.Block is
* yellowish and independent.
*/
@SideOnly(Side.CLIENT)
public int getSkyBlockTypeBrightness(final EnumSkyBlock skyBlock, final int x, int y, final int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z <= 30000000) {
if (skyBlock == EnumSkyBlock.Sky && this.worldObj.provider.hasNoSky)
return 0;
if (y < 0)
y = 0;
else if (y > 255)
y = 255;
final int arrayX = (x >> 4) - this.chunkX;
final int arrayZ = (z >> 4) - this.chunkZ;
assert (arrayX >= 0 && arrayX < this.dimX && arrayZ >= 0 && arrayZ < this.dimZ);
// if (l >= 0 && l < this.dimX && i1 >= 0 && i1 < this.dimZ)
final Chunk chunk = this.chunkArray[arrayX + arrayZ * this.dimX];
if (chunk.getBlock(x & 15, y, z & 15).getUseNeighborBrightness()) {
int l = this.getSpecialBlockBrightness(skyBlock, x, y + 1, z);
int i1 = this.getSpecialBlockBrightness(skyBlock, x + 1, y, z);
int j1 = this.getSpecialBlockBrightness(skyBlock, x - 1, y, z);
int k1 = this.getSpecialBlockBrightness(skyBlock, x, y, z + 1);
int l1 = this.getSpecialBlockBrightness(skyBlock, x, y, z - 1);
if (i1 > l) {
l = i1;
}
if (j1 > l) {
l = j1;
}
if (k1 > l) {
l = k1;
}
if (l1 > l) {
l = l1;
}
return l;
} else {
return chunk.getSavedLightValue(skyBlock, x & 15, y, z & 15);
}
} else {
return skyBlock.defaultLightValue;
}
}
/**
* is only used on stairs and tilled fields
*/
@SideOnly(Side.CLIENT)
public int getSpecialBlockBrightness(final EnumSkyBlock skyBlock, final int x, int y, final int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z <= 30000000) {
if (y < 0)
y = 0;
else if (y > 255)
y = 255;
final int arrayX = (x >> 4) - this.chunkX;
final int arrayZ = (z >> 4) - this.chunkZ;
assert (arrayX >= 0 && arrayX < this.dimX && arrayZ >= 0 && arrayZ < this.dimZ);
// if (l >= 0 && l < this.dimX && i1 >= 0 && i1 < this.dimZ)
return this.chunkArray[arrayX + arrayZ * this.dimX].getSavedLightValue(skyBlock, x & 15, y, z & 15);
} else {
return skyBlock.defaultLightValue;
}
}
/**
* Returns current world height.
*/
@SideOnly(Side.CLIENT)
public int getHeight() {
return 256;
}
@Override
public boolean isSideSolid(final int x, final int y, final int z, final ForgeDirection side,
final boolean _default) {
if (x < -30000000 || z < -30000000 || x >= 30000000 || z >= 30000000) {
return _default;
}
return getBlock(x, y, z).isSideSolid(this, x, y, z, side);
}
}
|
OreCruncher/Jiffy
|
src/main/java/org/blockartistry/world/ChunkCache.java
|
Java
|
mit
| 8,333 |
package org.sdmlib.openbank.util;
import org.sdmlib.models.pattern.PatternObject;
import org.sdmlib.openbank.FeeValue;
import org.sdmlib.openbank.TransactionTypeEnum;
import org.sdmlib.models.pattern.AttributeConstraint;
import org.sdmlib.models.pattern.Pattern;
import java.math.BigInteger;
import org.sdmlib.openbank.util.BankPO;
import org.sdmlib.openbank.Bank;
import org.sdmlib.openbank.util.FeeValuePO;
public class FeeValuePO extends PatternObject<FeeValuePO, FeeValue>
{
public FeeValueSet allMatches()
{
this.setDoAllMatches(true);
FeeValueSet matches = new FeeValueSet();
while (this.getPattern().getHasMatch())
{
matches.add((FeeValue) this.getCurrentMatch());
this.getPattern().findMatch();
}
return matches;
}
public FeeValuePO(){
newInstance(null);
}
public FeeValuePO(FeeValue... hostGraphObject) {
if(hostGraphObject==null || hostGraphObject.length<1){
return ;
}
newInstance(null, hostGraphObject);
}
public FeeValuePO(String modifier)
{
this.setModifier(modifier);
}
public FeeValuePO createTransTypeCondition(TransactionTypeEnum value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_TRANSTYPE)
.withTgtValue(value)
.withSrc(this)
.withModifier(this.getPattern().getModifier())
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public FeeValuePO createTransTypeAssignment(TransactionTypeEnum value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_TRANSTYPE)
.withTgtValue(value)
.withSrc(this)
.withModifier(Pattern.CREATE)
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public TransactionTypeEnum getTransType()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) getCurrentMatch()).getTransType();
}
return null;
}
public FeeValuePO withTransType(TransactionTypeEnum value)
{
if (this.getPattern().getHasMatch())
{
((FeeValue) getCurrentMatch()).setTransType(value);
}
return this;
}
public FeeValuePO createPercentCondition(BigInteger value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_PERCENT)
.withTgtValue(value)
.withSrc(this)
.withModifier(this.getPattern().getModifier())
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public FeeValuePO createPercentAssignment(BigInteger value)
{
new AttributeConstraint()
.withAttrName(FeeValue.PROPERTY_PERCENT)
.withTgtValue(value)
.withSrc(this)
.withModifier(Pattern.CREATE)
.withPattern(this.getPattern());
super.filterAttr();
return this;
}
public BigInteger getPercent()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) getCurrentMatch()).getPercent();
}
return null;
}
public FeeValuePO withPercent(BigInteger value)
{
if (this.getPattern().getHasMatch())
{
((FeeValue) getCurrentMatch()).setPercent(value);
}
return this;
}
public BankPO createBankPO()
{
BankPO result = new BankPO(new Bank[]{});
result.setModifier(this.getPattern().getModifier());
super.hasLink(FeeValue.PROPERTY_BANK, result);
return result;
}
public BankPO createBankPO(String modifier)
{
BankPO result = new BankPO(new Bank[]{});
result.setModifier(modifier);
super.hasLink(FeeValue.PROPERTY_BANK, result);
return result;
}
public FeeValuePO createBankLink(BankPO tgt)
{
return hasLinkConstraint(tgt, FeeValue.PROPERTY_BANK);
}
public FeeValuePO createBankLink(BankPO tgt, String modifier)
{
return hasLinkConstraint(tgt, FeeValue.PROPERTY_BANK, modifier);
}
public Bank getBank()
{
if (this.getPattern().getHasMatch())
{
return ((FeeValue) this.getCurrentMatch()).getBank();
}
return null;
}
}
|
SWE443-TeamRed/open-bank
|
open-bank/src/main/java/org/sdmlib/openbank/util/FeeValuePO.java
|
Java
|
mit
| 4,269 |
package tw.showang.apiabstractionframework.example.api;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import tw.showang.apiabstractionframework.example.api.base.ApiTestBase;
import tw.showang.apiabstractionframework.example.api.base.ExampleApiBase.ApiErrorListener;
import tw.showang.apiabstractionframework.example.api.base.ExampleApiBase.ApiSuccessListener;
@RunWith(RobolectricTestRunner.class)
public class GitHubUserApiTest extends ApiTestBase {
@Test
public void testRequestData() {
new GitHubUserApi()
.success(new ApiSuccessListener<String>() {
@Override
public void onSuccess(String response) {
System.out.println("success");
}
})
.fail(new ApiErrorListener() {
@Override
public void onFail(int errorType, String message) {
onRequestFail(errorType, message);
}
})
.start();
}
}
|
showang/ApiAbstractionFramework
|
example/src/test/java/tw/showang/apiabstractionframework/example/api/GitHubUserApiTest.java
|
Java
|
mit
| 915 |
// https://discuss.leetcode.com/topic/71438/c-dp-solution-with-comments
// https://discuss.leetcode.com/topic/76103/0-1-knapsack-detailed-explanation
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m+1][n+1];
for(String s : strs) {
int zeros = 0, ones = 0;
for(char c : s.toCharArray()) {
if(c - '0' == 0) zeros++;
else ones++;
}
// has to go from bigger to lower to avoid count the current string multiple times.
for(int i=m; i>=zeros; i--) {
for(int j=n; j>=ones; j--) {
dp[i][j] = Math.max(dp[i][j], 1+dp[i-zeros][j-ones]);
}
} // else not able to select the current string, no change to dp[i][j].
}
return dp[m][n];
}
}
|
l33tnobody/l33t_sol
|
src/474OnesAndZeros.java
|
Java
|
mit
| 867 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.queryProcessor.decomposer.query.visitors;
import com.foundationdb.sql.StandardException;
import com.foundationdb.sql.parser.FromSubquery;
import com.foundationdb.sql.parser.SelectNode;
import com.foundationdb.sql.parser.Visitable;
import madgik.exareme.master.queryProcessor.decomposer.query.SQLQuery;
/**
* @author heraldkllapi
*/
public class SelectVisitor extends AbstractVisitor {
public SelectVisitor(SQLQuery query) {
super(query);
}
@Override
public Visitable visit(Visitable node) throws StandardException {
if (node instanceof SelectNode) {
if (((SelectNode) node).isDistinct()) {
query.setOutputColumnsDistinct(true);
}
// Result columns
ResultColumnsVisitor projectVisitor = new ResultColumnsVisitor(query);
node.accept(projectVisitor);
// Input tables
FromListVisitor fromVisitor = new FromListVisitor(query);
node.accept(fromVisitor);
// Where conditions
WhereClauseVisitor whereVisitor = new WhereClauseVisitor(query);
whereVisitor.setVisitedJoin(true);
node.accept(whereVisitor);
// Group by
GroupByListVisitor groupByVisitor = new GroupByListVisitor(query);
node.accept(groupByVisitor);
return node;
}
return node;
}
@Override
public boolean skipChildren(Visitable node) {
return FromSubquery.class.isInstance(node);
}
}
|
madgik/exareme
|
Exareme-Docker/src/exareme/exareme-master/src/main/java/madgik/exareme/master/queryProcessor/decomposer/query/visitors/SelectVisitor.java
|
Java
|
mit
| 1,601 |
package com.knr.recyclr;
import org.json.*;
public class UpcItem {
public String number;
public String itemName;
public String description;
public UpcItem(String json) {
try {
JSONObject jsonObj = new JSONObject(json);
this.number = jsonObj.getString("number");
this.itemName = jsonObj.getString("itemname");
this.description = jsonObj.getString("description");
} catch (JSONException e) {
this.number = "0";
this.itemName = "invalid item";
this.description = "invalid UPC code";
}
}
}
|
kj2wong/Recyclr
|
Recyclr/src/com/knr/recyclr/UpcItem.java
|
Java
|
mit
| 521 |
package com.real.estate.parser;
import org.jsoup.nodes.Element;
import java.util.List;
/**
* Created by Snayki on 22.03.2016.
*/
public interface Parser<T> {
List<Element> parse();
T createFromElement(Element element);
}
|
Snayki/real-estate
|
src/main/java/com/real/estate/parser/Parser.java
|
Java
|
mit
| 236 |
package com.microsoft.bingads.v12.customermanagement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Predicates" type="{https://bingads.microsoft.com/Customer/v12/Entities}ArrayOfPredicate" minOccurs="0"/>
* <element name="Ordering" type="{https://bingads.microsoft.com/Customer/v12/Entities}ArrayOfOrderBy" minOccurs="0"/>
* <element name="PageInfo" type="{https://bingads.microsoft.com/Customer/v12/Entities}Paging" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"predicates",
"ordering",
"pageInfo"
})
@XmlRootElement(name = "SearchClientLinksRequest")
public class SearchClientLinksRequest {
@XmlElement(name = "Predicates", nillable = true)
protected ArrayOfPredicate predicates;
@XmlElement(name = "Ordering", nillable = true)
protected ArrayOfOrderBy ordering;
@XmlElement(name = "PageInfo", nillable = true)
protected Paging pageInfo;
/**
* Gets the value of the predicates property.
*
* @return
* possible object is
* {@link ArrayOfPredicate }
*
*/
public ArrayOfPredicate getPredicates() {
return predicates;
}
/**
* Sets the value of the predicates property.
*
* @param value
* allowed object is
* {@link ArrayOfPredicate }
*
*/
public void setPredicates(ArrayOfPredicate value) {
this.predicates = value;
}
/**
* Gets the value of the ordering property.
*
* @return
* possible object is
* {@link ArrayOfOrderBy }
*
*/
public ArrayOfOrderBy getOrdering() {
return ordering;
}
/**
* Sets the value of the ordering property.
*
* @param value
* allowed object is
* {@link ArrayOfOrderBy }
*
*/
public void setOrdering(ArrayOfOrderBy value) {
this.ordering = value;
}
/**
* Gets the value of the pageInfo property.
*
* @return
* possible object is
* {@link Paging }
*
*/
public Paging getPageInfo() {
return pageInfo;
}
/**
* Sets the value of the pageInfo property.
*
* @param value
* allowed object is
* {@link Paging }
*
*/
public void setPageInfo(Paging value) {
this.pageInfo = value;
}
}
|
bing-ads-sdk/BingAds-Java-SDK
|
proxies/com/microsoft/bingads/v12/customermanagement/SearchClientLinksRequest.java
|
Java
|
mit
| 3,065 |
/*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.preapproval.search;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import br.com.uol.pagseguro.api.PagSeguro;
import br.com.uol.pagseguro.api.common.domain.PreApprovalStatus;
import br.com.uol.pagseguro.api.utils.XMLUnmarshallListener;
/**
* Implementation of {@code PreApprovalSummary} and {@code XMLUnmarshallListener}
*
* @author PagSeguro Internet Ltda.
*/
public class PreApprovalSummaryXML implements PreApprovalSummary, XMLUnmarshallListener {
private PagSeguro pagSeguro;
private String name;
private String code;
private Date date;
private String tracker;
private String statusId;
private String reference;
private Date lastEvent;
private String charge;
PreApprovalSummaryXML() {
}
@Override
public void onUnmarshal(PagSeguro pagseguro, String rawData) {
this.pagSeguro = pagseguro;
}
@Override
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
@Override
public String getCode() {
return code;
}
@XmlElement
public void setCode(String code) {
this.code = code;
}
@Override
public Date getDate() {
return date;
}
@XmlElement
public void setDate(Date date) {
this.date = date;
}
@Override
public String getTracker() {
return tracker;
}
@XmlElement
public void setTracker(String tracker) {
this.tracker = tracker;
}
@Override
public PreApprovalStatus getStatus() {
return new PreApprovalStatus(getStatusId());
}
public String getStatusId() {
return statusId;
}
@XmlElement(name = "status")
public void setStatusId(String statusId) {
this.statusId = statusId;
}
@Override
public String getReference() {
return reference;
}
@XmlElement
public void setReference(String reference) {
this.reference = reference;
}
@Override
public Date getLastEvent() {
return lastEvent;
}
@XmlElement(name = "lastEventDate")
public void setLastEvent(Date lastEvent) {
this.lastEvent = lastEvent;
}
@Override
public String getCharge() {
return charge;
}
@XmlElement
public void setCharge(String charge) {
this.charge = charge;
}
@Override
public PreApprovalDetail getDetail() {
return pagSeguro.preApprovals().search().byCode(getCode());
}
@Override
public String toString() {
return "PreApprovalSummaryXML{" +
"pagSeguro=" + pagSeguro +
", name='" + name + '\'' +
", code='" + code + '\'' +
", date=" + date +
", tracker='" + tracker + '\'' +
", statusId='" + statusId + '\'' +
", reference='" + reference + '\'' +
", lastEvent=" + lastEvent +
", charge='" + charge + '\'' +
'}';
}
}
|
girinoboy/lojacasamento
|
pagseguro-api/src/main/java/br/com/uol/pagseguro/api/preapproval/search/PreApprovalSummaryXML.java
|
Java
|
mit
| 3,550 |
/**
* Michael' (The non-Asian one's) librarys.<br>
* Thank you for the help!
* @author Michael [???]
*
*/
package com.shadow53.libs;
|
Vectis99/sshs-2016-willamette
|
src/com/shadow53/libs/package-info.java
|
Java
|
mit
| 137 |
package ua.com.fielden.platform.entity_centre.review;
import java.util.Date;
import ua.com.fielden.platform.domaintree.testing.EntityWithStringKeyType;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.CompositeKeyMember;
import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.annotation.KeyTitle;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.Observable;
/**
* Entity for "domain tree representation" testing.
*
* @author TG Team
*
*/
@KeyTitle(value = "Key title", desc = "Key desc")
@KeyType(DynamicEntityKey.class)
public class EvenSlaverDomainEntity extends AbstractEntity<DynamicEntityKey> {
private static final long serialVersionUID = 1L;
protected EvenSlaverDomainEntity() {
}
////////// Range types //////////
@IsProperty
@CompositeKeyMember(1)
private Integer integerProp = null;
@IsProperty
@CompositeKeyMember(2)
private Double doubleProp = 0.0;
@IsProperty
private Date dateProp;
////////// A property of entity type //////////
@IsProperty
private EntityWithStringKeyType simpleEntityProp;
public Integer getIntegerProp() {
return integerProp;
}
@Observable
public void setIntegerProp(final Integer integerProp) {
this.integerProp = integerProp;
}
public Double getDoubleProp() {
return doubleProp;
}
@Observable
public void setDoubleProp(final Double doubleProp) {
this.doubleProp = doubleProp;
}
public Date getDateProp() {
return dateProp;
}
@Observable
public void setDateProp(final Date dateProp) {
this.dateProp = dateProp;
}
public EntityWithStringKeyType getSimpleEntityProp() {
return simpleEntityProp;
}
@Observable
public void setSimpleEntityProp(final EntityWithStringKeyType simpleEntityProp) {
this.simpleEntityProp = simpleEntityProp;
}
}
|
fieldenms/tg
|
platform-pojo-bl/src/test/java/ua/com/fielden/platform/entity_centre/review/EvenSlaverDomainEntity.java
|
Java
|
mit
| 2,107 |
package com.nepfix.sim.elements;
import com.nepfix.sim.core.Processor;
import java.util.Map;
public class UnitProcessor implements Processor {
private String id;
@Override public void init(String id, Map<String, String> args) {
this.id = id;
}
@Override public String process(String input) {
return input;
}
@Override public String getId() {
return id;
}
}
|
pabloogc/Nepfix
|
sim/src/main/java/com/nepfix/sim/elements/UnitProcessor.java
|
Java
|
mit
| 416 |
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.blocks.storage.item;
import net.minecraft.block.BlockState;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.ToolItem;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.api.blockentity.IMachineGuiHandler;
import reborncore.common.blocks.BlockMachineBase;
import reborncore.common.util.RebornInventory;
import reborncore.common.util.WorldUtils;
import techreborn.blockentity.storage.item.StorageUnitBaseBlockEntity;
import techreborn.blockentity.GuiType;
import techreborn.init.TRContent;
public class StorageUnitBlock extends BlockMachineBase {
public final TRContent.StorageUnit unitType;
public StorageUnitBlock(TRContent.StorageUnit unitType) {
super((Settings.of(unitType.name.equals("crude") ? Material.WOOD : Material.METAL).strength(2.0F, 2.0F)));
this.unitType = unitType;
}
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return new StorageUnitBaseBlockEntity(pos, state, unitType);
}
@Override
public ActionResult onUse(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockHitResult hitResult) {
if (unitType == TRContent.StorageUnit.CREATIVE || worldIn.isClient) {
return super.onUse(state, worldIn, pos, playerIn, hand, hitResult);
}
final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) worldIn.getBlockEntity(pos);
ItemStack stackInHand = playerIn.getStackInHand(Hand.MAIN_HAND);
Item itemInHand = stackInHand.getItem();
if (storageEntity != null && itemInHand != Items.AIR && (storageEntity.isSameType(stackInHand) && !storageEntity.isFull() ||
(!storageEntity.isLocked() && storageEntity.isEmpty() && (!(itemInHand instanceof ToolItem))))) {
// Add item which is the same type (in users inventory) into storage
for (int i = 0; i < playerIn.getInventory().size() && !storageEntity.isFull(); i++) {
ItemStack curStack = playerIn.getInventory().getStack(i);
if (curStack.getItem() == itemInHand) {
playerIn.getInventory().setStack(i, storageEntity.processInput(curStack));
}
}
return ActionResult.SUCCESS;
}
return super.onUse(state, worldIn, pos, playerIn, hand, hitResult);
}
@Override
public void onBlockBreakStart(BlockState state, World world, BlockPos pos, PlayerEntity player) {
super.onBlockBreakStart(state, world, pos, player);
if (world.isClient) return;
final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) world.getBlockEntity(pos);
ItemStack stackInHand = player.getStackInHand(Hand.MAIN_HAND);
if (storageEntity != null && (stackInHand.isEmpty() || storageEntity.isSameType(stackInHand)) && !storageEntity.isEmpty()) {
RebornInventory<StorageUnitBaseBlockEntity> inventory = storageEntity.getInventory();
ItemStack out = inventory.getStack(StorageUnitBaseBlockEntity.OUTPUT_SLOT);
// Drop stack if sneaking
if (player.isSneaking()) {
WorldUtils.dropItem(new ItemStack(out.getItem()), world, player.getBlockPos());
out.decrement(1);
} else {
WorldUtils.dropItem(out, world, player.getBlockPos());
out.setCount(0);
}
inventory.setHashChanged();
}
}
@Override
public IMachineGuiHandler getGui() {
return GuiType.STORAGE_UNIT;
}
}
|
TechReborn/TechReborn
|
src/main/java/techreborn/blocks/storage/item/StorageUnitBlock.java
|
Java
|
mit
| 4,798 |
// Copyright © 2017 Viro Media. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.viromedia.bridge.component.node;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ThemedReactContext;
/**
* SceneManager for building a {@link VRTScene}
* corresponding to the ViroScene.js control.
*/
public class VRTSceneManagerImpl extends VRTSceneManager<VRTScene> {
public VRTSceneManagerImpl(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "VRTScene";
}
@Override
protected VRTScene createViewInstance(ThemedReactContext reactContext) {
return new VRTScene(reactContext);
}
}
|
viromedia/viro
|
android/viro_bridge/src/main/java/com/viromedia/bridge/component/node/VRTSceneManagerImpl.java
|
Java
|
mit
| 1,801 |
package za.co.cporm.model.loader.support;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.CursorLoader;
import za.co.cporm.model.generate.TableDetails;
import za.co.cporm.model.query.Select;
import za.co.cporm.model.util.CPOrmCursor;
import za.co.cporm.model.util.ContentResolverValues;
/**
* Created by hennie.brink on 2015-03-31.
*/
public class CPOrmLoader<Model> extends CursorLoader {
private TableDetails tableDetails;
private int cacheSize = 0;
/**
* Creates a new cursor loader using the select statement provided. The default implementation
* will enable the cache of the cursor to improve view performance. To manually specify the
* cursor cache size, use the overloaded constructor.
* @param context The context that will be used to create the cursor.
* @param select The select statement that will be used to retrieve the data.
*/
public CPOrmLoader(Context context, Select<Model> select) {
super(context);
ContentResolverValues resolverValues = select.asContentResolverValue(context);
setUri(resolverValues.getItemUri());
setProjection(resolverValues.getProjection());
setSelection(resolverValues.getWhere());
setSelectionArgs(resolverValues.getWhereArgs());
setSortOrder(resolverValues.getSortOrder());
tableDetails = resolverValues.getTableDetails();
}
/**
* Creates a new cursor loader using the select statement provided. You
* can specify the cache size to use, or use -1 to disable cursor caching.
* @param context The context that will be used to create the cursor.
* @param select The select statement that will be used to retrieve the data.
* @param cacheSize The cache size for the cursor, or -1 to disable caching
*/
public CPOrmLoader(Context context, Select<Model> select, int cacheSize) {
this(context, select);
enableCursorCache(cacheSize);
}
public void enableCursorCache(int size) {
cacheSize = size;
}
@Override
public CPOrmCursor<Model> loadInBackground() {
Cursor asyncCursor = super.loadInBackground();
if(asyncCursor == null)
return null;
CPOrmCursor<Model> cursor = new CPOrmCursor<>(tableDetails, asyncCursor);
if(cacheSize == 0){
cursor.enableCache();
} else if(cacheSize > 0) {
cursor.enableCache(cacheSize);
}
//Prefetch at least some items in preparation for the list
int count = cursor.getCount();
for (int i = 0; i < count && cursor.isCacheEnabled() && i < 100; i++) {
cursor.moveToPosition(i);
Model inflate = cursor.inflate();
}
return cursor;
}
}
|
Wackymax/CPOrm
|
CPOrm/src/main/java/za/co/cporm/model/loader/support/CPOrmLoader.java
|
Java
|
mit
| 2,810 |
/*
* The MIT License
*
* Copyright 2015 Ryan Gilera.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.daytron.twaattin.presenter;
import com.github.daytron.twaattin.ui.LoginScreen;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.Position;
import com.vaadin.ui.Button;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import java.security.Principal;
/**
*
* @author Ryan Gilera
*/
public class LogoutBehaviour implements Button.ClickListener {
private final static long serialVersionUID = 1L;
@Override
public void buttonClick(Button.ClickEvent event) {
VaadinSession.getCurrent().setAttribute(Principal.class, null);
UI.getCurrent().setContent(new LoginScreen());
Notification logoutNotification = new Notification(
"You've been logout", Notification.Type.TRAY_NOTIFICATION);
logoutNotification.setPosition(Position.TOP_CENTER);
logoutNotification.show(Page.getCurrent());
}
}
|
Daytron/Twaattin
|
src/main/java/com/github/daytron/twaattin/presenter/LogoutBehaviour.java
|
Java
|
mit
| 2,099 |
package org.railwaystations.api.resources;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils;
import org.railwaystations.api.PhotoImporter;
import org.railwaystations.api.StationsRepository;
import org.railwaystations.api.model.Station;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Path("/")
public class SlackCommandResource {
private static final Pattern PATTERN_SEARCH = Pattern.compile("\\s*search\\s*(.*)");
private static final Pattern PATTERN_SHOW = Pattern.compile("\\s*show\\s\\s*([a-z]{1,3})\\s\\s*(\\w*)");
private static final Pattern PATTERN_SHOW_LEGACY = Pattern.compile("\\s*show\\s\\s*(\\d*)");
private final StationsRepository repository;
private final String verificationToken;
private final PhotoImporter photoImporter;
public SlackCommandResource(final StationsRepository repository, final String verificationToken, final PhotoImporter photoImporter) {
this.repository = repository;
this.verificationToken = verificationToken;
this.photoImporter = photoImporter;
}
@POST
@Path("slack")
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public SlackResponse command(@FormParam("token") final String token,
@FormParam("text") final String text,
@FormParam("response_url") final String responseUrl) {
if (!StringUtils.equals(verificationToken, token)) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
if (StringUtils.equals("import", text)) {
photoImporter.importPhotosAsync();
return new SlackResponse(ResponseType.in_channel, "Importing photos");
}
final Matcher matcherSearch = PATTERN_SEARCH.matcher(text);
if (matcherSearch.matches()) {
final Map<Station.Key, String> stations = repository.findByName(matcherSearch.group(1));
if (!stations.isEmpty()){
return new SlackResponse(ResponseType.in_channel, toMessage(stations));
}
return new SlackResponse(ResponseType.in_channel, "No stations found");
}
final Matcher matcherShow = PATTERN_SHOW.matcher(text);
if (matcherShow.matches()) {
return showStation(matcherShow.group(1).toLowerCase(Locale.ENGLISH), matcherShow.group(2));
}
final Matcher matcherShowLegacy = PATTERN_SHOW_LEGACY.matcher(text);
if (matcherShowLegacy.matches()) {
return showStation(null, matcherShowLegacy.group(1));
}
return new SlackResponse(ResponseType.ephimeral, String.format("I understand:%n- '/rsapi search <station-name>'%n- '/rsapi show <country-code> <station-id>%n- '/rsapi import'%n"));
}
private SlackResponse showStation(final String country, final String id) {
final Station.Key key = new Station.Key(country, id);
final Station station = repository.findByKey(key);
if (station == null) {
return new SlackResponse(ResponseType.in_channel, "Station with " + key + " not found");
} else {
return new SlackResponse(ResponseType.in_channel, toMessage(station));
}
}
private String toMessage(final Map<Station.Key, String> stations) {
final StringBuilder sb = new StringBuilder(String.format("Found:%n"));
stations.keySet().forEach(station -> sb.append(String.format("- %s: %s%n", stations.get(station), station)));
return sb.toString();
}
private String toMessage(final Station station) {
return String.format("Station: %s - %s%nCountry: %s%nLocation: %f,%f%nPhotographer: %s%nLicense: %s%nPhoto: %s%n", station.getKey().getId(), station.getTitle(), station.getKey().getCountry(), station.getCoordinates().getLat(), station.getCoordinates().getLon(), station.getPhotographer(), station.getLicense(), station.getPhotoUrl());
}
public enum ResponseType {
ephimeral,
in_channel
}
/**
* <div>
* {
* “response_type”: “ephemeral”,
* “text”: “How to use /please”,
* “attachments”:[
* {
* “text”:”To be fed, use `/please feed` to request food. We hear the elf needs food badly.\nTo tease, use `/please tease` — we always knew you liked noogies.\nYou’ve already learned how to getStationsByCountry help with `/please help`.”
* }
* ]
* }
* </div>
*/
private static class SlackResponse {
@JsonProperty("response_type")
private final ResponseType responseType;
@JsonProperty("text")
private final String text;
private SlackResponse(final ResponseType responseType, final String text) {
this.responseType = responseType;
this.text = text;
}
public String getText() {
return text;
}
public ResponseType getResponseType() {
return responseType;
}
}
}
|
pstorch/bahnhoefe.gpx
|
src/main/java/org/railwaystations/api/resources/SlackCommandResource.java
|
Java
|
mit
| 5,251 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2010-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package co.mewf.minirs.rs;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the annotated method responds to HTTP GET requests.
*
* @author Paul Sandoz
* @author Marc Hadley
* @see HttpMethod
* @since 1.0
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(HttpMethod.GET)
@Documented
public @interface GET {
}
|
mewf/minirs-core
|
src/main/java/co/mewf/minirs/rs/GET.java
|
Java
|
mit
| 2,502 |
/* ====================================================================
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.poi.openxml4j.exceptions;
/**
* Global exception throws when a critical error occurs (this exception is
* set as Runtime in order not to force the user to manage the exception in a
* try/catch).
*
* @author Julien Chable
* @version 1.0
*/
@SuppressWarnings("serial")
public class OpenXML4JRuntimeException extends RuntimeException {
public OpenXML4JRuntimeException(String msg) {
super(msg);
}
}
|
tobyclemson/msci-project
|
vendor/poi-3.6/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java
|
Java
|
mit
| 1,364 |
package de.danoeh.antennapod.core;
import android.content.Context;
import de.danoeh.antennapod.core.cast.CastManager;
import de.danoeh.antennapod.core.preferences.PlaybackPreferences;
import de.danoeh.antennapod.core.preferences.SleepTimerPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.storage.PodDBAdapter;
import de.danoeh.antennapod.core.util.NetworkUtils;
/**
* Stores callbacks for core classes like Services, DB classes etc. and other configuration variables.
* Apps using the core module of AntennaPod should register implementations of all interfaces here.
*/
public class ClientConfig {
private ClientConfig(){}
/**
* Should be used when setting User-Agent header for HTTP-requests.
*/
public static String USER_AGENT;
public static ApplicationCallbacks applicationCallbacks;
public static DownloadServiceCallbacks downloadServiceCallbacks;
public static PlaybackServiceCallbacks playbackServiceCallbacks;
public static GpodnetCallbacks gpodnetCallbacks;
public static FlattrCallbacks flattrCallbacks;
public static DBTasksCallbacks dbTasksCallbacks;
public static CastCallbacks castCallbacks;
private static boolean initialized = false;
public static synchronized void initialize(Context context) {
if(initialized) {
return;
}
PodDBAdapter.init(context);
UserPreferences.init(context);
UpdateManager.init(context);
PlaybackPreferences.init(context);
NetworkUtils.init(context);
CastManager.init(context);
SleepTimerPreferences.init(context);
initialized = true;
}
}
|
mfietz/AntennaPod
|
core/src/play/java/de/danoeh/antennapod/core/ClientConfig.java
|
Java
|
mit
| 1,708 |
package construtores;
public class ConstrutorTesteDrive {
public static void main(String[] args) {
// Construtor c1 = new Construtor();
// System.out.println("--c1\n" + c1.getNomeERg() + "\n\n");
Construtor c2 = new Construtor("Odair");
System.out.println("--c2\n" + c2.getNomeERg() + "\n\n");
Construtor c3 = new Construtor("Odair", "123456");
System.out.println("--c3\n" + c3.getNomeERg() + "\n\n");
}
}
|
wesleyegberto/study-ocjp
|
src/construtores/ConstrutorTesteDrive.java
|
Java
|
mit
| 449 |
package com.veaer.glass.viewpager;
import android.support.v4.view.ViewPager;
import com.veaer.glass.trigger.Trigger;
/**
* Created by Veaer on 15/11/18.
*/
public class PagerTrigger extends Trigger implements ViewPager.OnPageChangeListener {
private ColorProvider colorProvider;
private int startPosition, endPosition, maxLimit;
public static Trigger addTrigger(ViewPager viewPager, ColorProvider colorProvider) {
PagerTrigger viewPagerTrigger = new PagerTrigger(colorProvider);
viewPager.addOnPageChangeListener(viewPagerTrigger);
viewPagerTrigger.onPageSelected(0);
return viewPagerTrigger;
}
PagerTrigger(ColorProvider colorProvider) {
this.colorProvider = colorProvider;
maxLimit = colorProvider.getCount() - 1;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (isScrollingRight(position)) {
startPosition = position;
endPosition = Math.min(maxLimit, position + 1);
} else {
startPosition = Math.min(maxLimit, position + 1);
endPosition = position;
}
initColorGenerator();
setColor(ColorGenerator.getColor(position, positionOffset));
}
@Override
public void onPageScrollStateChanged(int state) {
//do nothing
}
@Override
public void onPageSelected(int position) {
endPosition = position;
startPosition = position;
initColorGenerator();
}
private boolean isScrollingRight(int position) {
return position == startPosition;
}
private void initColorGenerator() {
ColorGenerator.init(startPosition, endPosition, colorProvider);
}
}
|
Veaer/Glass
|
glass/src/main/java/com/veaer/glass/viewpager/PagerTrigger.java
|
Java
|
mit
| 1,762 |
/* 125.valid_palindrome
*/
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
int ni = nums[i];
for (int j = i + 1; j < nums.length; j++) {
int nj = nums[j];
if (ni + nj == target) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
|
aenon/OnlineJudge
|
leetcode/1.Array_String/125.valid_palindrome.java
|
Java
|
mit
| 423 |
package in.iamkelv.balances.alarms;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import in.iamkelv.balances.R;
import in.iamkelv.balances.activities.MainActivity;
import in.iamkelv.balances.models.Balances;
import in.iamkelv.balances.models.BalancesDeserializer;
import in.iamkelv.balances.models.PreferencesModel;
import in.iamkelv.balances.models.WisePayService;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
public class SchedulingService extends IntentService {
private final String ENDPOINT = "https://balances.iamkelv.in";
private PreferencesModel mPreferences;
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
NotificationCompat.Builder builder;
public SchedulingService() {
super("SchedulingService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("Balances", "Starting notification check");
mPreferences = new PreferencesModel(this);
if (isNetworkAvailable()) {
checkBalances();
} else {
Log.e("Balances", "Network Unavailable");
}
Log.i("Balances", "Notification check complete");
AlarmReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String title, String message) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void checkBalances() {
// Assign variables
String mUsername = mPreferences.getUsername();
String mPassword = mPreferences.getPassword();
// Set type adapter
Gson gson = new GsonBuilder()
.registerTypeAdapter(Balances.class, new BalancesDeserializer())
.create();
// Send balance request
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setConverter(new GsonConverter(gson))
.build();
WisePayService service = restAdapter.create(WisePayService.class);
Callback<Balances> callback = new Callback<Balances>() {
@Override
public void success(Balances balances, Response response) {
// Get balances
Double lunch = balances.lunch;
Double tuck = balances.tuck;
int lunchBalance = lunch.intValue();
int tuckBalance= tuck.intValue();
lunch /= 100;
tuck /= 100;
String strLunch = String.format("%.2f",lunch);
String strTuck = String.format("%.2f",tuck);
// Update preferences
mPreferences.setLunchBalance(strLunch);
mPreferences.setTuckBalance(strTuck);
mPreferences.setLastChecked(System.currentTimeMillis());
int lunchThreshold = mPreferences.getLunchThreshold() * 100;
int tuckThreshold = mPreferences.getTuckThreshold() * 100;
if (lunchBalance < lunchThreshold && tuckBalance < tuckThreshold) {
sendNotification("Balances Alert", "Your lunch and tuck balances are low");
} else if (lunchBalance < lunchThreshold) {
sendNotification("Balances Alert", "Your lunch balance is low");
} else if (tuckBalance < tuckThreshold) {
sendNotification("Balances Alert", "Your tuck balance is low");
}
}
@Override
public void failure(RetrofitError retrofitError) {
Log.e("BALANCES", "Failed callback");
// Check for authentication error
if (retrofitError.getResponse().getStatus() == 401) {
mPreferences.setAuthState(false);
sendNotification("Balances - Error", "Your WisePay login details are incorrect. Tap here to fix.");
} else {
JsonObject jsonResponse = (JsonObject) retrofitError.getBodyAs(JsonObject.class);
try {
sendNotification("Balances - Error", jsonResponse.get("message").getAsString());
} catch (NullPointerException e) {
sendNotification("Balances - Error", "An unknown error occurred while checking your balances.");
}
}
}
};
service.checkBalances(mUsername, mPassword, callback);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
}
|
kz/balances-android
|
app/src/main/java/in/iamkelv/balances/alarms/SchedulingService.java
|
Java
|
mit
| 5,935 |
package com.thecodeinside.easyfactory.core;
/**
* A factory's attribute.
*
* @author Wellington Pinheiro <wellington.pinheiro@gmail.com>
*
* @param <T> type of the attribute
*/
public class Attribute<T> {
private String id;
private T value;
public String getId() {
return this.id;
}
public T getValue() {
return this.value;
}
public Attribute() {
}
public Attribute(String id, T value) {
this.id = id;
this.value = value;
}
@Override
public String toString() {
return "Attribute [id=" + id + ", value=" + value + "]";
}
public boolean isReference() {
return value instanceof FactoryReference;
}
public boolean isNotReference() {
return !isReference();
}
}
|
wrpinheiro/easy-factory
|
core/src/main/java/com/thecodeinside/easyfactory/core/Attribute.java
|
Java
|
mit
| 795 |
package com.syntacticsugar.vooga.gameplayer.objects.items.bullets;
import com.syntacticsugar.vooga.gameplayer.event.implementations.SlowEvent;
import com.syntacticsugar.vooga.gameplayer.objects.GameObjectType;
public class SlowBullet extends AbstractBullet {
public SlowBullet(BulletParams params, double speedDecrease, int time) {
super(params);
SlowEvent slow = new SlowEvent(speedDecrease, time);
addCollisionBinding(GameObjectType.ENEMY, slow);
}
}
|
nbv3/voogasalad_CS308
|
src/com/syntacticsugar/vooga/gameplayer/objects/items/bullets/SlowBullet.java
|
Java
|
mit
| 465 |
package com.tommytony.war.job;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import com.tommytony.war.War;
import com.tommytony.war.volume.BlockInfo;
public class ResetCursorJob implements Runnable {
private final Block cornerBlock;
private final BlockInfo[] originalCursorBlocks;
private final boolean isSoutheast;
public ResetCursorJob(Block cornerBlock, BlockInfo[] originalCursorBlocks, boolean isSoutheast) {
this.cornerBlock = cornerBlock;
this.originalCursorBlocks = originalCursorBlocks;
this.isSoutheast = isSoutheast;
}
public void run() {
if (this.isSoutheast) {
this.cornerBlock.setType(this.originalCursorBlocks[0].getType());
this.cornerBlock.setData(this.originalCursorBlocks[0].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setType(this.originalCursorBlocks[1].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setData(this.originalCursorBlocks[1].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setType(this.originalCursorBlocks[2].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setData(this.originalCursorBlocks[2].getData());
} else {
this.cornerBlock.setType(this.originalCursorBlocks[0].getType());
this.cornerBlock.setData(this.originalCursorBlocks[0].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setType(this.originalCursorBlocks[1].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setData(this.originalCursorBlocks[1].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setType(this.originalCursorBlocks[2].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setData(this.originalCursorBlocks[2].getData());
}
}
}
|
grinning/war-tommybranch
|
war/src/main/java/com/tommytony/war/job/ResetCursorJob.java
|
Java
|
mit
| 2,006 |
package org.beryl.app;
/** Convenience class for retrieving the current Android version that's running on the device.
*
* Code example on how to use AndroidVersion to load a multi-versioned class at runtime for backwards compatibility without using reflection.
* <pre class="code"><code class="java">
import org.beryl.app.AndroidVersion;
public class StrictModeEnabler {
public static void enableOnThread() {
IStrictModeEnabler enabler = getStrictModeEnabler();
}
// Strict Mode is only supported on Gingerbread or higher.
private static IStrictModeEnabler getStrictModeEnabler() {
if(AndroidVersion.isGingerbreadOrHigher()) {
return new GingerbreadAndAboveStrictModeEnabler();
} else {
return new NoStrictModeEnabler();
}
}
}
</code></pre>*/
@SuppressWarnings("deprecation")
public class AndroidVersion {
private static final int _ANDROID_SDK_VERSION;
private static final int ANDROID_SDK_VERSION_PREVIEW = Integer.MAX_VALUE;
static {
int android_sdk = 3; // 3 is Android 1.5 (Cupcake) which is the earliest Android SDK available.
try {
android_sdk = Integer.parseInt(android.os.Build.VERSION.SDK);
}
catch (Exception e) {
android_sdk = ANDROID_SDK_VERSION_PREVIEW;
}
finally {}
_ANDROID_SDK_VERSION = android_sdk;
}
/** Returns true if running on development or preview version of Android. */
public static boolean isPreviewVersion() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
}
/** Gets the SDK Level available to the device. */
public static int getSdkVersion() {
return _ANDROID_SDK_VERSION;
}
/** Returns true if running on Android 1.5 or higher. */
public static boolean isCupcakeOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUPCAKE;
}
/** Returns true if running on Android 1.6 or higher. */
public static boolean isDonutOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.DONUT;
}
/** Returns true if running on Android 2.0 or higher. */
public static boolean isEclairOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR;
}
/** Returns true if running on Android 2.1-update1 or higher. */
public static boolean isEclairMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1;
}
/** Returns true if running on Android 2.2 or higher. */
public static boolean isFroyoOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.FROYO;
}
/** Returns true if running on Android 2.3 or higher. */
public static boolean isGingerbreadOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD;
}
/** Returns true if running on Android 2.3.3 or higher. */
public static boolean isGingerbreadMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
}
/** Returns true if running on Android 3.0 or higher. */
public static boolean isHoneycombOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB;
}
/** Returns true if running on Android 3.1 or higher. */
public static boolean isHoneycombMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
}
/** Returns true if running on Android 3.2 or higher. */
public static boolean isHoneycombMr2OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
}
/** Returns true if running on Android 4.0 or higher. */
public static boolean isIceCreamSandwichOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/** Returns true if running on Android 4.0.3 or higher. */
public static boolean isIceCreamSandwichMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
}
/** Returns true if running on an earlier version than Android 4.0.3. */
public static boolean isBeforeIceCreamSandwichMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
}
/** Returns true if running on an earlier version than Android 4.0. */
public static boolean isBeforeIceCreamSandwich() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/** Returns true if running on an earlier version than Android 3.2. */
public static boolean isBeforeHoneycombMr2() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
}
/** Returns true if running on an earlier version than Android 3.1. */
public static boolean isBeforeHoneycombMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
}
/** Returns true if running on an earlier version than Android 3.0. */
public static boolean isBeforeHoneycomb() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB;
}
/** Returns true if running on an earlier version than Android 2.3.3. */
public static boolean isBeforeGingerbreadMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
}
/** Returns true if running on an earlier version than Android 2.3. */
public static boolean isBeforeGingerbread() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD;
}
/** Returns true if running on an earlier version than Android 2.2. */
public static boolean isBeforeFroyo() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.FROYO;
}
/** Returns true if running on an earlier version than Android 2.1-update. */
public static boolean isBeforeEclairMr1() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1;
}
/** Returns true if running on an earlier version than Android 2.0. */
public static boolean isBeforeEclair() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ECLAIR;
}
/** Returns true if running on an earlier version than Android 1.6. */
public static boolean isBeforeDonut() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.DONUT;
}
/** Returns true if running on an earlier version than Android 1.5. */
public static boolean isBeforeCupcake() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.CUPCAKE;
}
private AndroidVersion() {
// Prevent users from instantiating this class.
}
}
|
jeremyje/android-beryl
|
beryl/src/org/beryl/app/AndroidVersion.java
|
Java
|
mit
| 6,414 |
package bence.prognyelvek.contexts;
import java.util.List;
/**
* @param <T> Input token type.
* @param <O> Output token type.
*/
public interface ContextFactory<T, O> {
Context<T, O> getInstance(List<T> tokens);
}
|
zporky/langs-and-paradigms
|
projects/EJULOK/Java/prognyelvek/src/main/java/bence/prognyelvek/contexts/ContextFactory.java
|
Java
|
mit
| 224 |
package sk.atris.netxms.confrepo.tests.service.database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sk.atris.netxms.confrepo.exceptions.DatabaseException;
import sk.atris.netxms.confrepo.service.database.DbConnectionManager;
import sk.atris.netxms.confrepo.service.database.DbObjectHandler;
import sk.atris.netxms.confrepo.tests.MockedDatabase;
public class DatabaseTest {
@Before
public void environmentSetup() throws Exception {
MockedDatabase.setup();
}
@After
public void environmentCleanup() throws Exception {
MockedDatabase.cleanup();
}
@Test
public void testDatabase() throws DatabaseException {
Revision object = new Revision("test", "test", 1);
// make sure database works
DbObjectHandler.getInstance().saveToDb(object);
DbObjectHandler.getInstance().removeFromDb(object);
// test shutdown
DbConnectionManager.getInstance().shutdown();
}
}
|
tomaskir/netxms-config-repository
|
src/test/java/sk/atris/netxms/confrepo/tests/service/database/DatabaseTest.java
|
Java
|
mit
| 992 |
package de.lathspell.test.service;
import lombok.extern.slf4j.Slf4j;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import de.lathspell.test.config.AopConfiguration;
import de.lathspell.test.service.BarService;
import de.lathspell.test.service.DebugService;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AopConfiguration.class)
@Slf4j
public class BarTest {
@Autowired
private BarService barService;
@Autowired
private DebugService logService;
@Before
public void before() {
logService.setLog("");
}
@Test
public void testAfterReturning() {
String result = barService.hello("Tim");
assertThat(result, is("Hello Tim"));
assertThat(logService.getLog(), is("afterHello()-afterReturningFromHello([Tim]) => Hello Tim"));
}
@Test
public void testAfterThrowing() {
try {
barService.hello(null);
} catch (Exception e) {
// ignore
}
assertThat(logService.getLog(), is("afterHello()-afterThrowingFromHello([null]) @" + barService.toString() + " => No name!"));
}
}
|
lathspell/java_test
|
java_test_spring_aop/src/test/java/de/lathspell/test/service/BarTest.java
|
Java
|
cc0-1.0
| 1,425 |
package com.sp.jb.service;
import com.sp.jb.model.Circle;
import com.sp.jb.model.Triangle;
public class ShapeService {
private Circle circle;
private Triangle triangle;
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
}
|
samirprakash/spring-aop
|
src/com/sp/jb/service/ShapeService.java
|
Java
|
cc0-1.0
| 482 |
/*
* This file is part of memoization.java. It is subject to the license terms in the LICENSE file found in the top-level
* directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of memoization.java,
* including this file, may be copied, modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
package de.xn__ho_hia.memoization.map;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.ConcurrentMap;
import java.util.function.DoubleBinaryOperator;
import de.xn__ho_hia.memoization.shared.DoubleBinaryFunction;
import de.xn__ho_hia.quality.suppression.CompilerWarnings;
final class ConcurrentMapBasedDoubleBinaryOperatorMemoizer<KEY>
extends ConcurrentMapBasedMemoizer<KEY, Double>
implements DoubleBinaryOperator {
private final DoubleBinaryFunction<KEY> keyFunction;
private final DoubleBinaryOperator operator;
@SuppressWarnings(CompilerWarnings.NLS)
public ConcurrentMapBasedDoubleBinaryOperatorMemoizer(
final ConcurrentMap<KEY, Double> cache,
final DoubleBinaryFunction<KEY> keyFunction,
final DoubleBinaryOperator operator) {
super(cache);
this.keyFunction = requireNonNull(keyFunction,
"Provide a key function, might just be 'MemoizationDefaults.doubleBinaryOperatorHashCodeKeyFunction()'.");
this.operator = requireNonNull(operator,
"Cannot memoize a NULL DoubleBinaryOperator - provide an actual DoubleBinaryOperator to fix this.");
}
@Override
public double applyAsDouble(final double left, final double right) {
final KEY key = keyFunction.apply(left, right);
return computeIfAbsent(key, givenKey -> Double.valueOf(operator.applyAsDouble(left, right)))
.doubleValue();
}
}
|
sebhoss/memoization.java
|
memoization-core/src/main/java/de/xn__ho_hia/memoization/map/ConcurrentMapBasedDoubleBinaryOperatorMemoizer.java
|
Java
|
cc0-1.0
| 1,887 |
package patterns.behavioral.command;
// General interface for all the commands
public abstract class Command {
public abstract void execute();
}
|
SigmaOne/DesignPatterns
|
src/main/java/patterns/behavioral/command/Command.java
|
Java
|
cc0-1.0
| 150 |
package org.cqframework.cql.tools.parsetree;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.cqframework.cql.gen.cqlLexer;
import org.cqframework.cql.gen.cqlParser;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A simple wrapper around the ANTLR4 testrig.
*/
public class Main {
public static void main(String[] args) throws IOException {
String inputFile = null;
if (args.length > 0) {
inputFile = args[0];
}
InputStream is = System.in;
if (inputFile != null) {
is = new FileInputStream(inputFile);
}
ANTLRInputStream input = new ANTLRInputStream(is);
cqlLexer lexer = new cqlLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
cqlParser parser = new cqlParser(tokens);
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.library();
tree.inspect(parser);
}
}
|
MeasureAuthoringTool/clinical_quality_language
|
Src/java/tools/cql-parsetree/src/main/java/org/cqframework/cql/tools/parsetree/Main.java
|
Java
|
cc0-1.0
| 1,105 |
/*
* (C) Copyright 2015 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.cq.tools.actool.validators;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.security.util.CqActions;
public class Validators {
private static final Logger LOG = LoggerFactory.getLogger(Validators.class);
public static boolean isValidNodePath(final String path) {
if (StringUtils.isBlank(path)) {
return true; // repository level permissions are created with 'left-out' path property
}
if (!path.startsWith("/")) {
return false;
}
return true;
}
/**
* Validates in the same way as <a href="https://github.com/apache/jackrabbit-oak/blob/7999b5cbce87295b502ea4d1622e729f5b96701d/oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserManagerImpl.java#L421">Oak's UserManagerImpl</a>.
* @param id the authorizable id to validate
* @return {@code true} in case the given id is a valid authorizable id, otherwise {@code false}
*/
public static boolean isValidAuthorizableId(final String id) {
if (StringUtils.isBlank(id)) {
return false;
}
return true;
}
public static boolean isValidRegex(String expression) {
if (StringUtils.isBlank(expression)) {
return true;
}
boolean isValid = true;
if (expression.startsWith("*")) {
expression = expression.replaceFirst("\\*", "\\\\*");
}
try {
Pattern.compile(expression);
} catch (PatternSyntaxException e) {
LOG.error("Error while validating rep glob: {} ", expression, e);
isValid = false;
}
return isValid;
}
public static boolean isValidAction(String action) {
List<String> validActions = Arrays.asList(CqActions.ACTIONS);
if (action == null) {
return false;
}
if (!validActions.contains(action)) {
return false;
}
return true;
}
public static boolean isValidJcrPrivilege(String privilege, AccessControlManager aclManager) {
if (privilege == null) {
return false;
}
try {
aclManager.privilegeFromName(privilege);
} catch (RepositoryException e) {
return false;
}
return true;
}
public static boolean isValidPermission(String permission) {
if (permission == null) {
return false;
}
if (StringUtils.equals("allow", permission)
|| StringUtils.equals("deny", permission)) {
return true;
}
return false;
}
}
|
mtstv/accesscontroltool
|
accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/validators/Validators.java
|
Java
|
epl-1.0
| 3,216 |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.eclipse.persistence.config.CacheIsolationType;
import static org.eclipse.persistence.config.CacheIsolationType.SHARED;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.eclipse.persistence.annotations.CacheType.SOFT_WEAK;
import static org.eclipse.persistence.annotations.CacheCoordinationType.SEND_OBJECT_CHANGES;
/**
* The Cache annotation is used to configure the EclipseLink object cache.
* By default EclipseLink uses a shared object cache to cache all objects.
* The caching type and options can be configured on a per class basis to allow
* optimal caching.
* <p>
* This includes options for configuring the type of caching,
* setting the size, disabling the shared cache, expiring objects, refreshing,
* and cache coordination (clustering).
* <p>
* A Cache annotation may be defined on an Entity or MappedSuperclass. In the
* case of inheritance, a Cache annotation should only be defined on the root
* of the inheritance hierarchy.
*
* @see org.eclipse.persistence.annotations.CacheType
* @see org.eclipse.persistence.annotations.CacheCoordinationType
*
* @see org.eclipse.persistence.descriptors.ClassDescriptor
* @see org.eclipse.persistence.descriptors.invalidation.CacheInvalidationPolicy
*
* @author Guy Pelletier
* @since Oracle TopLink 11.1.1.0.0
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface Cache {
/**
* (Optional) The type of cache to use.
* The default is SOFT_WEAK.
*/
CacheType type() default SOFT_WEAK;
/**
* (Optional) The size of cache to use.
* The default is 100.
*/
int size() default 100;
/**
* (Optional) Cached instances in the shared cache,
* or only a per EntityManager isolated cache.
* The default is shared.
* @deprecated As of Eclipselink 2.2. See the attribute 'isolation'
*/
@Deprecated
boolean shared() default true;
/**
* (Optional) Controls the level of caching this Entity will use.
* The default is CacheIsolationType.SHARED which has EclipseLink
* Caching all Entities in the Shared Cache.
* @see org.eclipse.persistence.config.CacheIsolationType
*/
CacheIsolationType isolation() default SHARED;
/**
* (Optional) Expire cached instance after a fix period of time (ms).
* Queries executed against the cache after this will be forced back
* to the database for a refreshed copy.
* By default there is no expiry.
*/
int expiry() default -1; // minus one is no expiry.
/**
* (Optional) Expire cached instance a specific time of day. Queries
* executed against the cache after this will be forced back to the
* database for a refreshed copy.
*/
TimeOfDay expiryTimeOfDay() default @TimeOfDay(specified=false);
/**
* (Optional) Force all queries that go to the database to always
* refresh the cache.
* Default is false.
* Consider disabling the shared cache instead of forcing refreshing.
*/
boolean alwaysRefresh() default false;
/**
* (Optional) For all queries that go to the database, refresh the cache
* only if the data received from the database by a query is newer than
* the data in the cache (as determined by the optimistic locking field).
* This is normally used in conjunction with alwaysRefresh, and by itself
* it only affect explicit refresh calls or queries.
* Default is false.
*/
boolean refreshOnlyIfNewer() default false;
/**
* (Optional) Setting to true will force all queries to bypass the
* cache for hits but still resolve against the cache for identity.
* This forces all queries to hit the database.
*/
boolean disableHits() default false;
/**
* (Optional) The cache coordination mode.
* Note that cache coordination must also be configured for the persistence unit/session.
*/
CacheCoordinationType coordinationType() default SEND_OBJECT_CHANGES;
/**
* (Optional) The database change notification mode.
* Note that database event listener must also be configured for the persistence unit/session.
*/
DatabaseChangeNotificationType databaseChangeNotificationType() default DatabaseChangeNotificationType.INVALIDATE;
}
|
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
|
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/annotations/Cache.java
|
Java
|
epl-1.0
| 5,380 |
/**
* Java Beans.
*
* @author Archimedes Trajano
*/
package net.trajano.ms.vertx.beans;
|
trajano/app-ms
|
ms-common-impl/src/main/java/net/trajano/ms/vertx/beans/package-info.java
|
Java
|
epl-1.0
| 92 |
package edu.stanford.nlp.lm;
import java.io.File;
import java.util.Arrays;
/**
* This is a simple test of srilm.
* @author Alexandre Denis
*
*/
public class TestSRILM
{
/**
* @param args
*/
public static void main(String[] args)
{
SRILanguageModel model = new SRILanguageModel(new File("resources/ranking/lm-genia-lemma"), 3);
System.out.println(model.getSentenceLogProb(Arrays.asList("the central nucleotide be proportional to the size of the vacuole".split(" "))));
System.out.println(model.getSentenceLogProb(Arrays.asList("the be size to the nucleotide vacuole central the proportional to".split(" "))));
}
}
|
ModelWriter/Deliverables
|
WP2/D2.5.2_Generation/Jeni/src/edu/stanford/nlp/lm/TestSRILM.java
|
Java
|
epl-1.0
| 639 |
package daanielz.tools.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import daanielz.tools.Utils;
public class WorkbenchCmd implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player){
Player p = (Player) sender;
if(cmd.getName().equalsIgnoreCase("workbench")){
if(!sender.hasPermission("vetesda.workbench")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openWorkbench(null, true);
}
} else if(cmd.getName().equalsIgnoreCase("enchanttable")){
if(!sender.hasPermission("vetesda.enchanttable")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openEnchanting(null, true);
}
}
} return true;
}
}
|
DaanielZ/DToolsZ
|
DToolsZ/src/daanielz/tools/commands/WorkbenchCmd.java
|
Java
|
epl-1.0
| 978 |
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.base.impl.service.timer;
import java.io.Serializable;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLogger;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLoggingFactory;
/**
* Timer
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class Timer implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final TimerPriority priority;
private final NabuccoLogger logger = NabuccoLoggingFactory.getInstance().getLogger(this.getClass());
/**
* Creates a new {@link Timer} instance.
*
* @param name
* the timer name
* @param priority
* the timer priority
*/
public Timer(String name, TimerPriority priority) {
if (name == null) {
throw new IllegalArgumentException("Cannot create Timer for name [null].");
}
if (priority == null) {
throw new IllegalArgumentException("Cannot create Timer for priority [null].");
}
this.name = name;
this.priority = priority;
}
/**
* Getter for the logger.
*
* @return Returns the logger.
*/
protected NabuccoLogger getLogger() {
return this.logger;
}
/**
* Getter for the name.
*
* @return Returns the name.
*/
public final String getName() {
return this.name;
}
/**
* Getter for the priority.
*
* @return Returns the priority.
*/
public final TimerPriority getPriority() {
return this.priority;
}
/**
* Method that executes the appropriate timer logic.
*
* @throws TimerExecutionException
* when an exception during timer execution occurs
*/
public abstract void execute() throws TimerExecutionException;
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Timer other = (Timer) obj;
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public final String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.name);
builder.append(" [");
builder.append(this.getClass().getCanonicalName());
builder.append(", ");
builder.append(this.priority);
builder.append("]");
return builder.toString();
}
}
|
NABUCCO/org.nabucco.framework.base
|
org.nabucco.framework.base.impl.service/src/main/man/org/nabucco/framework/base/impl/service/timer/Timer.java
|
Java
|
epl-1.0
| 3,676 |
// Copyright (c) 1996-2002 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.application.api;
/** An plugin interface which identifies an ArgoUML data loader.
* <br>
* TODO: identify methods
*
* @author Thierry Lach
* @since ARGO0.11.3
*/
public interface PluggableProjectWriter extends Pluggable {
} /* End interface PluggableProjectWriter */
|
argocasegeo/argocasegeo
|
src/org/argouml/application/api/PluggableProjectWriter.java
|
Java
|
epl-1.0
| 1,869 |
package org.junit.runners.fix.v411;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
/**
* <p>
* The custom runner <code>Parameterized</code> implements parameterized tests.
* When running a parameterized test class, instances are created for the
* cross-product of the test methods and the test data elements.
* </p>
*
* For example, to test a Fibonacci function, write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters(name= "{index}: fib({0})={1}")
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
*
* private int fInput;
*
* private int fExpected;
*
* public FibonacciTest(int input, int expected) {
* fInput= input;
* fExpected= expected;
* }
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed using the
* two-argument constructor and the data values in the
* <code>@Parameters</code> method.
*
* <p>
* In order that you can easily identify the individual tests, you may provide a
* name for the <code>@Parameters</code> annotation. This name is allowed
* to contain placeholders, which are replaced at runtime. The placeholders are
* <dl>
* <dt>{index}</dt>
* <dd>the current parameter index</dd>
* <dt>{0}</dt>
* <dd>the first parameter value</dd>
* <dt>{1}</dt>
* <dd>the second parameter value</dd>
* <dt>...</dt>
* <dd></dd>
* </dl>
* In the example given above, the <code>Parameterized</code> runner creates
* names like <code>[1: fib(3)=2]</code>. If you don't use the name parameter,
* then the current parameter index is used as name.
* </p>
*
* You can also write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
* @Parameter(0)
* public int fInput;
*
* @Parameter(1)
* public int fExpected;
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed with the default constructor
* and fields annotated by <code>@Parameter</code> will be initialized
* with the data values in the <code>@Parameters</code> method.
* </p>
*
* @since 4.0
*/
public class Parameterized extends Suite {
/**
* Annotation for a method which provides parameters to be injected into the
* test class constructor by <code>Parameterized</code>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Parameters {
/**
* <p>
* Optional pattern to derive the test's name from the parameters. Use
* numbers in braces to refer to the parameters or the additional data
* as follows:
* </p>
*
* <pre>
* {index} - the current parameter index
* {0} - the first parameter value
* {1} - the second parameter value
* etc...
* </pre>
* <p>
* Default value is "{index}" for compatibility with previous JUnit
* versions.
* </p>
*
* @return {@link MessageFormat} pattern string, except the index
* placeholder.
* @see MessageFormat
*/
String name() default "{index}";
}
/**
* Annotation for fields of the test class which will be initialized by the
* method annotated by <code>Parameters</code><br/>
* By using directly this annotation, the test class constructor isn't needed.<br/>
* Index range must start at 0.
* Default value is 0.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface Parameter {
/**
* Method that returns the index of the parameter in the array
* returned by the method annotated by <code>Parameters</code>.<br/>
* Index range must start at 0.
* Default value is 0.
*
* @return the index of the parameter.
*/
int value() default 0;
}
protected static final Map<Character, String> ESCAPE_SEQUENCES = new HashMap<Character, String>();
static {
ESCAPE_SEQUENCES.put('\0', "\\\\0");
ESCAPE_SEQUENCES.put('\t', "\\\\t");
ESCAPE_SEQUENCES.put('\b', "\\\\b");
ESCAPE_SEQUENCES.put('\n', "\\\\n");
ESCAPE_SEQUENCES.put('\r', "\\\\r");
ESCAPE_SEQUENCES.put('\f', "\\\\f");
}
private class TestClassRunnerForParameters extends BlockJUnit4ClassRunner {
private final Object[] fParameters;
private final String fName;
TestClassRunnerForParameters(final Class<?> type, final Object[] parameters, final String name) throws InitializationError {
super(type);
this.fParameters = parameters;
this.fName = name;
}
@Override
public Object createTest() throws Exception {
if (fieldsAreAnnotated()) {
return createTestUsingFieldInjection();
} else {
return createTestUsingConstructorInjection();
}
}
private Object createTestUsingConstructorInjection() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(this.fParameters);
}
private Object createTestUsingFieldInjection() throws Exception {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
if (annotatedFieldsByParameter.size() != this.fParameters.length) {
throw new Exception(
"Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + this.fParameters.length + ".");
}
Object testClassInstance = getTestClass().getJavaClass().newInstance();
for (FrameworkField each : annotatedFieldsByParameter) {
Field field = each.getField();
Parameter annotation = field.getAnnotation(Parameter.class);
int index = annotation.value();
try {
field.set(testClassInstance, this.fParameters[index]);
} catch (IllegalArgumentException iare) {
throw new Exception(
getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + this.fParameters[index] + " that is not the right type (" + this.fParameters[index].getClass()
.getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);
}
}
return testClassInstance;
}
@Override
protected String getName() {
return this.fName;
}
@Override
protected String testName(final FrameworkMethod method) {
return method.getName() + getName();
}
@Override
protected void validateConstructor(final List<Throwable> errors) {
validateOnlyOneConstructor(errors);
if (fieldsAreAnnotated()) {
validateZeroArgConstructor(errors);
}
}
@Override
protected void validateFields(final List<Throwable> errors) {
super.validateFields(errors);
if (fieldsAreAnnotated()) {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
int[] usedIndices = new int[annotatedFieldsByParameter.size()];
for (FrameworkField each : annotatedFieldsByParameter) {
int index = each.getField().getAnnotation(Parameter.class).value();
if ((index < 0) || (index > (annotatedFieldsByParameter.size() - 1))) {
errors.add(new Exception(
"Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));
} else {
usedIndices[index]++;
}
}
for (int index = 0; index < usedIndices.length; index++) {
int numberOfUse = usedIndices[index];
if (numberOfUse == 0) {
errors.add(new Exception("@Parameter(" + index + ") is never used."));
} else if (numberOfUse > 1) {
errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));
}
}
}
}
@Override
protected Statement classBlock(final RunNotifier notifier) {
return childrenInvoker(notifier);
}
@Override
protected Annotation[] getRunnerAnnotations() {
return new Annotation[0];
}
}
private static final List<Runner> NO_RUNNERS = Collections.<Runner> emptyList();
private final ArrayList<Runner> runners = new ArrayList<Runner>();
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(final Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
@Override
protected List<Runner> getChildren() {
return this.runners;
}
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
private FrameworkMethod getParametersMethod() throws Exception {
List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
if (each.isStatic() && each.isPublic()) {
return each;
}
}
throw new Exception("No public static parameters method on class " + getTestClass().getName());
}
private void createRunnersForParameters(final Iterable<Object[]> allParameters, final String namePattern) throws InitializationError, Exception {
try {
int i = 0;
for (Object[] parametersOfSingleTest : allParameters) {
String name = nameFor(namePattern, i, parametersOfSingleTest);
TestClassRunnerForParameters runner = new TestClassRunnerForParameters(getTestClass().getJavaClass(), parametersOfSingleTest, name);
this.runners.add(runner);
++i;
}
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
private String nameFor(final String namePattern, final int index, final Object[] parameters) {
String finalPattern = namePattern.replaceAll("\\{index\\}", Integer.toString(index));
String name = MessageFormat.format(finalPattern, parameters);
return "[" + sanitizeEscapeSequencesWithName(name) + "]";
}
private String sanitizeEscapeSequencesWithName(final String name) {
String result = name;
for (Map.Entry<Character, String> currentSequence : ESCAPE_SEQUENCES.entrySet()) {
result = result.replaceAll("" + currentSequence.getKey(), currentSequence.getValue());
}
return result;
}
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", className, methodName);
return new Exception(message);
}
private List<FrameworkField> getAnnotatedFieldsByParameter() {
return getTestClass().getAnnotatedFields(Parameter.class);
}
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
}
|
aporo69/junit-issue-1167
|
poc/src/main/java/org/junit/runners/fix/v411/Parameterized.java
|
Java
|
epl-1.0
| 13,537 |
/**
* This file was copied and re-packaged automatically by
* org.xtext.example.delphi.build.GenerateCS2AST
* from
* ..\..\org.eclipse.qvtd\plugins\org.eclipse.qvtd.runtime\src\org\eclipse\qvtd\runtime\evaluation\AbstractInvocation.java
*
* Do not edit this file.
*/
/*******************************************************************************
* Copyright (c) 2013, 2016 Willink Transformations and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* E.D.Willink - Initial API and implementation
*******************************************************************************/
package org.xtext.example.delphi.tx;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.ocl.pivot.ids.TypeId;
import org.xtext.example.delphi.internal.tx.AbstractInvocationInternal;
/**
* AbstractInvocation provides the mandatory shared functionality of the intrusive blocked/waiting linked list functionality.
*/
public abstract class AbstractInvocation extends AbstractInvocationInternal
{
public abstract static class Incremental extends AbstractInvocation implements Invocation.Incremental
{
public static final @NonNull List<@NonNull Object> EMPTY_OBJECT_LIST = Collections.emptyList();
public static final @NonNull List<SlotState.@NonNull Incremental> EMPTY_SLOT_LIST = Collections.emptyList();
protected final @NonNull InvocationConstructor constructor;
protected final int sequence;
private Set<@NonNull Object> createdObjects = null;
private Set<SlotState.@NonNull Incremental> readSlots = null;
private Set<SlotState.@NonNull Incremental> writeSlots = null;
protected Incremental(InvocationConstructor.@NonNull Incremental constructor) {
super(constructor);
this.constructor = constructor;
this.sequence = constructor.nextSequence();
}
@Override
public void addCreatedObject(@NonNull Object createdObject) {
if (createdObjects == null) {
createdObjects = new HashSet<>();
}
createdObjects.add(createdObject);
}
@Override
public void addReadSlot(SlotState.@NonNull Incremental readSlot) {
if (readSlots == null) {
readSlots = new HashSet<>();
}
readSlots.add(readSlot);
readSlot.addTargetInternal(this);
}
@Override
public void addWriteSlot(SlotState.@NonNull Incremental writeSlot) {
if (writeSlots == null) {
writeSlots = new HashSet<>();
}
writeSlots.add(writeSlot);
writeSlot.addSourceInternal(this);
}
protected @NonNull Connection createConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createConnection(name, typeId, isStrict);
}
protected Connection.@NonNull Incremental createIncrementalConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createIncrementalConnection(name, typeId, isStrict);
}
@Override
public @NonNull Iterable<@NonNull Object> getCreatedObjects() {
return createdObjects != null ? createdObjects : EMPTY_OBJECT_LIST;
}
@SuppressWarnings("null")
@Override
public @NonNull String getName() {
InvocationConstructor constructor2 = constructor; // May be invoked from toString() during constructor debugging
return (constructor2 != null ? constructor2.getName() : "null") + "-" + sequence;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getReadSlots() {
return readSlots != null ? readSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getWriteSlots() {
return writeSlots != null ? writeSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull String toString() {
return getName();
}
}
protected AbstractInvocation(@NonNull InvocationConstructor constructor) {
super(constructor.getInterval());
}
@Override
public <R> R accept(@NonNull ExecutionVisitor<R> visitor) {
return visitor.visitInvocation(this);
}
@Override
public @NonNull String getName() {
return toString().replace("@", "\n@");
}
}
|
adolfosbh/cs2as
|
org.xtext.example.delphi/src-gen/org/xtext/example/delphi/tx/AbstractInvocation.java
|
Java
|
epl-1.0
| 4,339 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.model.sitemap.internal;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.openhab.model.core.ModelRepository;
import org.openhab.model.sitemap.Sitemap;
import org.openhab.model.sitemap.SitemapProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides access to the sitemap model files.
*
* @author Kai Kreuzer
*
*/
public class SitemapProviderImpl implements SitemapProvider {
private static final Logger logger = LoggerFactory.getLogger(SitemapProviderImpl.class);
private ModelRepository modelRepo = null;
public void setModelRepository(ModelRepository modelRepo) {
this.modelRepo = modelRepo;
}
public void unsetModelRepository(ModelRepository modelRepo) {
this.modelRepo = null;
}
/* (non-Javadoc)
* @see org.openhab.model.sitemap.internal.SitemapProvider#getSitemap(java.lang.String)
*/
public Sitemap getSitemap(String sitemapName) {
if(modelRepo!=null) {
//System.out.println("\n***SiteMapProviderImpl->getSitemap->"+modelRepo.getName());
Sitemap sitemap = (Sitemap) modelRepo.getModel(sitemapName + ".sitemap");
if(sitemap!=null) {
return sitemap;
} else {
logger.debug("Sitemap {} can not be found", sitemapName);
return null;
}
} else {
logger.debug("No model repository service is available");
return null;
}
}
public void iterate(EObject sitemap){
final TreeIterator<EObject> contentIterator=sitemap.eAllContents();
while (contentIterator.hasNext()) {
final EObject next=contentIterator.next();
}
}
}
|
rahulopengts/myhome
|
bundles/model/org.openhab.model.sitemap/src/org/openhab/model/sitemap/internal/SitemapProviderImpl.java
|
Java
|
epl-1.0
| 1,935 |
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.project.server;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.project.SourceStorage;
import org.eclipse.che.api.core.model.project.type.Attribute;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.core.util.LinksHelper;
import org.eclipse.che.api.project.server.importer.ProjectImporter;
import org.eclipse.che.api.project.server.type.ProjectTypeDef;
import org.eclipse.che.api.project.shared.dto.AttributeDto;
import org.eclipse.che.api.project.shared.dto.ItemReference;
import org.eclipse.che.api.project.shared.dto.ProjectImporterDescriptor;
import org.eclipse.che.api.project.shared.dto.ProjectTypeDto;
import org.eclipse.che.api.project.shared.dto.ValueDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectProblemDto;
import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import static javax.ws.rs.HttpMethod.DELETE;
import static javax.ws.rs.HttpMethod.GET;
import static javax.ws.rs.HttpMethod.PUT;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_CHILDREN;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_DELETE;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_GET_CONTENT;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_TREE;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_UPDATE_CONTENT;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_UPDATE_PROJECT;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
/**
* Helper methods for convert server essentials to DTO and back.
*
* @author andrew00x
*/
public class DtoConverter {
private DtoConverter() {
}
public static ProjectTypeDto toTypeDefinition(ProjectTypeDef projectType) {
final ProjectTypeDto definition = newDto(ProjectTypeDto.class).withId(projectType.getId())
.withDisplayName(projectType.getDisplayName())
.withPrimaryable(projectType.isPrimaryable())
.withMixable(projectType.isMixable())
.withAncestors(projectType.getAncestors());
final List<AttributeDto> typeAttributes = new ArrayList<>();
for (Attribute attr : projectType.getAttributes()) {
ValueDto valueDto = newDto(ValueDto.class);
if (attr.getValue() != null) {
valueDto.withList(attr.getValue().getList());
}
typeAttributes.add(newDto(AttributeDto.class).withName(attr.getName())
.withDescription(attr.getDescription())
.withRequired(attr.isRequired())
.withVariable(attr.isVariable())
.withValue(valueDto));
}
definition.withAttributes(typeAttributes).withParents(projectType.getParents());
return definition;
}
public static ProjectImporterDescriptor toImporterDescriptor(ProjectImporter importer) {
return newDto(ProjectImporterDescriptor.class).withId(importer.getId())
.withInternal(importer.isInternal())
.withDescription(importer.getDescription() != null ? importer.getDescription()
: "description not found")
.withCategory(importer.getCategory().getValue());
}
public static ItemReference toItemReference(FileEntry file, String workspace, UriBuilder uriBuilder)
throws ServerException {
return newDto(ItemReference.class).withName(file.getName())
.withPath(file.getPath().toString())
.withType("file")
.withAttributes(file.getAttributes())
.withModified(file.getModified())
.withContentLength(file.getVirtualFile().getLength())
.withLinks(generateFileLinks(file, workspace, uriBuilder));
}
public static ItemReference toItemReference(FolderEntry folder, String workspace, UriBuilder uriBuilder) {
return newDto(ItemReference.class).withName(folder.getName())
.withPath(folder.getPath().toString())
.withType(folder.isProject() ? "project" : "folder")
.withAttributes(folder.getAttributes())
.withModified(folder.getModified())
.withLinks(generateFolderLinks(folder, workspace, uriBuilder));
}
/**
* The method tries to provide as much as possible information about project.If get error then save information about error
* with 'problems' field in ProjectConfigDto.
*
* @param project
* project from which we need get information
* @param serviceUriBuilder
* service for building URI
* @return an instance of {@link ProjectConfigDto}
*/
public static ProjectConfigDto toProjectConfig(RegisteredProject project, String workspace, UriBuilder serviceUriBuilder) {
ProjectConfigDto projectConfigDto = newDto(ProjectConfigDto.class);
projectConfigDto.withName(project.getName())
.withPath(project.getPath())
.withDescription(project.getDescription());
List <String> mixins = project.getMixinTypes().keySet().stream().collect(Collectors.toList());
projectConfigDto.withMixins(mixins);
projectConfigDto.withAttributes(project.getAttributes());
projectConfigDto.withType(project.getProjectType().getId());
projectConfigDto.withSource(toSourceDto(project.getSource()));
for (RegisteredProject.Problem p : project.getProblems()) {
ProjectProblemDto projectProblem = newDto(ProjectProblemDto.class).withCode(p.code).withMessage(p.message);
projectConfigDto.getProblems().add(projectProblem);
}
if (serviceUriBuilder != null) {
projectConfigDto.withLinks(generateProjectLinks(project, workspace, serviceUriBuilder));
}
return projectConfigDto;
}
private static SourceStorageDto toSourceDto(SourceStorage sourceStorage) {
SourceStorageDto storageDto = newDto(SourceStorageDto.class);
if (sourceStorage != null) {
storageDto.withType(sourceStorage.getType())
.withLocation(sourceStorage.getLocation())
.withParameters(sourceStorage.getParameters());
}
return storageDto;
}
private static List<Link> generateProjectLinks(RegisteredProject project, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
if (project.getBaseFolder() != null) { //here project can be not imported so base directory not exist on file system but project exist in workspace config
links.addAll(generateFolderLinks(project.getBaseFolder(), workspace, uriBuilder));
}
final String relPath = project.getPath().substring(1);
links.add(LinksHelper.createLink(PUT,
uriBuilder.clone()
.path(ProjectService.class, "updateProject")
.build(workspace, relPath)
.toString(),
APPLICATION_JSON,
APPLICATION_JSON,
LINK_REL_UPDATE_PROJECT
));
return links;
}
private static List<Link> generateFolderLinks(FolderEntry folder, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
final String relPath = folder.getPath().toString().substring(1);
// links.add(LinksHelper.createLink(GET,
// uriBuilder.clone().path(ProjectService.class, "exportZip").build(workspace, relPath).toString(),
// ExtMediaType.APPLICATION_ZIP, LINK_REL_EXPORT_ZIP));
links.add(LinksHelper.createLink(GET,
uriBuilder.clone().path(ProjectService.class, "getChildren").build(workspace, relPath).toString(),
APPLICATION_JSON, LINK_REL_CHILDREN));
links.add(LinksHelper.createLink(GET,
uriBuilder.clone().path(ProjectService.class, "getTree").build(workspace, relPath).toString(),
null, APPLICATION_JSON, LINK_REL_TREE)
);
links.add(LinksHelper.createLink(DELETE,
uriBuilder.clone().path(ProjectService.class, "delete").build(workspace, relPath).toString(),
LINK_REL_DELETE));
return links;
}
private static List<Link> generateFileLinks(FileEntry file, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
final String relPath = file.getPath().toString().substring(1);
links.add(LinksHelper.createLink(GET, uriBuilder.clone().path(ProjectService.class, "getFile").build(workspace, relPath).toString(),
null, null, LINK_REL_GET_CONTENT));
links.add(LinksHelper.createLink(PUT,
uriBuilder.clone().path(ProjectService.class, "updateFile").build(workspace, relPath).toString(),
MediaType.WILDCARD, null, LINK_REL_UPDATE_CONTENT));
links.add(LinksHelper.createLink(DELETE,
uriBuilder.clone().path(ProjectService.class, "delete").build(workspace, relPath).toString(),
LINK_REL_DELETE));
return links;
}
}
|
dhuebner/che
|
wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/DtoConverter.java
|
Java
|
epl-1.0
| 11,509 |
/*******************************************************************************
* Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Denise Smith - 2.4
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.json.namespaces;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.PropertyException;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.testing.jaxb.json.JSONMarshalUnmarshalTestCases;
public class DifferentNamespacesTestCases extends JSONMarshalUnmarshalTestCases{
private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/namespaces/person.json";
private final static String JSON_WRITE_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/namespaces/person_different.json";
public DifferentNamespacesTestCases(String name) throws Exception {
super(name);
setControlJSON(JSON_RESOURCE);
setWriteControlJSON(JSON_WRITE_RESOURCE);
setClasses(new Class[]{Person.class});
}
protected Object getControlObject() {
Person p = new Person();
p.setId(10);
p.setFirstName("Jill");
p.setLastName("MacDonald");
List<String> middleNames = new ArrayList<String>();
middleNames.add("Jane");
middleNames.add("Janice");
p.setMiddleNames(middleNames);
Address addr = new Address();
addr.setStreet("The Street");
addr.setCity("Ottawa");
p.setAddress(addr);
return p;
}
public void setUp() throws Exception{
super.setUp();
Map<String, String> marshalNamespaceMap = new HashMap<String, String>();
marshalNamespaceMap.put("namespace0", "aaa");
marshalNamespaceMap.put("namespace1", "bbb");
marshalNamespaceMap.put("namespace2", "ccc");
marshalNamespaceMap.put("namespace3", "ddd");
Map<String, String> unmarshalNamespaceMap = new HashMap<String, String>();
unmarshalNamespaceMap.put("namespace0", "ns0");
unmarshalNamespaceMap.put("namespace1", "ns1");
unmarshalNamespaceMap.put("namespace2", "ns2");
unmarshalNamespaceMap.put("namespace3", "ns3");
try{
jsonMarshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, marshalNamespaceMap);
jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, unmarshalNamespaceMap);
}catch(PropertyException e){
e.printStackTrace();
fail("An error occurred setting properties during setup.");
}
}
public Map getProperties(){
Map props = new HashMap();
props.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");
return props;
}
}
|
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
|
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/namespaces/DifferentNamespacesTestCases.java
|
Java
|
epl-1.0
| 3,331 |
/******************************************************************************
*
* Copyright 2013-2019 Paphus Solutions Inc.
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
*
* 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.botlibre.web.rest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.botlibre.util.Utils;
import org.botlibre.web.admin.AccessMode;
import org.botlibre.web.bean.IssueTrackerBean;
import org.botlibre.web.bean.LoginBean;
/**
* DTO for XML IssueTracker config.
*/
@XmlRootElement(name="issuetracker")
@XmlAccessorType(XmlAccessType.FIELD)
public class IssueTrackerConfig extends WebMediumConfig {
@XmlAttribute
public String createAccessMode;
@XmlAttribute
public String issues;
public String getCreateAccessMode() {
if (this.createAccessMode == null || this.createAccessMode.isEmpty()) {
return AccessMode.Everyone.name();
}
return this.createAccessMode;
}
public IssueTrackerBean getBean(LoginBean loginBean) {
return loginBean.getBean(IssueTrackerBean.class);
}
public void sanitize() {
createAccessMode = Utils.sanitize(createAccessMode);
issues = Utils.sanitize(issues);
}
}
|
BOTlibre/BOTlibre
|
botlibre-web/source/org/botlibre/web/rest/IssueTrackerConfig.java
|
Java
|
epl-1.0
| 1,868 |
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.base.facade.datatype;
import java.util.Arrays;
/**
* NByteArray
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class NByteArray extends BasetypeSupport implements Basetype, Comparable<NByteArray> {
private static final long serialVersionUID = 1L;
private byte[] value;
/**
* Default constructor
*/
public NByteArray() {
this(null);
}
/**
* Constructor initializing the value.
*
* @param value
* the value to initialize
*/
public NByteArray(byte[] value) {
super(BasetypeType.BYTE_ARRAY);
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String getValueAsString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public void setValue(Object value) throws IllegalArgumentException {
if (value != null && !(value instanceof byte[])) {
throw new IllegalArgumentException("Cannot set value '" + value + "' to NByteArray.");
}
this.setValue((byte[]) value);
}
/**
* Setter for the byte[] value.
*
* @param value
* the byte[] value to set.
*/
public void setValue(byte[] value) {
this.value = value;
}
/**
* Returns a <code>String</code> object representing this <code>NByteArray</code>'s value.
*
* @return a string representation of the value of this object in base 10.
*/
@Override
public String toString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof NByteArray))
return false;
NByteArray other = (NByteArray) obj;
if (!Arrays.equals(this.value, other.value))
return false;
return true;
}
@Override
public int compareTo(NByteArray other) {
if (other == null) {
return -1;
}
if (getValue() == null) {
if (other.getValue() == null) {
return 0;
}
return 1;
}
if (other.getValue() == null) {
return -1;
}
if (this.value.length != other.value.length) {
if (this.value.length > other.value.length) {
return 1;
}
if (this.value.length < other.value.length) {
return -1;
}
}
for (int i = 0; i < this.value.length; i++) {
if (this.value[i] != other.value[i]) {
if (this.value[i] > other.value[i]) {
return 1;
}
if (this.value[i] < other.value[i]) {
return -1;
}
}
}
return 0;
}
@Override
public abstract NByteArray cloneObject();
/**
* Clones the properties of this basetype into the given basetype.
*
* @param clone
* the cloned basetype
*/
protected void cloneObject(NByteArray clone) {
if (this.value != null) {
clone.value = Arrays.copyOf(this.value, this.value.length);
}
}
}
|
NABUCCO/org.nabucco.framework.base
|
org.nabucco.framework.base.facade.datatype/src/main/man/org/nabucco/framework/base/facade/datatype/NByteArray.java
|
Java
|
epl-1.0
| 4,346 |
package ch.docbox.ws.cdachservicesv2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.hl7.v3.CE;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="code" type="{urn:hl7-org:v3}CE" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"code"
})
@XmlRootElement(name = "getInboxClinicalDocuments")
public class GetInboxClinicalDocuments {
protected CE code;
/**
* Ruft den Wert der code-Eigenschaft ab.
*
* @return
* possible object is
* {@link CE }
*
*/
public CE getCode() {
return code;
}
/**
* Legt den Wert der code-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CE }
*
*/
public void setCode(CE value) {
this.code = value;
}
}
|
DavidGutknecht/elexis-3-base
|
bundles/ch.elexis.docbox.ws.client/src-gen/ch/docbox/ws/cdachservicesv2/GetInboxClinicalDocuments.java
|
Java
|
epl-1.0
| 1,395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.