repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
siarhei-luskanau/siarhei.luskanau.places | data/src/main/java/siarhei/luskanau/places/data/repository/datasource/DiskPlaceDataStore.java | 1764 | /**
* Copyright (C) 2015 Fernando Cejas Open Source Project
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 siarhei.luskanau.places.data.repository.datasource;
import java.util.List;
import io.reactivex.Observable;
import siarhei.luskanau.places.data.cache.PlaceCache;
import siarhei.luskanau.places.data.entity.PlaceEntity;
import siarhei.luskanau.places.domain.LatLng;
/**
* {@link PlaceDataStore} implementation based on file system data store.
*/
class DiskPlaceDataStore implements PlaceDataStore {
private final PlaceCache placeCache;
/**
* Construct a {@link PlaceDataStore} based file system data store.
*
* @param placeCache A {@link PlaceCache} to cache data retrieved from the api.
*/
DiskPlaceDataStore(PlaceCache placeCache) {
this.placeCache = placeCache;
}
@Override
public Observable<List<PlaceEntity>> placeEntityList(LatLng location) {
//TODO: implement simple cache for storing/retrieving collections of places.
throw new UnsupportedOperationException("Operation is not available!!!");
}
@Override
public Observable<PlaceEntity> placeEntityDetails(final String placeId) {
return this.placeCache.get(placeId);
}
}
| mit |
TehStoneMan/ShipWright | src/main/java/io/github/tehstoneman/shipwright/block/BlockCrateWood.java | 1680 | package io.github.tehstoneman.shipwright.block;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class BlockCrateWood extends Block
{
public static final PropertyDirection FACING = PropertyDirection.create( "facing", EnumFacing.Plane.HORIZONTAL );
public static int renderID;
private static String name = "crate_wood";
public BlockCrateWood()
{
super( Material.wood );
setBlockBounds( 0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F );
setHardness( 1F );
setResistance( 1F );
setStepSound( Block.soundTypeWood );
}
public static String getName()
{
return name;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean isFullCube()
{
return false;
}
@Override
protected BlockState createBlockState()
{
return new BlockState( this, new IProperty[] { FACING } );
}
@Override
public int getMetaFromState( IBlockState state )
{
final EnumFacing facing = (EnumFacing) state.getValue( FACING );
return facing.getHorizontalIndex();
}
@Override
public IBlockState onBlockPlaced( World world, BlockPos pos, EnumFacing blockFaceClickedOn, float hitX, float hitY, float hitZ, int meta,
EntityLivingBase placer )
{
return getDefaultState().withProperty( FACING, placer.getHorizontalFacing().getOpposite() );
}
}
| mit |
spark008/mit6005-pingball | src/pb/render/Viewport.java | 3947 | package pb.render;
import java.awt.Color;
import java.awt.Graphics2D;
/**
* Parameters for rendering a board into a GUI window.
*
* Instances of this class are thread-safe, and are used to pass high-level
* rendering information from the board thread managed by
* {@link pb.client.ClientController} to {@link pb.client.ClientUiFrame}.
*/
public class Viewport {
/** The board size along the X axis. */
private final int m_xSize;
/** The board size along the Y axis. */
private final int m_ySize;
/** Number of horizontal pixels taken up by each board length unit (L). */
private final int m_xScale;
/** Number of vertical pixels taken up by each board length unit (L). */
private final int m_yScale;
// Rep invariant:
// m_xSize, m_ySize, m_xScale and m_yScale must be positive
// AF:
// a board of m_xSize x m_ySize Ls should be rendered on the screen using
// a box of m_xScale x m_yScale pixels for each 1L-side box on the board
// Thread safety:
// all fields are final primitive values, and therefore immutable
public Viewport(int xSize, int ySize) {
assert xSize > 0;
assert ySize > 0;
this.m_xSize = xSize;
this.m_ySize = ySize;
this.m_xScale = 20;
this.m_yScale = 20;
}
/**
* The size of the board along the X axis.
*
* @return the size of the board along the X axis, in Ls (length units)
*/
public int xSize() {
return m_xSize;
}
/**
* The size of the board along the Y axis.
*
* @return the size of the board along the Y axis, in Ls (length units)
*/
public int ySize() {
return m_ySize;
}
/**
* The number of horizontal pixels taken up by each board length unit (L).
*
* @return the number of pixels used to render a 1L horizontal line
*/
public int xScale() {
return m_xScale;
}
/**
* The number of vertical pixels taken up by each board length unit (L).
*
* @return the number of pixels used to render a 1L vertical line
*/
public int yScale() {
return m_yScale;
}
/**
* The number of horizontal pixels needed to render the board.
*
* @return the horizontal size, in pixels, of the UI element that contains
* the board's rendering
*/
public int xPixels() {
return m_xScale * (m_xSize + 2);
}
/**
* The number of vertical pixels needed to render the board.
*
* @return the vertical size, in pixels, of the UI element that contains
* the board's rendering
*/
public int yPixels() {
return m_yScale * (m_ySize + 2);
}
/**
* Translates from board coordinates to render coordinates along the X axis.
*
* @param x the X board coordinate, in Ls
* @return the corresponding coordinate in render space, in pixels
*/
public int x(double x) {
assert -1 <= x && x <= m_xSize + 1;
return m_xScale + (int)Math.round(m_xScale * x);
}
/**
* Translates from board coordinates to render coordinates along the Y axis.
*
* @param y the Y board coordinate, in Ls
* @return the corresponding coordinate in render space, in pixels
*/
public int y(double y) {
assert -1 <= y && y <= m_xSize + 1;
return m_yScale + (int)Math.round(m_yScale * y);
}
/**
* Translates from board distances to render distances along the X axis.
*
* @param dx the X board distance, in Ls
* @return the corresponding distance in render space, in pixels
*/
public int dx(double x) {
return (int)Math.round(m_xScale * x);
}
/**
* Translates from board distances to render distances along the Y axis.
*
* @param dy the Y board distance, in Ls
* @return the corresponding distance in render space, in pixels
*/
public int dy(double y) {
return (int)Math.round(m_yScale * y);
}
/**
* Convenience method for clearing a rendering buffer.
*
* @param context drawing context for the rendering buffer to be cleared
*/
public void clear(Graphics2D context) {
context.setColor(Color.BLACK);
context.fillRect(0, 0, xPixels(), yPixels());
}
} | mit |
YashchenkoN/doctor-office-api | src/main/java/ua/kpi/dto/response/CurrentUser.java | 312 | package ua.kpi.dto.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.hateoas.ResourceSupport;
/**
* @author Mykola Yashchenko
*/
@Getter
@Setter
@AllArgsConstructor
public class CurrentUser extends ResourceSupport {
private String name;
}
| mit |
LinDA-tools/RDF2Any | linda/src/main/java/de/unibonn/iai/eis/linda/querybuilder/output/ClassPropertyOutput.java | 639 | package de.unibonn.iai.eis.linda.querybuilder.output;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import de.unibonn.iai.eis.linda.querybuilder.classes.MultipleRDFClass;
import de.unibonn.iai.eis.linda.querybuilder.classes.RDFClass;
@JsonInclude(Include.NON_NULL)
public class ClassPropertyOutput {
public RDFClass rdfClass = null;
public MultipleRDFClass multiRdfClass = null;
public ClassPropertyOutput(RDFClass rdfClass){
this.rdfClass = rdfClass;
}
public ClassPropertyOutput(MultipleRDFClass multiRdfClass){
this.multiRdfClass = multiRdfClass;
}
}
| mit |
XtraStudio/XtraAPI | src/main/java/com/xtra/api/command/base/CommandBase.java | 3037 | /**
* This file is part of XtraAPI, licensed under the MIT License (MIT).
*
* Copyright (c) 2016 - 2016 XtraStudio <https://github.com/XtraStudio>
* 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 com.xtra.api.command.base;
import java.lang.reflect.ParameterizedType;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import com.xtra.api.command.Command;
import com.xtra.api.util.command.CommandBaseExecutor;
/**
* Provides a base for commands. Support for many XtraCore command features are
* provided through this default implementation. It is highly recommended to use
* this base class, over implementing your own {@link Command} or using
* {@link CommandBaseLite}.
*
* @param <T> The {@link CommandSource} required to execute this command. If a
* {@link CommandSource} not of the same type as the one specified in
* this generic attempts to execute this command, they will receive an
* error message. Note that if you wish for any {@link CommandSource} to
* execute this command, specify <code>CommandSource</code> in the
* generic.
*/
public abstract class CommandBase<T extends CommandSource> implements Command {
// NOTE: this is overridden by the implementation
private static CommandBaseExecutor BASE = null;
public abstract CommandResult executeCommand(T src, CommandContext args) throws Exception;
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
// Get the generic type
@SuppressWarnings("rawtypes")
Class<?> o = ((Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0]);
// Let the implementation handle the rest of the logic
return BASE.execute(this, o, src, args);
}
}
| mit |
Juffik/JavaRush-1 | src/com/javarush/test/level06/lesson11/home05/Solution.java | 986 | package com.javarush.test.level06.lesson11.home05;
/* Есть новые идеи? Подумаем...
1. В классе Solution создать public статический класс Idea
2. В классе Idea создать метод public String getDescription(), который будет возвращать любой непустой текст
3. В классе Solution создайте статический метод public void printIdea(Idea idea), который будет выводить
на экран описание идеи - это то, что возвращает метод getDescription
*/
public class Solution
{
public static void main(String[] args) {
Idea op = new Idea();
printIdea(op);
}
public static class Idea {
public String getDescription() {
return "waaaat?";
}
}
public static void printIdea(Idea id)
{
System.out.println(id.getDescription());
}
}
| mit |
roberthovhannisyan/cordova-plugin-datepicker | src/android/DatePickerPlugin.java | 14692 | /**
* @author Bikas Vaibhav (http://bikasv.com) 2013
* Rewrote the plug-in at https://github.com/phonegap/phonegap-plugins/tree/master/Android/DatePicker
* It can now accept `min` and `max` dates for DatePicker.
*
* @author Andre Moraes (https://github.com/andrelsmoraes)
* Refactored code, changed default mode to show date and time dialog.
* Added options `okText`, `cancelText`, `todayText`, `nowText`, `is24Hour`.
*/
package com.plugin.datepicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Random;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
@SuppressLint("NewApi")
public class DatePickerPlugin extends CordovaPlugin {
private static final String ACTION_DATE = "date";
private static final String ACTION_TIME = "time";
private static final String RESULT_ERROR = "error";
private static final String RESULT_CANCEL = "cancel";
private final String pluginName = "DatePickerPlugin";
// On some devices, onDateSet or onTimeSet are being called twice
private boolean called = false;
private boolean canceled = false;
@Override
public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) {
Log.d(pluginName, "DatePicker called with options: " + data);
called = false;
canceled = false;
boolean result = false;
this.show(data, callbackContext);
result = true;
return result;
}
public synchronized void show(final JSONArray data, final CallbackContext callbackContext) {
DatePickerPlugin datePickerPlugin = this;
Context currentCtx = cordova.getActivity();
Runnable runnable;
JsonDate jsonDate = new JsonDate().fromJson(data);
// Retrieve Android theme
JSONObject options = data.optJSONObject(0);
int theme = options.optInt("androidTheme", 1);
if (ACTION_TIME.equalsIgnoreCase(jsonDate.action)) {
runnable = runnableTimeDialog(datePickerPlugin, theme, currentCtx,
callbackContext, jsonDate, Calendar.getInstance(TimeZone.getDefault()));
} else {
runnable = runnableDatePicker(datePickerPlugin, theme, currentCtx, callbackContext, jsonDate);
}
cordova.getActivity().runOnUiThread(runnable);
}
private Runnable runnableTimeDialog(final DatePickerPlugin datePickerPlugin,
final int theme, final Context currentCtx, final CallbackContext callbackContext,
final JsonDate jsonDate, final Calendar calendarDate) {
return new Runnable() {
@Override
public void run() {
final TimeSetListener timeSetListener = new TimeSetListener(datePickerPlugin, callbackContext, calendarDate);
final TimePickerDialog timeDialog = new TimePickerDialog(currentCtx, theme, timeSetListener, jsonDate.hour,
jsonDate.minutes, jsonDate.is24Hour);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
timeDialog.setCancelable(true);
timeDialog.setCanceledOnTouchOutside(false);
if (!jsonDate.nowText.isEmpty()){
timeDialog.setButton(DialogInterface.BUTTON_NEUTRAL, jsonDate.nowText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Calendar now = Calendar.getInstance();
timeSetListener.onTimeSet(null, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
}
});
}
String labelCancel = jsonDate.cancelText.isEmpty() ? currentCtx.getString(android.R.string.cancel) : jsonDate.cancelText;
timeDialog.setButton(DialogInterface.BUTTON_NEGATIVE, labelCancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
canceled = true;
callbackContext.error(RESULT_CANCEL);
}
});
String labelOk = jsonDate.okText.isEmpty() ? currentCtx.getString(android.R.string.ok) : jsonDate.okText;
timeDialog.setButton(DialogInterface.BUTTON_POSITIVE, labelOk, timeDialog);
}
timeDialog.show();
timeDialog.updateTime(new Random().nextInt(23), new Random().nextInt(59));
timeDialog.updateTime(jsonDate.hour, jsonDate.minutes);
}
};
}
private Runnable runnableDatePicker(
final DatePickerPlugin datePickerPlugin,
final int theme, final Context currentCtx,
final CallbackContext callbackContext, final JsonDate jsonDate) {
return new Runnable() {
@Override
public void run() {
final DateSetListener dateSetListener = new DateSetListener(datePickerPlugin, theme, callbackContext, jsonDate);
final DatePickerDialog dateDialog = new DatePickerDialog(currentCtx, theme, dateSetListener, jsonDate.year,
jsonDate.month, jsonDate.day);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
prepareDialog(dateDialog, dateSetListener, callbackContext, currentCtx, jsonDate);
}
else {
prepareDialogPreHoneycomb(dateDialog, callbackContext, currentCtx, jsonDate);
}
dateDialog.show();
}
};
}
private void prepareDialog(final DatePickerDialog dateDialog, final OnDateSetListener dateListener,
final CallbackContext callbackContext, Context currentCtx, JsonDate jsonDate) {
dateDialog.setCancelable(true);
dateDialog.setCanceledOnTouchOutside(false);
if (!jsonDate.todayText.isEmpty()){
dateDialog.setButton(DialogInterface.BUTTON_NEUTRAL, jsonDate.todayText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Calendar now = Calendar.getInstance();
DatePicker datePicker = dateDialog.getDatePicker();
dateListener.onDateSet(datePicker, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
}
});
}
String labelCancel = jsonDate.cancelText.isEmpty() ? currentCtx.getString(android.R.string.cancel) : jsonDate.cancelText;
dateDialog.setButton(DialogInterface.BUTTON_NEGATIVE, labelCancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
canceled = true;
callbackContext.error(RESULT_CANCEL);
}
});
String labelOk = jsonDate.okText.isEmpty() ? currentCtx.getString(android.R.string.ok) : jsonDate.okText;
dateDialog.setButton(DialogInterface.BUTTON_POSITIVE, labelOk, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatePicker datePicker = dateDialog.getDatePicker();
datePicker.clearFocus();
dateListener.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
}
});
DatePicker dp = dateDialog.getDatePicker();
if(jsonDate.minDate > 0) {
dp.setMinDate(jsonDate.minDate);
}
if(jsonDate.maxDate > 0 && jsonDate.maxDate > jsonDate.minDate) {
dp.setMaxDate(jsonDate.maxDate);
}
}
private void prepareDialogPreHoneycomb(DatePickerDialog dateDialog,
final CallbackContext callbackContext, Context currentCtx, final JsonDate jsonDate){
java.lang.reflect.Field mDatePickerField = null;
try {
mDatePickerField = dateDialog.getClass().getDeclaredField("mDatePicker");
} catch (NoSuchFieldException e) {
callbackContext.error(RESULT_ERROR);
}
mDatePickerField.setAccessible(true);
DatePicker pickerView = null;
try {
pickerView = (DatePicker) mDatePickerField.get(dateDialog);
} catch (IllegalArgumentException e) {
callbackContext.error(RESULT_ERROR);
} catch (IllegalAccessException e) {
callbackContext.error(RESULT_ERROR);
}
final Calendar startDate = Calendar.getInstance();
startDate.setTimeInMillis(jsonDate.minDate);
final Calendar endDate = Calendar.getInstance();
endDate.setTimeInMillis(jsonDate.maxDate);
final int minYear = startDate.get(Calendar.YEAR);
final int minMonth = startDate.get(Calendar.MONTH);
final int minDay = startDate.get(Calendar.DAY_OF_MONTH);
final int maxYear = endDate.get(Calendar.YEAR);
final int maxMonth = endDate.get(Calendar.MONTH);
final int maxDay = endDate.get(Calendar.DAY_OF_MONTH);
if(startDate !=null || endDate != null) {
pickerView.init(jsonDate.year, jsonDate.month, jsonDate.day, new OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if(jsonDate.maxDate > 0 && jsonDate.maxDate > jsonDate.minDate) {
if(year > maxYear || month > maxMonth && year == maxYear || day > maxDay && year == maxYear && month == maxMonth){
view.updateDate(maxYear, maxMonth, maxDay);
}
}
if(jsonDate.minDate > 0) {
if(year < minYear || month < minMonth && year == minYear || day < minDay && year == minYear && month == minMonth) {
view.updateDate(minYear, minMonth, minDay);
}
}
}
});
}
}
private final class DateSetListener implements OnDateSetListener {
private JsonDate jsonDate;
private final DatePickerPlugin datePickerPlugin;
private final CallbackContext callbackContext;
private final int theme;
private DateSetListener(DatePickerPlugin datePickerPlugin, int theme, CallbackContext callbackContext, JsonDate jsonDate) {
this.datePickerPlugin = datePickerPlugin;
this.callbackContext = callbackContext;
this.jsonDate = jsonDate;
this.theme = theme;
}
/**
* Return a string containing the date in the format YYYY/MM/DD or call TimeDialog if action != date
*/
@Override
public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
if (canceled || called) {
return;
}
called = true;
canceled = false;
Log.d("onDateSet", "called: " + called);
Log.d("onDateSet", "canceled: " + canceled);
Log.d("onDateSet", "mode: " + jsonDate.action);
Calendar selectedDate = Calendar.getInstance();
selectedDate.set(Calendar.YEAR, year);
selectedDate.set(Calendar.MONTH, monthOfYear);
selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (ACTION_DATE.equalsIgnoreCase(jsonDate.action)) {
selectedDate.set(Calendar.HOUR_OF_DAY, 0);
selectedDate.set(Calendar.MINUTE, 0);
selectedDate.set(Calendar.SECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String toReturn = sdf.format(selectedDate.getTime());
Log.d(pluginName, "onDateSet returned date: " + toReturn);
callbackContext.success(toReturn);
} else {
// Open time dialog
cordova.getActivity().runOnUiThread(runnableTimeDialog(datePickerPlugin, theme, cordova.getActivity(),
callbackContext, jsonDate, selectedDate));
}
}
}
private final class TimeSetListener implements OnTimeSetListener {
private Calendar calendarDate;
private final CallbackContext callbackContext;
private TimeSetListener(DatePickerPlugin datePickerPlugin, CallbackContext callbackContext, Calendar selectedDate) {
this.callbackContext = callbackContext;
this.calendarDate = selectedDate != null ? selectedDate : Calendar.getInstance();
}
/**
* Return the current date with the time modified as it was set in the
* time picker.
*/
@Override
public void onTimeSet(final TimePicker view, final int hourOfDay, final int minute) {
if (canceled) {
return;
}
calendarDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendarDate.set(Calendar.MINUTE, minute);
calendarDate.set(Calendar.SECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String toReturn = sdf.format(calendarDate.getTime());
Log.d(pluginName, "onTimeSet returned time: " + toReturn);
callbackContext.success(toReturn);
}
}
private final class JsonDate {
private String action = ACTION_DATE;
private String okText = "";
private String cancelText = "";
private String todayText = "";
private String nowText = "";
private long minDate = 0;
private long maxDate = 0;
private int month = 0;
private int day = 0;
private int year = 0;
private int hour = 0;
private int minutes = 0;
private boolean is24Hour = false;
public JsonDate() {
reset(Calendar.getInstance());
}
private void reset(Calendar c) {
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
}
public JsonDate fromJson(JSONArray data) {
try {
JSONObject obj = data.getJSONObject(0);
action = isNotEmpty(obj, "mode") ? obj.getString("mode")
: ACTION_DATE;
minDate = isNotEmpty(obj, "minDate") ? obj.getLong("minDate") : 0l;
maxDate = isNotEmpty(obj, "maxDate") ? obj.getLong("maxDate") : 0l;
okText = isNotEmpty(obj, "okText") ? obj.getString("okText") : "";
cancelText = isNotEmpty(obj, "cancelText") ? obj
.getString("cancelText") : "";
todayText = isNotEmpty(obj, "todayText") ? obj
.getString("todayText") : "";
nowText = isNotEmpty(obj, "nowText") ? obj.getString("nowText")
: "";
is24Hour = isNotEmpty(obj, "is24Hour") ? obj.getBoolean("is24Hour")
: false;
String optionDate = obj.getString("date");
String[] datePart = optionDate.split("/");
month = Integer.parseInt(datePart[0]) - 1;
day = Integer.parseInt(datePart[1]);
year = Integer.parseInt(datePart[2]);
hour = Integer.parseInt(datePart[3]);
minutes = Integer.parseInt(datePart[4]);
} catch (JSONException e) {
reset(Calendar.getInstance());
}
return this;
}
public boolean isNotEmpty(JSONObject object, String key)
throws JSONException {
return object.has(key)
&& !object.isNull(key)
&& object.get(key).toString().length() > 0
&& !JSONObject.NULL.toString().equals(
object.get(key).toString());
}
}
}
| mit |
defano/hypertalk-java | src/main/java/com/defano/wyldcard/search/WyldCardSearchManager.java | 2731 | package com.defano.wyldcard.search;
import com.defano.hypertalk.ast.model.Value;
import com.defano.hypertalk.exception.HtException;
import com.defano.wyldcard.runtime.context.ExecutionContext;
import com.google.inject.Singleton;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class WyldCardSearchManager implements SearchManager {
private SearchQuery lastQuery;
private List<SearchResult> results = new ArrayList<>();
private int nextResult = 0;
private Value foundChunk = new Value();
private Value foundField = new Value();
private Value foundLine = new Value();
private Value foundText = new Value();
@Override
public void find(ExecutionContext context, SearchQuery query) throws HtException {
// Wrap search results
if (nextResult >= results.size()) {
nextResult = 0;
}
// Continue last query
if (isResumingSearch(query)) {
processSearchResult(context, results.get(nextResult++));
}
// Start new query
else {
lastQuery = query;
results = SearchIndexer.indexResults(context, query);
nextResult = 0;
if (results.isEmpty()) {
processSearchResult(context, null);
} else {
processSearchResult(context, results.get(nextResult++));
}
}
}
@Override
public void reset() {
clearSearchHighlights(new ExecutionContext());
results.clear();
foundChunk = new Value();
foundField = new Value();
foundLine = new Value();
foundChunk = new Value();
}
@Override
public Value getFoundChunk() {
return foundChunk;
}
@Override
public Value getFoundField() {
return foundField;
}
@Override
public Value getFoundLine() {
return foundLine;
}
@Override
public Value getFoundText() {
return foundText;
}
private void processSearchResult(ExecutionContext context, SearchResult result) {
if (result == null) {
context.setResult(new Value("Not found"));
Toolkit.getDefaultToolkit().beep();
} else {
foundText = new Value(result.getFoundText());
foundField = new Value(result.getFoundField(context));
foundLine = new Value(result.getFoundLine(context));
foundChunk = new Value(result.getFoundChunk(context));
highlightSearchResult(context, result);
}
}
private boolean isResumingSearch(SearchQuery query) {
return lastQuery != null && lastQuery.equals(query) && results.size() > 0;
}
}
| mit |
OfficeDev/Microsoft-Graph-SDK-Android | sdk/graph-services/src/main/java/com/microsoft/services/graph/ContactFolder.java | 3173 | /*******************************************************************************
**NOTE** This code was generated by a tool and will occasionally be
overwritten. We welcome comments and issues regarding this code; they will be
addressed in the generation tool. If you wish to submit pull requests, please
do so for the templates in that tool.
This code was generated by Vipr (https://github.com/microsoft/vipr) using
the T4TemplateWriter (https://github.com/msopentech/vipr-t4templatewriter).
Copyright (c) Microsoft Corporation. All Rights Reserved.
Licensed under the Apache License 2.0; see LICENSE in the source repository
root for authoritative license information.
******************************************************************************/
package com.microsoft.services.graph;
/**
* The type Contact Folder.
* @deprecated This SDK is deprecated. Please review the README for further information (https://github.com/OfficeDev/Microsoft-Graph-SDK-Android).
*/
@Deprecated
public class ContactFolder extends Entity {
public ContactFolder(){
setODataType("#microsoft.graph.contactFolder");
}
private String parentFolderId;
/**
* Gets the parent Folder Id.
*
* @return the String
*/
public String getParentFolderId() {
return this.parentFolderId;
}
/**
* Sets the parent Folder Id.
*
* @param value the String
*/
public void setParentFolderId(String value) {
this.parentFolderId = value;
valueChanged("parentFolderId", value);
}
private String displayName;
/**
* Gets the display Name.
*
* @return the String
*/
public String getDisplayName() {
return this.displayName;
}
/**
* Sets the display Name.
*
* @param value the String
*/
public void setDisplayName(String value) {
this.displayName = value;
valueChanged("displayName", value);
}
private java.util.List<Contact> contacts = null;
/**
* Gets the contacts.
*
* @return the java.util.List<Contact>
*/
public java.util.List<Contact> getContacts() {
return this.contacts;
}
/**
* Sets the contacts.
*
* @param value the java.util.List<Contact>
*/
public void setContacts(java.util.List<Contact> value) {
this.contacts = value;
valueChanged("contacts", value);
}
private java.util.List<ContactFolder> childFolders = null;
/**
* Gets the child Folders.
*
* @return the java.util.List<ContactFolder>
*/
public java.util.List<ContactFolder> getChildFolders() {
return this.childFolders;
}
/**
* Sets the child Folders.
*
* @param value the java.util.List<ContactFolder>
*/
public void setChildFolders(java.util.List<ContactFolder> value) {
this.childFolders = value;
valueChanged("childFolders", value);
}
}
| mit |
lastrix/asn1s | asn1s-io/src/main/java/org/asn1s/io/ber/input/NullBerDecoder.java | 2381 | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2017. Lapinin "lastrix" Sergey. /
// /
// 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 /
// NON INFRINGEMENT. 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.asn1s.io.ber.input;
import org.asn1s.api.type.Type.Family;
import org.asn1s.api.value.Value;
import org.asn1s.api.value.x680.NullValue;
import org.jetbrains.annotations.NotNull;
final class NullBerDecoder implements BerDecoder
{
@Override
public Value decode( @NotNull ReaderContext context )
{
assert context.getType().getFamily() == Family.NULL;
assert context.getLength() == 0;
return NullValue.INSTANCE;
}
}
| mit |
michaelfairley/flippy_bird | core/src/main/java/com/m12y/flippy_bird/core/rendering/GameRenderer.java | 5037 | package com.m12y.flippy_bird.core.rendering;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector3;
import com.m12y.flippy_bird.core.logic.Game;
import com.m12y.flippy_bird.core.logic.Obstacle;
public class GameRenderer {
private final ShapeRenderer shapeRenderer;
private final ShapeRenderer textShapeRenderer;
private final OrthographicCamera camera;
private final OrthographicCamera textCamera;
private final BirdRenderer birdRenderer;
private final ObstacleRenderer obstacleRenderer;
private final BitmapFont scoreFont;
private final SpriteBatch spriteBatch;
private final SpriteBatch textSpriteBatch;
public static GameRenderer instance;
private final Texture ceilingTexture;
private final Texture floorTexture;
public GameRenderer() {
instance = this;
camera = new OrthographicCamera();
textCamera = new OrthographicCamera();
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(camera.combined);
textShapeRenderer = new ShapeRenderer();
spriteBatch = new SpriteBatch();
textSpriteBatch = new SpriteBatch();
FileHandle fontFile = Gdx.files.internal("score.fnt");
FileHandle fontImageFile = Gdx.files.internal("score.png");
Texture texture = new Texture(fontImageFile);
texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
scoreFont = new BitmapFont(fontFile, new TextureRegion(texture), false);
birdRenderer = new BirdRenderer(spriteBatch);
obstacleRenderer = new ObstacleRenderer(spriteBatch);
ceilingTexture = new Texture(Gdx.files.internal("bricks.png"));
floorTexture = new Texture(Gdx.files.internal("stone.png"));
}
public void render(Game game) {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
birdRenderer.render(game.bird);
for (Obstacle obstacle : game.obstacles) {
obstacleRenderer.render(obstacle);
}
renderCeiling(game);
renderFloor(game);
spriteBatch.end();
renderScore(game);
}
private void renderScore(Game game) {
String scoreString = Integer.toString(game.score);
float width = scoreFont.getBounds(scoreString).width;
textSpriteBatch.begin();
scoreFont.draw(textSpriteBatch, scoreString, (textCamera.viewportWidth - width) / 2, 380f);
textSpriteBatch.end();
}
private void renderCeiling(Game game) {
float scrolled = game.ticks() * -Game.SCROLL_SPEED % 1;
for (; scrolled < Game.WIDTH; scrolled += 1) {
spriteBatch.draw(ceilingTexture, scrolled, Game.HEIGHT, 1, 1);
}
}
private void renderFloor(Game game) {
float scrolled = game.ticks() * -Game.SCROLL_SPEED % 1;
for (; scrolled < Game.WIDTH; scrolled += 1) {
spriteBatch.draw(floorTexture, scrolled, -1, 1, 1);
}
}
public void resize(int width, int height) {
camera.setToOrtho(false, Game.WIDTH, Game.WIDTH * height / (1.0f * width));
camera.translate(0, Game.HEIGHT + 1 - Game.WIDTH * height / (1.0f * width));
camera.update();
float textScale = width / 320.f;
textCamera.setToOrtho(false, width/textScale, height/textScale);
textCamera.translate(0, (Game.HEIGHT + 1 - Game.WIDTH * height / (1.0f * width)) * (width / Game.WIDTH) / textScale);
textCamera.update();
shapeRenderer.setProjectionMatrix(camera.combined);
spriteBatch.setProjectionMatrix(camera.combined);
textShapeRenderer.setProjectionMatrix(textCamera.combined);
textSpriteBatch.setProjectionMatrix(textCamera.combined);
}
public void renderStartText(String line1, String line2) {
float width1 = scoreFont.getBounds(line1).width;
float width2 = scoreFont.getBounds(line2).width;
float backgroundWidth = Math.max(width1, width2) + 40;
textShapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
textShapeRenderer.setColor(0, 0, 0, 0);
textShapeRenderer.rect(
(textCamera.viewportWidth - backgroundWidth) / 2,
30,
backgroundWidth,
140
);
textShapeRenderer.end();
textSpriteBatch.begin();
scoreFont.draw(textSpriteBatch, line1, (textCamera.viewportWidth - width1) / 2, 150f);
scoreFont.draw(textSpriteBatch, line2, (textCamera.viewportWidth - width2) / 2, 90f);
textSpriteBatch.end();
}
}
| mit |
alwx/react-native-photo-view | android/src/main/java/com/reactnative/photoview/PhotoView.java | 11099 | package com.reactnative.photoview;
import android.content.Context;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.AutoRotateDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.SystemClock;
import com.facebook.react.modules.fresco.ReactNetworkImageRequest;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.EventDispatcher;
import me.relex.photodraweeview.OnPhotoTapListener;
import me.relex.photodraweeview.OnScaleChangeListener;
import me.relex.photodraweeview.OnViewTapListener;
import me.relex.photodraweeview.PhotoDraweeView;
import javax.annotation.Nullable;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import static com.facebook.react.views.image.ReactImageView.REMOTE_IMAGE_FADE_DURATION_MS;
/**
* @author alwx (https://github.com/alwx)
* @version 1.0
*/
public class PhotoView extends PhotoDraweeView {
private Uri mUri;
private ReadableMap mHeaders;
private boolean mIsDirty;
private boolean mIsLocalImage;
private Drawable mLoadingImageDrawable;
private PipelineDraweeControllerBuilder mDraweeControllerBuilder;
private int mFadeDurationMs = -1;
private ControllerListener mControllerListener;
public PhotoView(Context context) {
super(context);
}
public void setSource(@Nullable ReadableMap source,
@NonNull ResourceDrawableIdHelper resourceDrawableIdHelper) {
mUri = null;
if (source != null) {
String uri = source.getString("uri");
try {
mUri = Uri.parse(uri);
// Verify scheme is set, so that relative uri (used by static resources) are not handled.
if (mUri.getScheme() == null) {
mUri = null;
}
if (source.hasKey("headers")) {
mHeaders = source.getMap("headers");
}
} catch (Exception e) {
// ignore malformed uri, then attempt to extract resource ID.
}
if (mUri == null) {
mUri = resourceDrawableIdHelper.getResourceDrawableUri(getContext(), uri);
mIsLocalImage = true;
} else {
mIsLocalImage = false;
}
}
mIsDirty = true;
}
public void setLoadingIndicatorSource(@Nullable String name,
ResourceDrawableIdHelper resourceDrawableIdHelper) {
Drawable drawable = resourceDrawableIdHelper.getResourceDrawable(getContext(), name);
mLoadingImageDrawable =
drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null;
mIsDirty = true;
}
public void setFadeDuration(int durationMs) {
mFadeDurationMs = durationMs;
// no worth marking as dirty if it already rendered..
}
public void setShouldNotifyLoadEvents(boolean shouldNotify) {
if (!shouldNotify) {
mControllerListener = null;
} else {
final EventDispatcher eventDispatcher = ((ReactContext) getContext())
.getNativeModule(UIManagerModule.class).getEventDispatcher();
mControllerListener = new BaseControllerListener<ImageInfo>() {
@Override
public void onSubmit(String id, Object callerContext) {
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_LOAD_START)
);
}
@Override
public void onFinalImageSet(
String id,
@Nullable final ImageInfo imageInfo,
@Nullable Animatable animatable) {
if (imageInfo != null) {
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_LOAD)
);
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_LOAD_END)
);
update(imageInfo.getWidth(), imageInfo.getHeight());
}
}
@Override
public void onFailure(String id, Throwable throwable) {
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_ERROR)
);
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_LOAD_END)
);
}
};
}
mIsDirty = true;
}
public void maybeUpdateView(@NonNull PipelineDraweeControllerBuilder builder) {
if (!mIsDirty) {
return;
}
GenericDraweeHierarchy hierarchy = getHierarchy();
if (mLoadingImageDrawable != null) {
hierarchy.setPlaceholderImage(mLoadingImageDrawable, ScalingUtils.ScaleType.CENTER);
}
hierarchy.setFadeDuration(
mFadeDurationMs >= 0
? mFadeDurationMs
: mIsLocalImage ? 0 : REMOTE_IMAGE_FADE_DURATION_MS);
ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(mUri)
.setAutoRotateEnabled(true).setResizeOptions(new ResizeOptions(getMaxTextureSize(), getMaxTextureSize()));
ImageRequest imageRequest = ReactNetworkImageRequest
.fromBuilderWithHeaders(imageRequestBuilder, mHeaders);
mDraweeControllerBuilder = builder;
mDraweeControllerBuilder.setImageRequest(imageRequest);
mDraweeControllerBuilder.setAutoPlayAnimations(true);
mDraweeControllerBuilder.setOldController(getController());
mDraweeControllerBuilder.setControllerListener(new BaseControllerListener<ImageInfo>() {
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
super.onFinalImageSet(id, imageInfo, animatable);
if (imageInfo == null) {
return;
}
update(imageInfo.getWidth(), imageInfo.getHeight());
}
});
if (mControllerListener != null) {
mDraweeControllerBuilder.setControllerListener(mControllerListener);
}
setController(mDraweeControllerBuilder.build());
setViewCallbacks();
mIsDirty = false;
}
private void setViewCallbacks() {
final EventDispatcher eventDispatcher = ((ReactContext) getContext())
.getNativeModule(UIManagerModule.class).getEventDispatcher();
setOnPhotoTapListener(new OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float x, float y) {
WritableMap scaleChange = Arguments.createMap();
scaleChange.putDouble("x", x);
scaleChange.putDouble("y", y);
scaleChange.putDouble("scale", PhotoView.this.getScale());
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_TAP).setExtras(scaleChange)
);
}
});
setOnScaleChangeListener(new OnScaleChangeListener() {
@Override
public void onScaleChange(float scaleFactor, float focusX, float focusY) {
WritableMap scaleChange = Arguments.createMap();
scaleChange.putDouble("scale", PhotoView.this.getScale());
scaleChange.putDouble("scaleFactor", scaleFactor);
scaleChange.putDouble("focusX", focusX);
scaleChange.putDouble("focusY", focusY);
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_SCALE).setExtras(scaleChange)
);
}
});
setOnViewTapListener(new OnViewTapListener() {
@Override
public void onViewTap(View view, float x, float y) {
WritableMap scaleChange = Arguments.createMap();
scaleChange.putDouble("x", x);
scaleChange.putDouble("y", y);
eventDispatcher.dispatchEvent(
new ImageEvent(getId(), ImageEvent.ON_VIEW_TAP).setExtras(scaleChange)
);
}
});
}
private int getMaxTextureSize() {
// Safe minimum default size
final int IMAGE_MAX_BITMAP_DIMENSION = 2048;
// Get EGL Display
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
// Initialise
int[] version = new int[2];
egl.eglInitialize(display, version);
// Query total number of configurations
int[] totalConfigurations = new int[1];
egl.eglGetConfigs(display, null, 0, totalConfigurations);
// Query actual list configurations
EGLConfig[] configurationsList = new EGLConfig[totalConfigurations[0]];
egl.eglGetConfigs(display, configurationsList, totalConfigurations[0], totalConfigurations);
int[] textureSize = new int[1];
int maximumTextureSize = 0;
// Iterate through all the configurations to located the maximum texture size
for (int i = 0; i < totalConfigurations[0]; i++) {
// Only need to check for width since opengl textures are always squared
egl.eglGetConfigAttrib(display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_WIDTH, textureSize);
// Keep track of the maximum texture size
if (maximumTextureSize < textureSize[0])
maximumTextureSize = textureSize[0];
}
// Release
egl.eglTerminate(display);
// Return largest texture size found, or default
return Math.max(maximumTextureSize, IMAGE_MAX_BITMAP_DIMENSION);
}
}
| mit |
avedensky/JavaRushTasks | 4.JavaCollections/src/com/javarush/task/task28/task2810/model/MoikrugStrategy.java | 4921 | package com.javarush.task.task28.task2810.model;
import com.javarush.task.task28.task2810.vo.Vacancy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Alexey on 10.05.2017.
*/
public class MoikrugStrategy implements Strategy {
//private static final String URL_FORMAT = "https://moikrug.ru/vacancies?q=java&page=2";
private static final String URL_FORMAT= "https://moikrug.ru/vacancies?q=java+%s&page=%d";
//private static final String URL_FORMAT = "http://javarush.ru/testdata/big28data2.html";
@Override
public List<Vacancy> getVacancies(String searchString)
{
List<Vacancy> Vacancies = new ArrayList<>();
int pageNum = 0;
Document doc = null;
while(true)
{
try {
doc = getDocument(searchString, pageNum);
} catch (IOException e) {
e.printStackTrace();
}
Elements vacancies = doc.getElementsByClass("job");
if (vacancies.size()==0) break;
for (Element element: vacancies)
{
if (element != null)
{
Vacancy vac = new Vacancy();
vac.setTitle(element.getElementsByAttributeValue("class", "title").text());
vac.setCompanyName(element.getElementsByAttributeValue("class", "company_name").text());
vac.setSiteName(URL_FORMAT);
vac.setUrl("https://moikrug.ru" + element.select("a[class=job_icon]").attr("href"));
String salary = element.getElementsByAttributeValue("class", "salary").text();
String city = element.getElementsByAttributeValue("class", "location").text();
vac.setSalary(salary.length()==0 ? "" : salary);
vac.setCity(city.length()==0 ? "" : city);
Vacancies.add(vac);
}
}
pageNum++;
}
return Vacancies;
}
/* @Override
public List<Vacancy> getVacancies(String searchString) {
List<Vacancy> vacancies = new ArrayList<>();
try {
int page = 0;
while (true) {
//System.out.println("--------------------- moikrug.ru ----------------------");
Document document = getDocument(searchString, page);
if (document == null) { break; }
Elements pageElements = document.select("[class=job ]");
pageElements.addAll(document.select("[class=job marked]"));
if (pageElements.size() == 0) { break; }
String siteName = "https://moikrug.ru";
for (Element pageElement : pageElements) {
Element title = pageElement.select("[class=title]").first();
Element companyName = pageElement.select("[class=company_name]").first();
Element salary = pageElement.select("[class=salary").first();
Element city = pageElement.select("[class=location]").first();
String url = siteName + title.select("a[href]").attr("href");
Vacancy vacancy = new Vacancy();
vacancy.setSiteName("https://moikrug.ru");
vacancy.setTitle(title.text());
vacancy.setCompanyName(companyName.text());
vacancy.setCity( (city != null) ? city.text() : "");
vacancy.setUrl(url);
vacancy.setSalary( (salary != null) ? salary.text() : "");
vacancies.add(vacancy);
}
//Next Page
int oldPage = page;
String nextPageHref = document.body().getElementsByAttributeValue("data-qa", "pager-next").attr("href");
if (nextPageHref.contains("page"))
page = Integer.parseInt(nextPageHref.substring(nextPageHref.indexOf("page=")).split("=")[1]);
else
break;
if (oldPage == page)
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return vacancies;
}*/
protected Document getDocument(String searchString, int page) throws IOException {
//String url = String.format("%s?q==%s&page=%s",URL_FORMAT, searchString, page);
String url = String.format(URL_FORMAT, searchString, page);
return Jsoup.connect(url)
.userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
.timeout(5000)
.referrer("http://google.ru")
.get();
}
}
| mit |
arnaudroger/SimpleFlatMapper | sfm-converter/src/test/java/org/simpleflatmapper/converter/test/ConverterServiceTestHelper.java | 1775 | package org.simpleflatmapper.converter.test;
import org.simpleflatmapper.converter.ContextFactory;
import org.simpleflatmapper.converter.ContextualConverter;
import org.simpleflatmapper.converter.ConverterService;
import org.simpleflatmapper.converter.DefaultContextFactoryBuilder;
import java.util.Arrays;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ConverterServiceTestHelper {
@SuppressWarnings("unchecked")
public static <I, O> void testConverter(I i, O o, Object... params) throws Exception {
testConverter(i, o, (Class<? super I>)i.getClass(), (Class<? super O>)o.getClass(), params);
}
public static <I, O> void testConverter(I i, O o, Class<I> classi, Class<O> classo, Object... params) throws Exception {
if (hasZoneId(params)) {
params = Arrays.copyOf(params, params.length + 1);
params[params.length - 1] = TimeZone.getTimeZone("UTC");
}
DefaultContextFactoryBuilder defaultContextFactoryBuilder = new DefaultContextFactoryBuilder();
final ContextualConverter<? super I, ? extends O> converter = ConverterService.getInstance().findConverter(classi, classo, defaultContextFactoryBuilder, params);
assertNotNull("Converter not null", converter);
ContextFactory contextFactory = defaultContextFactoryBuilder.build();
assertEquals(o, converter.convert(i, contextFactory.newContext()));
assertNotNull(converter.toString());
}
private static boolean hasZoneId(Object[] params) {
for(Object o : params) {
if (o instanceof TimeZone || o.getClass().getSimpleName().equals("ZoneId")) return true;
}
return false;
}
} | mit |
Sotanna/Quartz-Server | src/main/java/org/quartzpowered/network/session/Session.java | 4274 | /*
* This file is a component of Quartz Powered, this license makes sure any work
* associated with Quartz Powered, must follow the conditions of the license included.
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Quartz Powered
*
* 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.quartzpowered.network.session;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.name.Named;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.quartzpowered.engine.observe.Observer;
import org.quartzpowered.network.pipeline.CompressionHandler;
import org.quartzpowered.network.pipeline.HandlerFactory;
import org.quartzpowered.network.pipeline.NoopHandler;
import org.quartzpowered.network.protocol.Protocol;
import org.quartzpowered.network.protocol.ProtocolState;
import org.quartzpowered.network.protocol.packet.Packet;
import org.quartzpowered.network.session.attribute.AttributeRegistry;
import org.quartzpowered.network.session.attribute.AttributeStorage;
import org.quartzpowered.network.session.profile.PlayerProfile;
import javax.crypto.SecretKey;
import javax.inject.Inject;
import java.util.Random;
import static org.quartzpowered.network.protocol.ProtocolState.HANDSHAKE;
@ToString(of = {"channel", "profile"})
public class Session implements Observer {
@Inject private HandlerFactory handlerFactory;
@Inject private NoopHandler noopHandler;
@Inject @Assisted
@Getter
private Channel channel;
@Inject @Named("identifier")
@Getter @Setter
private Protocol protocol;
@Getter
private ProtocolState state = HANDSHAKE;
private static final Random random = new Random();
@Getter
private final String sessionId = Long.toString(random.nextLong(), 16).trim();
@Getter @Setter
private String verifyUsername;
@Getter @Setter
private byte[] verifyToken;
@Getter @Setter
private PlayerProfile profile;
@Getter
private final AttributeStorage attributes;
@Inject
public Session(AttributeRegistry attributeRegistry) {
this.attributes = attributeRegistry.get(this);
}
public ChannelFuture send(Packet packet) {
return channel.writeAndFlush(packet);
}
public void disconnect() {
channel.close();
}
public void disconnect(Packet packet) {
channel.writeAndFlush(packet)
.addListener(future -> channel.close());
}
public void enableEncryption(SecretKey sharedSecret) {
updatePipeline("encryption", handlerFactory.createEncryptionHandler(sharedSecret));
}
public void enableCompression(int threshold) {
updatePipeline("compression", new CompressionHandler(threshold));
}
public void disableCompression() {
updatePipeline("compression", noopHandler);
}
private void updatePipeline(String key, ChannelHandler handler) {
channel.pipeline().replace(key, key, handler);
}
public void setState(ProtocolState state) {
this.state = state;
}
@Override
public void observe(Packet packet) {
send(packet);
}
}
| mit |
BlitzKraig/AndroidResizer | src/androidresizer/AndroidResizer.java | 756 | /*
* 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 androidresizer;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.UIManager;
/**
*
* @author planys
*/
public class AndroidResizer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// System.out.println("TEST");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception ex) {
ex.printStackTrace();
}
new AResizerFrame().setVisible(true);
}
}
| mit |
abachar/collab | src/main/java/fr/abachar/collab/model/issue/RelationshipType.java | 158 | package fr.abachar.collab.model.issue;
/**
* Types of relationships
*/
public enum RelationshipType {
PARENT,
CHILD,
DUPLICATE,
RELATED;
}
| mit |
VerkhovtsovPavel/BSUIR_Labs | Labs/ADB/ADB-4/src/by/bsuir/verkpavel/adb/bank_server/ui/client/ShowView.java | 535 | package by.bsuir.verkpavel.adb.bank_server.ui.client;
import java.awt.Component;
import java.text.ParseException;
public class ShowView extends ActionView {
protected ShowView() throws ParseException {
super();
}
private static final long serialVersionUID = 5886161954641963633L;
@Override
protected void customActions() throws ParseException {
fillFields(currentClient);
for (Component component : mainPanel.getComponents()) {
component.setEnabled(false);
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/signalr/mgmt-v2020_05_01/src/main/java/com/microsoft/azure/management/signalr/v2020_05_01/implementation/package-info.java | 427 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
/**
* This package contains the implementation classes for SignalRManagementClient.
* REST API for Azure SignalR Service.
*/
package com.microsoft.azure.management.signalr.v2020_05_01.implementation;
| mit |
arifgit12/NearByService | NearByServiceAPI/src/main/java/com/nearby/app/models/Product.java | 2527 | package com.nearby.app.models;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.*;
import javax.validation.constraints.Min;
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
@NotEmpty (message = "The product name must not be null.")
private String productName;
private String productCategory;
private String productDescription;
@Min(value = 0, message = "The product price must no be less then zero.")
private double productPrice;
private String productCondition;
private String productStatus;
@Min(value = 0, message = "The product unit must not be less than zero.")
private int unitInStock;
private String productManufacturer;
@Transient
private MultipartFile productImage;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public MultipartFile getProductImage() {
return productImage;
}
public void setProductImage(MultipartFile productImage) {
this.productImage = productImage;
}
}
| mit |
idelpivnitskiy/JBattleCity | src/main/java/ua/pp/condor/jbattlecity/area/actions/ProjectilesTimerTask.java | 4115 | package ua.pp.condor.jbattlecity.area.actions;
import ua.pp.condor.jbattlecity.JBattleCity;
import ua.pp.condor.jbattlecity.area.Cell;
import ua.pp.condor.jbattlecity.area.MapState;
import ua.pp.condor.jbattlecity.tank.ProjectileState;
import ua.pp.condor.jbattlecity.utils.Images;
import ua.pp.condor.jbattlecity.utils.Sound;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
public class ProjectilesTimerTask extends TimerTask {
private final MapState mapState;
private final Cell[][] currentMap;
public ProjectilesTimerTask(MapState mapState) {
this.mapState = mapState;
currentMap = mapState.getCurrentMap();
}
@Override
public void run() {
int delta = 5;
final Map<Integer, ProjectileState> projectiles = mapState.getProjectilesMap();
Set<Integer> projectilesIds = projectiles.keySet();
for (Integer projectileId : projectilesIds) {
ProjectileState ps = projectiles.get(projectileId);
if (ps.getX() < Images.PROJECTILE_SIZE || ps.getX() > JBattleCity.WIDTH - Images.PROJECTILE_SIZE - delta
|| ps.getY() < Images.PROJECTILE_SIZE || ps.getY() > JBattleCity.HEIGHT - Images.PROJECTILE_SIZE - delta) {
ps.getParent().setHasProjectile(false);
projectiles.remove(projectileId);
continue;
}
int x = 0, y = 0;
int x1 = 0, y1 = 0;
int x2 = 0, y2 = 0;
int x3 = 0, y3 = 0;
switch (ps.getOrientation()) {
case UP: {
int newY = ps.getY() - delta;
x = ps.getX() / 10; y = newY / 10;
x1 = x - 1; y1 = y;
x2 = x - 2; y2 = y;
x3 = x + 1; y3 = y;
ps.setY(newY);
break;
}
case RIGHT: {
int newX = ps.getX() + delta;
x = newX / 10; y = ps.getY() / 10;
x1 = x; y1 = y - 1;
x2 = x; y2 = y - 2;
x3 = x; y3 = y + 1;
ps.setX(newX);
break;
}
case DOWN: {
int newY = ps.getY() + delta;
x = ps.getX() / 10; y = newY / 10;
x1 = x - 1; y1 = y;
x2 = x - 2; y2 = y;
x3 = x + 1; y3 = y;
ps.setY(newY);
break;
}
case LEFT: {
int newX = ps.getX() - delta;
x = newX / 10; y = ps.getY() / 10;
x1 = x; y1 = y - 1;
x2 = x; y2 = y - 2;
x3 = x; y3 = y + 1;
ps.setX(newX);
break;
}
}
boolean destroyed = false;
if (mapState.getCell(x, y) != Cell.empty || mapState.getCell(x1, y1) != Cell.empty) {
ps.getParent().setHasProjectile(false);
projectiles.remove(projectileId);
}
if (mapState.getCell(x, y) == Cell.base || mapState.getCell(x1, y1) == Cell.base) {
mapState.setGameOver();
}
if (mapState.getCell(x, y) == Cell.tank || mapState.getCell(x1, y1) == Cell.tank) {
mapState.destroyTank(x, y, x1, y1);
}
if (mapState.getCell(x, y) == Cell.wall) {
currentMap[x][y] = Cell.empty;
destroyed = true;
}
if (mapState.getCell(x1, y1) == Cell.wall) {
currentMap[x1][y1] = Cell.empty;
destroyed = true;
}
if (destroyed) {
if (mapState.getCell(x2, y2) == Cell.wall)
currentMap[x2][y2] = Cell.empty;
if (mapState.getCell(x3, y3) == Cell.wall)
currentMap[x3][y3] = Cell.empty;
Sound.getBrick().play();
}
}
}
}
| mit |
BeltranGomezUlises/machineAdminAPI | src/main/java/com/auth/daos/admin/DaoUsuario.java | 1804 | /*
* Copyright (C) 2017 Alonso --- alonso@kriblet.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.auth.daos.admin;
import com.auth.daos.commons.DaoSQLFacade;
import com.auth.entities.admin.Usuario;
import com.auth.entities.admin.UsuariosPerfil;
import com.auth.entities.admin.UsuariosPerfilPK;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author Alonso --- alonso@kriblet.com
*/
public class DaoUsuario extends DaoSQLFacade<Usuario, Integer> {
public DaoUsuario() {
super(Usuario.class, Integer.class);
}
public void registrarUsuario(Usuario nuevoUsuario, List<Integer> perfilesAsignar) {
EntityManager em = this.getEM();
em.getTransaction().begin();
em.persist(nuevoUsuario);
em.flush();
//generar relacion con los ids de los perfiles del usuario
UsuariosPerfil up;
for (Integer perfilId : perfilesAsignar) {
up = new UsuariosPerfil();
up.setHereda(Boolean.TRUE);
up.setUsuariosPerfilPK(new UsuariosPerfilPK(nuevoUsuario.getId(), perfilId));
em.persist(up);
}
em.getTransaction().commit();
}
}
| mit |
PrinceOfAmber/CyclicMagic | src/main/java/com/lothrazar/cyclic/net/PacketItemScroll.java | 1165 | package com.lothrazar.cyclic.net;
import java.util.function.Supplier;
import com.lothrazar.cyclic.item.enderbook.EnderBookItem;
import com.lothrazar.cyclic.registry.ItemRegistry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
public class PacketItemScroll extends PacketBaseCyclic {
private int slot;
private boolean isDown;
public PacketItemScroll(int slot, boolean isDown) {
this.slot = slot;
this.isDown = isDown;
}
public static void handle(PacketItemScroll message, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
ServerPlayer player = ctx.get().getSender();
player.getCooldowns().addCooldown(ItemRegistry.ENDER_BOOK.get(), 5);
EnderBookItem.scroll(player, message.slot, message.isDown);
});
message.done(ctx);
}
public static PacketItemScroll decode(FriendlyByteBuf buf) {
return new PacketItemScroll(buf.readInt(), buf.readBoolean());
}
public static void encode(PacketItemScroll msg, FriendlyByteBuf buf) {
buf.writeInt(msg.slot);
buf.writeBoolean(msg.isDown);
}
}
| mit |
simplity/examples | springIntegration/src/main/java/org/simplity/examples/springIntegration/dao/UserDAO.java | 1265 | package org.simplity.examples.springIntegration.dao;
import java.util.ArrayList;
import java.util.List;
import org.simplity.examples.springIntegration.model.User;
import org.springframework.stereotype.Service;
@Service("userDAO")
public class UserDAO {
private static List<User> userList;
{
userList = new ArrayList<User>();
userList.add(new User(101, "Dhoni", "Dhoni@gmail.com", "121-232-3435"));
userList.add(new User(201, "Virat", "Virat@gmail.com", "343-545-2345"));
userList.add(new User(301, "Raina", "Raina@gmail.com", "876-237-2987"));
}
public List<User> list() {
return userList;
}
public User get(Long id) {
for (User user : userList) {
if (user.getId().equals(id)) {
return user;
}
}
return null;
}
public User create(User user) {
user.setId((int) System.currentTimeMillis());
userList.add(user);
return user;
}
public Integer delete(Integer id) {
for (User u : userList) {
if (u.getId().equals(id)) {
userList.remove(u);
return id;
}
}
return null;
}
public User update(Long id, User user) {
for (User c : userList) {
if (c.getId().equals(id)) {
user.setId(c.getId());
userList.remove(c);
userList.add(user);
return user;
}
}
return null;
}
} | mit |
lucidfox/jpromises | src/main/java/org/lucidfox/jpromises/core/ResolveCallback.java | 1908 | /*
* Copyright 2014 Maia Everett <maia@lucidfox.org>
*
* 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.lucidfox.jpromises.core;
import org.lucidfox.jpromises.Promise;
/**
* A callback to be invoked when a {@link Promise} or arbitrary {@link Thenable} is resolved.
*
* @param <V> the value type of the promise the callback is being bound to via {@link Thenable#then}
* @param <R> the value type of the returned promise for chaining
*/
public interface ResolveCallback<V, R> {
/**
* Called when the promise (thenable) is resolved.
*
* @param value the value with which the promise is resolved
* @return the promise (thenable) to be chained after the current promise is resolved (optional)
* @throws Exception Signals that an error occurred when handling the result of the promise execution.
*/
Thenable<R> onResolve(V value) throws Exception;
}
| mit |
PCLuddite/baxshops | src/main/java/tbax/shops/Shop.java | 2210 | /*
* Copyright © 2012 Nathan Dinsmore and Sam Lazarus
* Modifications Copyright © Timothy Baxendale
*
* 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 tbax.shops;
import org.bukkit.Location;
import org.tbax.baxshops.BaxShop;
import org.tbax.baxshops.internal.serialization.states.StateLoader_00050;
import java.io.Serializable;
import java.util.ArrayList;
@Deprecated
public class Shop implements Serializable
{
private static final long serialVersionUID = 1L;
public static final int ITEMS_PER_PAGE = 7;
public String owner;
public Boolean isInfinite;
public ArrayList<ShopEntry> inventory;
public transient Location location;
public Shop() {
this.inventory = new ArrayList<>();
}
public BaxShop update(StateLoader_00050 stateLoader_00050)
{
org.tbax.baxshops.BaxShop baxShop = new org.tbax.baxshops.BaxShop(location);
baxShop.setFlagInfinite(isInfinite == null ? false : isInfinite);
baxShop.setOwner(stateLoader_00050.getPlayerSafe(null, owner));
for(ShopEntry entry : inventory) {
baxShop.add(entry.update(stateLoader_00050));
}
return baxShop;
}
}
| mit |
PizzaPastaRobottino/opencv-onboard | libraries/opencv/src/org/opencv/videoio/VideoWriter.java | 4993 |
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.videoio;
import org.opencv.core.Mat;
import org.opencv.core.Size;
// C++: class VideoWriter
//javadoc: VideoWriter
public class VideoWriter {
protected final long nativeObj;
protected VideoWriter(long addr) {
nativeObj = addr;
}
//
// C++: VideoWriter(String filename, int fourcc, double fps, Size frameSize, bool isColor = true)
//
//javadoc: VideoWriter::VideoWriter(filename, fourcc, fps, frameSize, isColor)
public VideoWriter(String filename, int fourcc, double fps, Size frameSize, boolean isColor) {
nativeObj = VideoWriter_0(filename, fourcc, fps, frameSize.width, frameSize.height, isColor);
return;
}
//javadoc: VideoWriter::VideoWriter(filename, fourcc, fps, frameSize)
public VideoWriter(String filename, int fourcc, double fps, Size frameSize) {
nativeObj = VideoWriter_1(filename, fourcc, fps, frameSize.width, frameSize.height);
return;
}
//
// C++: VideoWriter()
//
//javadoc: VideoWriter::VideoWriter()
public VideoWriter() {
nativeObj = VideoWriter_2();
return;
}
//
// C++: bool isOpened()
//
//javadoc: VideoWriter::isOpened()
public boolean isOpened() {
boolean retVal = isOpened_0(nativeObj);
return retVal;
}
//
// C++: bool open(String filename, int fourcc, double fps, Size frameSize, bool isColor = true)
//
//javadoc: VideoWriter::open(filename, fourcc, fps, frameSize, isColor)
public boolean open(String filename, int fourcc, double fps, Size frameSize, boolean isColor) {
boolean retVal = open_0(nativeObj, filename, fourcc, fps, frameSize.width, frameSize.height, isColor);
return retVal;
}
//javadoc: VideoWriter::open(filename, fourcc, fps, frameSize)
public boolean open(String filename, int fourcc, double fps, Size frameSize) {
boolean retVal = open_1(nativeObj, filename, fourcc, fps, frameSize.width, frameSize.height);
return retVal;
}
//
// C++: bool set(int propId, double value)
//
//javadoc: VideoWriter::set(propId, value)
public boolean set(int propId, double value) {
boolean retVal = set_0(nativeObj, propId, value);
return retVal;
}
//
// C++: double get(int propId)
//
//javadoc: VideoWriter::get(propId)
public double get(int propId) {
double retVal = get_0(nativeObj, propId);
return retVal;
}
//
// C++: static int fourcc(char c1, char c2, char c3, char c4)
//
//javadoc: VideoWriter::fourcc(c1, c2, c3, c4)
public static int fourcc(char c1, char c2, char c3, char c4) {
int retVal = fourcc_0(c1, c2, c3, c4);
return retVal;
}
//
// C++: void release()
//
//javadoc: VideoWriter::release()
public void release() {
release_0(nativeObj);
return;
}
//
// C++: void write(Mat image)
//
//javadoc: VideoWriter::write(image)
public void write(Mat image) {
write_0(nativeObj, image.nativeObj);
return;
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: VideoWriter(String filename, int fourcc, double fps, Size frameSize, bool isColor = true)
private static native long VideoWriter_0(String filename, int fourcc, double fps, double frameSize_width, double frameSize_height, boolean isColor);
private static native long VideoWriter_1(String filename, int fourcc, double fps, double frameSize_width, double frameSize_height);
// C++: VideoWriter()
private static native long VideoWriter_2();
// C++: bool isOpened()
private static native boolean isOpened_0(long nativeObj);
// C++: bool open(String filename, int fourcc, double fps, Size frameSize, bool isColor = true)
private static native boolean open_0(long nativeObj, String filename, int fourcc, double fps, double frameSize_width, double frameSize_height, boolean isColor);
private static native boolean open_1(long nativeObj, String filename, int fourcc, double fps, double frameSize_width, double frameSize_height);
// C++: bool set(int propId, double value)
private static native boolean set_0(long nativeObj, int propId, double value);
// C++: double get(int propId)
private static native double get_0(long nativeObj, int propId);
// C++: static int fourcc(char c1, char c2, char c3, char c4)
private static native int fourcc_0(char c1, char c2, char c3, char c4);
// C++: void release()
private static native void release_0(long nativeObj);
// C++: void write(Mat image)
private static native void write_0(long nativeObj, long image_nativeObj);
// native support for java finalize()
private static native void delete(long nativeObj);
}
| mit |
michaljonko/blog-examples | message-bus/src/main/java/pl/coffeepower/blog/messagebus/util/BasicService.java | 1298 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Michał Jonko
*
* 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 pl.coffeepower.blog.messagebus.util;
public interface BasicService {
void start() throws Exception;
void stop() throws Exception;
}
| mit |
xandelol/telecursoAndroid | TelecursoXandao/app/src/main/java/com/xandecompany/telecursoxandao/Movie.java | 718 | package com.xandecompany.telecursoxandao;
/**
* Created by Alexandre on 11.01.2017.
*/
public class Movie {
private String nome;
private int rating;
private int year;
public Movie(String nome, int rating, int year) {
this.nome = nome;
this.rating = rating;
this.year = year;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
| mit |
Barofioso/TeamSpeak-3-Java-API | src/main/java/com/github/theholywaffle/teamspeak3/api/event/TS3EventType.java | 1524 | package com.github.theholywaffle.teamspeak3.api.event;
/*
* #%L
* TeamSpeak 3 Java API
* %%
* Copyright (C) 2014 Bert De Geyter
* %%
* 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.
* #L%
*/
public enum TS3EventType {
SERVER("server"),
CHANNEL("channel"),
TEXT_SERVER("textserver"),
TEXT_CHANNEL("textchannel"),
TEXT_PRIVATE("textprivate");
private final String name;
TS3EventType(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
| mit |
prttstft/MaterialMensa | app/src/main/java/de/prttstft/materialmensa/model/restaurants/MensaForumPaderborn.java | 285 | package de.prttstft.materialmensa.model.restaurants;
import com.google.gson.annotations.SerializedName;
public class MensaForumPaderborn {
@SuppressWarnings("unused") @SerializedName("status") private String status;
public String getStatus() {
return status;
}
} | mit |
Krigu/bookstore | bookstore-web/src/main/java/org/books/presentation/bean/account/ChangePasswordBean.java | 1800 | package org.books.presentation.bean.account;
import org.books.util.MessageFactory;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import org.books.application.CustomerService;
import org.books.application.exception.CustomerNotFoundException;
/**
*
* @author tjd
*/
@RequestScoped
@Named("changePasswordBean")
public class ChangePasswordBean implements Serializable {
public static String PASSWORD_CHANGED_SUCCESSFUL = "org.books.presentation.bean.account.changepasswordbean.PASSWORD_CHANGED_SUCCESSFUL";
public static String PASSWORD_NOT_CHANGED = "org.books.presentation.bean.account.changepasswordbean.PASSWORD_NOT_CHANGED";
private static final Logger LOGGER = Logger.getLogger(ChangePasswordBean.class.getName());
private String newPassword;
@Inject
private CustomerBean customerBean;
@EJB
private CustomerService customerService;
/**
* Use this methode to update the password
* @return null - No navigation
*/
public String updatePassword() {
try {
customerService.changePassword(customerBean.getCustomer().getEmail(), newPassword);
MessageFactory.info(PASSWORD_CHANGED_SUCCESSFUL);
} catch (CustomerNotFoundException ex) {
//TODO update the message to CUSTOMER NOT FOUND
LOGGER.log(Level.SEVERE, "Customer not found", ex);
MessageFactory.info(PASSWORD_NOT_CHANGED);
}
return null;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getNewPassword() {
return newPassword;
}
}
| mit |
diirt/diirt | pvmanager/datasource/src/main/java/org/diirt/datasource/DesiredRateEvent.java | 1189 | /**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Represents an event after the rate is decoupled. The event groups multiple
* events of different types.
* <p>
* The class is thread-safe.
*
* @author carcassi
*/
class DesiredRateEvent {
enum Type {READ_CONNECTION, WRITE_CONNECTION, VALUE, READ_EXCEPTION, WRITE_EXCEPTION, WRITE_SUCCEEDED, WRITE_FAILED};
private final List<Type> types = new CopyOnWriteArrayList<>();
private volatile Exception writeException;
public List<Type> getTypes() {
return types;
}
public void addType(Type type) {
// TODO: may want to preserve ordering
if (!types.contains(type)) {
types.add(type);
}
}
public void addWriteFailed(Exception ex) {
if (writeException != null) {
throw new UnsupportedOperationException("Right now, only one failed write can be queued");
}
types.add(Type.WRITE_FAILED);
writeException = ex;
}
}
| mit |
kazocsaba/mesh | src/main/java/hu/kazocsaba/v3d/mesh/TriangleStrip.java | 939 | package hu.kazocsaba.v3d.mesh;
/**
* A mesh composed of triangle strips.
* @author Kazó Csaba
*/
public interface TriangleStrip extends TriangleMesh {
/**
* Returns the number of strips this mesh is composed of.
* @return the number of strips
*/
public int getStripCount();
/**
* Returns the points of the specified strip.
* @param index the index of the strip to return
* @return the points of the specified strip, containing at least three points. Each three consecutive
* points form a triangle (i.e. points (0, 1, 2), points (1, 2, 3) etc.).
* @throws IndexOutOfBoundsException if the index is invalid
*/
public PointList getStrip(int index);
/**
* Returns the number of points making up the specified strip.
* @param index the index of the strip
* @return the number of points in the strip
* @throws IndexOutOfBoundsException if the index is invalid
*/
public int getStripLength(int index);
}
| mit |
scen/Facepunch | app/src/main/java/com/stanleycen/facepunch/event/ThreadDataEvent.java | 436 | package com.stanleycen.facepunch.event;
import com.stanleycen.facepunch.model.fp.FPForum;
import com.stanleycen.facepunch.model.fp.FPThread;
/**
* Created by scen on 2/18/14.
*/
public class ThreadDataEvent {
public boolean success;
public FPThread thread;
public ThreadDataEvent() {}
public ThreadDataEvent(boolean success, FPThread thread) {
this.success = success;
this.thread = thread;
}
}
| mit |
fpeter8/lombok | src/core/lombok/eclipse/handlers/HandleBuilder.java | 39731 | /*
* Copyright (C) 2013-2018 The Project Lombok Authors.
*
* 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 lombok.eclipse.handlers;
import static lombok.eclipse.Eclipse.*;
import static lombok.core.handlers.HandlerUtil.*;
import static lombok.eclipse.handlers.EclipseHandlerUtil.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.Assignment;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.EqualExpression;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.FalseLiteral;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.IfStatement;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.OperatorIds;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import org.eclipse.jdt.internal.compiler.ast.TrueLiteral;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.ast.UnaryExpression;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.MethodScope;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import org.mangosdk.spi.ProviderFor;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Builder.ObtainVia;
import lombok.ConfigurationKeys;
import lombok.Singular;
import lombok.ToString;
import lombok.core.AST.Kind;
import lombok.core.handlers.HandlerUtil;
import lombok.core.handlers.InclusionExclusionUtils.Included;
import lombok.core.AnnotationValues;
import lombok.core.HandlerPriority;
import lombok.eclipse.Eclipse;
import lombok.eclipse.EclipseAnnotationHandler;
import lombok.eclipse.EclipseNode;
import lombok.eclipse.handlers.EclipseSingularsRecipes.EclipseSingularizer;
import lombok.eclipse.handlers.EclipseSingularsRecipes.SingularData;
import lombok.eclipse.handlers.HandleConstructor.SkipIfConstructorExists;
import lombok.experimental.NonFinal;
@ProviderFor(EclipseAnnotationHandler.class)
@HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes.
public class HandleBuilder extends EclipseAnnotationHandler<Builder> {
private HandleConstructor handleConstructor = new HandleConstructor();
private static final char[] CLEAN_FIELD_NAME = "$lombokUnclean".toCharArray();
private static final char[] CLEAN_METHOD_NAME = "$lombokClean".toCharArray();
private static final boolean toBoolean(Object expr, boolean defaultValue) {
if (expr == null) return defaultValue;
if (expr instanceof FalseLiteral) return false;
if (expr instanceof TrueLiteral) return true;
return ((Boolean) expr).booleanValue();
}
private static class BuilderFieldData {
Annotation[] annotations;
TypeReference type;
char[] rawName;
char[] name;
char[] nameOfDefaultProvider;
char[] nameOfSetFlag;
SingularData singularData;
ObtainVia obtainVia;
EclipseNode obtainViaNode;
EclipseNode originalFieldNode;
List<EclipseNode> createdFields = new ArrayList<EclipseNode>();
}
private static boolean equals(String a, char[] b) {
if (a.length() != b.length) return false;
for (int i = 0; i < b.length; i++) {
if (a.charAt(i) != b[i]) return false;
}
return true;
}
private static boolean equals(String a, char[][] b) {
if (a == null || a.isEmpty()) return b.length == 0;
String[] aParts = a.split("\\.");
if (aParts.length != b.length) return false;
for (int i = 0; i < b.length; i++) {
if (!equals(aParts[i], b[i])) return false;
}
return true;
}
private static final char[] DEFAULT_PREFIX = {'$', 'd', 'e', 'f', 'a', 'u', 'l', 't', '$'};
private static final char[] SET_PREFIX = {'$', 's', 'e', 't'};
private static final char[] prefixWith(char[] prefix, char[] name) {
char[] out = new char[prefix.length + name.length];
System.arraycopy(prefix, 0, out, 0, prefix.length);
System.arraycopy(name, 0, out, prefix.length, name.length);
return out;
}
@Override public void handle(AnnotationValues<Builder> annotation, Annotation ast, EclipseNode annotationNode) {
handleFlagUsage(annotationNode, ConfigurationKeys.BUILDER_FLAG_USAGE, "@Builder");
long p = (long) ast.sourceStart << 32 | ast.sourceEnd;
Builder builderInstance = annotation.getInstance();
// These exist just to support the 'old' lombok.experimental.Builder, which had these properties. lombok.Builder no longer has them.
boolean fluent = toBoolean(annotation.getActualExpression("fluent"), true);
boolean chain = toBoolean(annotation.getActualExpression("chain"), true);
String builderMethodName = builderInstance.builderMethodName();
String buildMethodName = builderInstance.buildMethodName();
String builderClassName = builderInstance.builderClassName();
String toBuilderMethodName = "toBuilder";
boolean toBuilder = builderInstance.toBuilder();
List<char[]> typeArgsForToBuilder = null;
if (builderMethodName == null) builderMethodName = "builder";
if (buildMethodName == null) builderMethodName = "build";
if (builderClassName == null) builderClassName = "";
if (!checkName("builderMethodName", builderMethodName, annotationNode)) return;
if (!checkName("buildMethodName", buildMethodName, annotationNode)) return;
if (!builderClassName.isEmpty()) {
if (!checkName("builderClassName", builderClassName, annotationNode)) return;
}
EclipseNode parent = annotationNode.up();
List<BuilderFieldData> builderFields = new ArrayList<BuilderFieldData>();
TypeReference returnType;
TypeParameter[] typeParams;
TypeReference[] thrownExceptions;
char[] nameOfStaticBuilderMethod;
EclipseNode tdParent;
EclipseNode fillParametersFrom = parent.get() instanceof AbstractMethodDeclaration ? parent : null;
boolean addCleaning = false;
boolean isStatic = true;
if (parent.get() instanceof TypeDeclaration) {
tdParent = parent;
TypeDeclaration td = (TypeDeclaration) tdParent.get();
List<EclipseNode> allFields = new ArrayList<EclipseNode>();
boolean valuePresent = (hasAnnotation(lombok.Value.class, parent) || hasAnnotation("lombok.experimental.Value", parent));
for (EclipseNode fieldNode : HandleConstructor.findAllFields(tdParent, true)) {
FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
EclipseNode isDefault = findAnnotation(Builder.Default.class, fieldNode);
boolean isFinal = ((fd.modifiers & ClassFileConstants.AccFinal) != 0) || (valuePresent && !hasAnnotation(NonFinal.class, fieldNode));
Annotation[] copyableAnnotations = findCopyableAnnotations(fieldNode);
BuilderFieldData bfd = new BuilderFieldData();
bfd.rawName = fieldNode.getName().toCharArray();
bfd.name = removePrefixFromField(fieldNode);
bfd.annotations = copyAnnotations(fd, copyableAnnotations);
bfd.type = fd.type;
bfd.singularData = getSingularData(fieldNode, ast);
bfd.originalFieldNode = fieldNode;
if (bfd.singularData != null && isDefault != null) {
isDefault.addError("@Builder.Default and @Singular cannot be mixed.");
isDefault = null;
}
if (fd.initialization == null && isDefault != null) {
isDefault.addWarning("@Builder.Default requires an initializing expression (' = something;').");
isDefault = null;
}
if (fd.initialization != null && isDefault == null) {
if (isFinal) continue;
fieldNode.addWarning("@Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.");
}
if (isDefault != null) {
bfd.nameOfDefaultProvider = prefixWith(DEFAULT_PREFIX, bfd.name);
bfd.nameOfSetFlag = prefixWith(bfd.name, SET_PREFIX);
MethodDeclaration md = generateDefaultProvider(bfd.nameOfDefaultProvider, td.typeParameters, fieldNode, ast);
if (md != null) injectMethod(tdParent, md);
}
addObtainVia(bfd, fieldNode);
builderFields.add(bfd);
allFields.add(fieldNode);
}
handleConstructor.generateConstructor(tdParent, AccessLevel.PACKAGE, allFields, false, null, SkipIfConstructorExists.I_AM_BUILDER,
Collections.<Annotation>emptyList(), annotationNode);
returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p);
typeParams = td.typeParameters;
thrownExceptions = null;
nameOfStaticBuilderMethod = null;
if (builderClassName.isEmpty()) builderClassName = new String(td.name) + "Builder";
} else if (parent.get() instanceof ConstructorDeclaration) {
ConstructorDeclaration cd = (ConstructorDeclaration) parent.get();
if (cd.typeParameters != null && cd.typeParameters.length > 0) {
annotationNode.addError("@Builder is not supported on constructors with constructor type parameters.");
return;
}
tdParent = parent.up();
TypeDeclaration td = (TypeDeclaration) tdParent.get();
returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p);
typeParams = td.typeParameters;
thrownExceptions = cd.thrownExceptions;
nameOfStaticBuilderMethod = null;
if (builderClassName.isEmpty()) builderClassName = new String(cd.selector) + "Builder";
} else if (parent.get() instanceof MethodDeclaration) {
MethodDeclaration md = (MethodDeclaration) parent.get();
tdParent = parent.up();
isStatic = md.isStatic();
if (toBuilder) {
final String TO_BUILDER_NOT_SUPPORTED = "@Builder(toBuilder=true) is only supported if you return your own type.";
char[] token;
char[][] pkg = null;
if (md.returnType.dimensions() > 0) {
annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
return;
}
if (md.returnType instanceof SingleTypeReference) {
token = ((SingleTypeReference) md.returnType).token;
} else if (md.returnType instanceof QualifiedTypeReference) {
pkg = ((QualifiedTypeReference) md.returnType).tokens;
token = pkg[pkg.length];
char[][] pkg_ = new char[pkg.length - 1][];
System.arraycopy(pkg, 0, pkg_, 0, pkg_.length);
pkg = pkg_;
} else {
annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
return;
}
if (pkg != null && !equals(parent.getPackageDeclaration(), pkg)) {
annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
return;
}
if (tdParent == null || !equals(tdParent.getName(), token)) {
annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
return;
}
TypeParameter[] tpOnType = ((TypeDeclaration) tdParent.get()).typeParameters;
TypeParameter[] tpOnMethod = md.typeParameters;
TypeReference[][] tpOnRet_ = null;
if (md.returnType instanceof ParameterizedSingleTypeReference) {
tpOnRet_ = new TypeReference[1][];
tpOnRet_[0] = ((ParameterizedSingleTypeReference) md.returnType).typeArguments;
} else if (md.returnType instanceof ParameterizedQualifiedTypeReference) {
tpOnRet_ = ((ParameterizedQualifiedTypeReference) md.returnType).typeArguments;
}
if (tpOnRet_ != null) for (int i = 0; i < tpOnRet_.length - 1; i++) {
if (tpOnRet_[i] != null && tpOnRet_[i].length > 0) {
annotationNode.addError("@Builder(toBuilder=true) is not supported if returning a type with generics applied to an intermediate.");
return;
}
}
TypeReference[] tpOnRet = tpOnRet_ == null ? null : tpOnRet_[tpOnRet_.length - 1];
typeArgsForToBuilder = new ArrayList<char[]>();
// Every typearg on this method needs to be found in the return type, but the reverse is not true.
// We also need to 'map' them.
if (tpOnMethod != null) for (TypeParameter onMethod : tpOnMethod) {
int pos = -1;
if (tpOnRet != null) for (int i = 0; i < tpOnRet.length; i++) {
if (tpOnRet[i].getClass() != SingleTypeReference.class) continue;
if (!Arrays.equals(((SingleTypeReference) tpOnRet[i]).token, onMethod.name)) continue;
pos = i;
}
if (pos == -1 || tpOnType == null || tpOnType.length <= pos) {
annotationNode.addError("@Builder(toBuilder=true) requires that each type parameter on the static method is part of the typeargs of the return value. Type parameter " + new String(onMethod.name) + " is not part of the return type.");
return;
}
typeArgsForToBuilder.add(tpOnType[pos].name);
}
}
returnType = copyType(md.returnType, ast);
typeParams = md.typeParameters;
thrownExceptions = md.thrownExceptions;
nameOfStaticBuilderMethod = md.selector;
if (builderClassName.isEmpty()) {
char[] token;
if (md.returnType instanceof QualifiedTypeReference) {
char[][] tokens = ((QualifiedTypeReference) md.returnType).tokens;
token = tokens[tokens.length - 1];
} else if (md.returnType instanceof SingleTypeReference) {
token = ((SingleTypeReference) md.returnType).token;
if (!(md.returnType instanceof ParameterizedSingleTypeReference) && typeParams != null) {
for (TypeParameter tp : typeParams) {
if (Arrays.equals(tp.name, token)) {
annotationNode.addError("@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type.");
return;
}
}
}
} else {
annotationNode.addError("Unexpected kind of return type on annotated method. Specify 'builderClassName' to solve this problem.");
return;
}
if (Character.isLowerCase(token[0])) {
char[] newToken = new char[token.length];
System.arraycopy(token, 1, newToken, 1, token.length - 1);
newToken[0] = Character.toTitleCase(token[0]);
token = newToken;
}
builderClassName = new String(token) + "Builder";
}
} else {
annotationNode.addError("@Builder is only supported on types, constructors, and methods.");
return;
}
if (fillParametersFrom != null) {
for (EclipseNode param : fillParametersFrom.down()) {
if (param.getKind() != Kind.ARGUMENT) continue;
BuilderFieldData bfd = new BuilderFieldData();
Argument arg = (Argument) param.get();
Annotation[] copyableAnnotations = findCopyableAnnotations(param);
bfd.rawName = arg.name;
bfd.name = arg.name;
bfd.annotations = copyAnnotations(arg, copyableAnnotations);
bfd.type = arg.type;
bfd.singularData = getSingularData(param, ast);
bfd.originalFieldNode = param;
addObtainVia(bfd, param);
builderFields.add(bfd);
}
}
EclipseNode builderType = findInnerClass(tdParent, builderClassName);
if (builderType == null) {
builderType = makeBuilderClass(isStatic, tdParent, builderClassName, typeParams, ast);
} else {
TypeDeclaration builderTypeDeclaration = (TypeDeclaration) builderType.get();
if (isStatic && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) == 0) {
annotationNode.addError("Existing Builder must be a static inner class.");
return;
} else if (!isStatic && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) != 0) {
annotationNode.addError("Existing Builder must be a non-static inner class.");
return;
}
sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode);
/* generate errors for @Singular BFDs that have one already defined node. */ {
for (BuilderFieldData bfd : builderFields) {
SingularData sd = bfd.singularData;
if (sd == null) continue;
EclipseSingularizer singularizer = sd.getSingularizer();
if (singularizer == null) continue;
if (singularizer.checkForAlreadyExistingNodesAndGenerateError(builderType, sd)) {
bfd.singularData = null;
}
}
}
}
for (BuilderFieldData bfd : builderFields) {
if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
if (bfd.singularData.getSingularizer().requiresCleaning()) {
addCleaning = true;
break;
}
}
if (bfd.obtainVia != null) {
if (bfd.obtainVia.field().isEmpty() == bfd.obtainVia.method().isEmpty()) {
bfd.obtainViaNode.addError("The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\").");
return;
}
if (bfd.obtainVia.method().isEmpty() && bfd.obtainVia.isStatic()) {
bfd.obtainViaNode.addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set.");
return;
}
}
}
generateBuilderFields(builderType, builderFields, ast);
if (addCleaning) {
FieldDeclaration cleanDecl = new FieldDeclaration(CLEAN_FIELD_NAME, 0, -1);
cleanDecl.declarationSourceEnd = -1;
cleanDecl.modifiers = ClassFileConstants.AccPrivate;
cleanDecl.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
injectFieldAndMarkGenerated(builderType, cleanDecl);
}
if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) {
ConstructorDeclaration cd = HandleConstructor.createConstructor(
AccessLevel.PACKAGE, builderType, Collections.<EclipseNode>emptyList(), false,
annotationNode, Collections.<Annotation>emptyList());
if (cd != null) injectMethod(builderType, cd);
}
for (BuilderFieldData bfd : builderFields) {
makeSetterMethodsForBuilder(builderType, bfd, annotationNode, fluent, chain);
}
if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) {
MethodDeclaration md = generateBuildMethod(tdParent, isStatic, buildMethodName, nameOfStaticBuilderMethod, returnType, builderFields, builderType, thrownExceptions, addCleaning, ast);
if (md != null) injectMethod(builderType, md);
}
if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
List<Included<EclipseNode, ToString.Include>> fieldNodes = new ArrayList<Included<EclipseNode, ToString.Include>>();
for (BuilderFieldData bfd : builderFields) {
for (EclipseNode f : bfd.createdFields) {
fieldNodes.add(new Included<EclipseNode, ToString.Include>(f, null, true));
}
}
MethodDeclaration md = HandleToString.createToString(builderType, fieldNodes, true, false, ast, FieldAccess.ALWAYS_FIELD);
if (md != null) injectMethod(builderType, md);
}
if (addCleaning) {
MethodDeclaration cleanMethod = generateCleanMethod(builderFields, builderType, ast);
if (cleanMethod != null) injectMethod(builderType, cleanMethod);
}
if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) {
MethodDeclaration md = generateBuilderMethod(isStatic, builderMethodName, builderClassName, tdParent, typeParams, ast);
if (md != null) injectMethod(tdParent, md);
}
if (toBuilder) switch (methodExists(toBuilderMethodName, tdParent, 0)) {
case EXISTS_BY_USER:
annotationNode.addWarning("Not generating toBuilder() as it already exists.");
break;
case NOT_EXISTS:
TypeParameter[] tps = typeParams;
if (typeArgsForToBuilder != null) {
tps = new TypeParameter[typeArgsForToBuilder.size()];
for (int i = 0; i < tps.length; i++) {
tps[i] = new TypeParameter();
tps[i].name = typeArgsForToBuilder.get(i);
}
}
MethodDeclaration md = generateToBuilderMethod(toBuilderMethodName, builderClassName, tdParent, tps, builderFields, fluent, ast);
if (md != null) injectMethod(tdParent, md);
}
}
private static final char[] EMPTY_LIST = "emptyList".toCharArray();
private MethodDeclaration generateToBuilderMethod(String methodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, List<BuilderFieldData> builderFields, boolean fluent, ASTNode source) {
// return new ThingieBuilder<A, B>().setA(this.a).setB(this.b);
int pS = source.sourceStart, pE = source.sourceEnd;
long p = (long) pS << 32 | pE;
MethodDeclaration out = new MethodDeclaration(
((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.selector = methodName.toCharArray();
out.modifiers = ClassFileConstants.AccPublic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
AllocationExpression invoke = new AllocationExpression();
invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
Expression receiver = invoke;
for (BuilderFieldData bfd : builderFields) {
char[] setterName = fluent ? bfd.name : HandlerUtil.buildAccessorName("set", new String(bfd.name)).toCharArray();
MessageSend ms = new MessageSend();
Expression[] tgt = new Expression[bfd.singularData == null ? 1 : 2];
if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) {
char[] fieldName = bfd.obtainVia == null ? bfd.rawName : bfd.obtainVia.field().toCharArray();
for (int i = 0; i < tgt.length; i++) {
FieldReference fr = new FieldReference(fieldName, 0);
fr.receiver = new ThisReference(0, 0);
tgt[i] = fr;
}
} else {
String obtainName = bfd.obtainVia.method();
boolean obtainIsStatic = bfd.obtainVia.isStatic();
for (int i = 0; i < tgt.length; i++) {
MessageSend obtainExpr = new MessageSend();
obtainExpr.receiver = obtainIsStatic ? new SingleNameReference(type.getName().toCharArray(), 0) : new ThisReference(0, 0);
obtainExpr.selector = obtainName.toCharArray();
if (obtainIsStatic) obtainExpr.arguments = new Expression[] {new ThisReference(0, 0)};
tgt[i] = obtainExpr;
}
}
if (bfd.singularData == null) {
ms.arguments = tgt;
} else {
Expression ifNull = new EqualExpression(tgt[0], new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL);
MessageSend emptyList = new MessageSend();
emptyList.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Collections".toCharArray());
emptyList.selector = EMPTY_LIST;
emptyList.typeArguments = copyTypes(bfd.singularData.getTypeArgs().toArray(new TypeReference[0]));
ms.arguments = new Expression[] {new ConditionalExpression(ifNull, emptyList, tgt[1])};
}
ms.receiver = receiver;
ms.selector = setterName;
receiver = ms;
}
out.statements = new Statement[] {new ReturnStatement(receiver, pS, pE)};
out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
return out;
}
private MethodDeclaration generateCleanMethod(List<BuilderFieldData> builderFields, EclipseNode builderType, ASTNode source) {
List<Statement> statements = new ArrayList<Statement>();
for (BuilderFieldData bfd : builderFields) {
if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, builderType, statements);
}
}
FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0);
thisUnclean.receiver = new ThisReference(0, 0);
statements.add(new Assignment(thisUnclean, new FalseLiteral(0, 0), 0));
MethodDeclaration decl = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
decl.selector = CLEAN_METHOD_NAME;
decl.modifiers = ClassFileConstants.AccPrivate;
decl.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
decl.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
decl.statements = statements.toArray(new Statement[0]);
decl.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
return decl;
}
public MethodDeclaration generateBuildMethod(EclipseNode tdParent, boolean isStatic, String name, char[] staticName, TypeReference returnType, List<BuilderFieldData> builderFields, EclipseNode type, TypeReference[] thrownExceptions, boolean addCleaning, ASTNode source) {
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
List<Statement> statements = new ArrayList<Statement>();
if (addCleaning) {
FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0);
thisUnclean.receiver = new ThisReference(0, 0);
Expression notClean = new UnaryExpression(thisUnclean, OperatorIds.NOT);
MessageSend invokeClean = new MessageSend();
invokeClean.selector = CLEAN_METHOD_NAME;
statements.add(new IfStatement(notClean, invokeClean, 0, 0));
}
for (BuilderFieldData bfd : builderFields) {
if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
bfd.singularData.getSingularizer().appendBuildCode(bfd.singularData, type, statements, bfd.name, "this");
}
}
List<Expression> args = new ArrayList<Expression>();
for (BuilderFieldData bfd : builderFields) {
if (bfd.nameOfSetFlag != null) {
MessageSend inv = new MessageSend();
inv.sourceStart = source.sourceStart;
inv.sourceEnd = source.sourceEnd;
inv.receiver = new SingleNameReference(((TypeDeclaration) tdParent.get()).name, 0L);
inv.selector = bfd.nameOfDefaultProvider;
inv.typeArguments = typeParameterNames(((TypeDeclaration) type.get()).typeParameters);
args.add(new ConditionalExpression(
new SingleNameReference(bfd.nameOfSetFlag, 0L),
new SingleNameReference(bfd.name, 0L),
inv));
} else {
args.add(new SingleNameReference(bfd.name, 0L));
}
}
if (addCleaning) {
FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0);
thisUnclean.receiver = new ThisReference(0, 0);
statements.add(new Assignment(thisUnclean, new TrueLiteral(0, 0), 0));
}
out.modifiers = ClassFileConstants.AccPublic;
out.selector = name.toCharArray();
out.thrownExceptions = copyTypes(thrownExceptions);
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
out.returnType = returnType;
if (staticName == null) {
AllocationExpression allocationStatement = new AllocationExpression();
allocationStatement.type = copyType(out.returnType);
allocationStatement.arguments = args.isEmpty() ? null : args.toArray(new Expression[args.size()]);
statements.add(new ReturnStatement(allocationStatement, 0, 0));
} else {
MessageSend invoke = new MessageSend();
invoke.selector = staticName;
if (isStatic)
invoke.receiver = new SingleNameReference(type.up().getName().toCharArray(), 0);
else
invoke.receiver = new QualifiedThisReference(new SingleTypeReference(type.up().getName().toCharArray(), 0) , 0, 0);
invoke.typeArguments = typeParameterNames(((TypeDeclaration) type.get()).typeParameters);
invoke.arguments = args.isEmpty() ? null : args.toArray(new Expression[args.size()]);
if (returnType instanceof SingleTypeReference && Arrays.equals(TypeConstants.VOID, ((SingleTypeReference) returnType).token)) {
statements.add(invoke);
} else {
statements.add(new ReturnStatement(invoke, 0, 0));
}
}
out.statements = statements.isEmpty() ? null : statements.toArray(new Statement[statements.size()]);
out.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
return out;
}
private TypeReference[] typeParameterNames(TypeParameter[] typeParameters) {
if (typeParameters == null) return null;
TypeReference[] trs = new TypeReference[typeParameters.length];
for (int i = 0; i < trs.length; i++) {
trs[i] = new SingleTypeReference(typeParameters[i].name, 0);
}
return trs;
}
public static MethodDeclaration generateDefaultProvider(char[] methodName, TypeParameter[] typeParameters, EclipseNode fieldNode, ASTNode source) {
int pS = source.sourceStart, pE = source.sourceEnd;
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) fieldNode.top().get()).compilationResult);
out.typeParameters = copyTypeParams(typeParameters, source);
out.selector = methodName;
out.modifiers = ClassFileConstants.AccPrivate | ClassFileConstants.AccStatic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
out.returnType = copyType(fd.type, source);
out.statements = new Statement[] {new ReturnStatement(fd.initialization, pS, pE)};
fd.initialization = null;
out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) fieldNode.up().get()).scope);
return out;
}
public MethodDeclaration generateBuilderMethod(boolean isStatic, String builderMethodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) {
int pS = source.sourceStart, pE = source.sourceEnd;
long p = (long) pS << 32 | pE;
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.selector = builderMethodName.toCharArray();
out.modifiers = ClassFileConstants.AccPublic;
if (isStatic) out.modifiers |= ClassFileConstants.AccStatic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
out.typeParameters = copyTypeParams(typeParams, source);
AllocationExpression invoke = new AllocationExpression();
invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
out.statements = new Statement[] {new ReturnStatement(invoke, pS, pE)};
out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
return out;
}
public void generateBuilderFields(EclipseNode builderType, List<BuilderFieldData> builderFields, ASTNode source) {
List<EclipseNode> existing = new ArrayList<EclipseNode>();
for (EclipseNode child : builderType.down()) {
if (child.getKind() == Kind.FIELD) existing.add(child);
}
for (BuilderFieldData bfd : builderFields) {
if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
bfd.createdFields.addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType));
} else {
EclipseNode field = null, setFlag = null;
for (EclipseNode exists : existing) {
char[] n = ((FieldDeclaration) exists.get()).name;
if (Arrays.equals(n, bfd.name)) field = exists;
if (bfd.nameOfSetFlag != null && Arrays.equals(n, bfd.nameOfSetFlag)) setFlag = exists;
}
if (field == null) {
FieldDeclaration fd = new FieldDeclaration(bfd.name, 0, 0);
fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
fd.modifiers = ClassFileConstants.AccPrivate;
fd.type = copyType(bfd.type);
fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
field = injectFieldAndMarkGenerated(builderType, fd);
}
if (setFlag == null && bfd.nameOfSetFlag != null) {
FieldDeclaration fd = new FieldDeclaration(bfd.nameOfSetFlag, 0, 0);
fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
fd.modifiers = ClassFileConstants.AccPrivate;
fd.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
injectFieldAndMarkGenerated(builderType, fd);
}
bfd.createdFields.add(field);
}
}
}
private static final AbstractMethodDeclaration[] EMPTY = {};
public void makeSetterMethodsForBuilder(EclipseNode builderType, BuilderFieldData bfd, EclipseNode sourceNode, boolean fluent, boolean chain) {
boolean deprecate = isFieldDeprecated(bfd.originalFieldNode);
if (bfd.singularData == null || bfd.singularData.getSingularizer() == null) {
makeSimpleSetterMethodForBuilder(builderType, deprecate, bfd.createdFields.get(0), bfd.nameOfSetFlag, sourceNode, fluent, chain, bfd.annotations);
} else {
bfd.singularData.getSingularizer().generateMethods(bfd.singularData, deprecate, builderType, fluent, chain);
}
}
private void makeSimpleSetterMethodForBuilder(EclipseNode builderType, boolean deprecate, EclipseNode fieldNode, char[] nameOfSetFlag, EclipseNode sourceNode, boolean fluent, boolean chain, Annotation[] annotations) {
TypeDeclaration td = (TypeDeclaration) builderType.get();
AbstractMethodDeclaration[] existing = td.methods;
if (existing == null) existing = EMPTY;
int len = existing.length;
FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
char[] name = fd.name;
for (int i = 0; i < len; i++) {
if (!(existing[i] instanceof MethodDeclaration)) continue;
char[] existingName = existing[i].selector;
if (Arrays.equals(name, existingName) && !isTolerate(fieldNode, existing[i])) return;
}
String setterName = fluent ? fieldNode.getName() : HandlerUtil.buildAccessorName("set", fieldNode.getName());
MethodDeclaration setter = HandleSetter.createSetter(td, deprecate, fieldNode, setterName, nameOfSetFlag, chain, ClassFileConstants.AccPublic,
sourceNode, Collections.<Annotation>emptyList(), annotations != null ? Arrays.asList(copyAnnotations(sourceNode.get(), annotations)) : Collections.<Annotation>emptyList());
injectMethod(builderType, setter);
}
public EclipseNode findInnerClass(EclipseNode parent, String name) {
char[] c = name.toCharArray();
for (EclipseNode child : parent.down()) {
if (child.getKind() != Kind.TYPE) continue;
TypeDeclaration td = (TypeDeclaration) child.get();
if (Arrays.equals(td.name, c)) return child;
}
return null;
}
public EclipseNode makeBuilderClass(boolean isStatic, EclipseNode tdParent, String builderClassName, TypeParameter[] typeParams, ASTNode source) {
TypeDeclaration parent = (TypeDeclaration) tdParent.get();
TypeDeclaration builder = new TypeDeclaration(parent.compilationResult);
builder.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
builder.modifiers |= ClassFileConstants.AccPublic;
if (isStatic) builder.modifiers |= ClassFileConstants.AccStatic;
builder.typeParameters = copyTypeParams(typeParams, source);
builder.name = builderClassName.toCharArray();
builder.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
return injectType(tdParent, builder);
}
private void addObtainVia(BuilderFieldData bfd, EclipseNode node) {
for (EclipseNode child : node.down()) {
if (!annotationTypeMatches(ObtainVia.class, child)) continue;
AnnotationValues<ObtainVia> ann = createAnnotation(ObtainVia.class, child);
bfd.obtainVia = ann.getInstance();
bfd.obtainViaNode = child;
return;
}
}
/**
* Returns the explicitly requested singular annotation on this node (field
* or parameter), or null if there's no {@code @Singular} annotation on it.
*
* @param node The node (field or method param) to inspect for its name and potential {@code @Singular} annotation.
*/
private SingularData getSingularData(EclipseNode node, ASTNode source) {
for (EclipseNode child : node.down()) {
if (!annotationTypeMatches(Singular.class, child)) continue;
char[] pluralName = node.getKind() == Kind.FIELD ? removePrefixFromField(node) : ((AbstractVariableDeclaration) node.get()).name;
AnnotationValues<Singular> ann = createAnnotation(Singular.class, child);
String explicitSingular = ann.getInstance().value();
if (explicitSingular.isEmpty()) {
if (Boolean.FALSE.equals(node.getAst().readConfiguration(ConfigurationKeys.SINGULAR_AUTO))) {
node.addError("The singular must be specified explicitly (e.g. @Singular(\"task\")) because auto singularization is disabled.");
explicitSingular = new String(pluralName);
} else {
explicitSingular = autoSingularize(new String(pluralName));
if (explicitSingular == null) {
node.addError("Can't singularize this name; please specify the singular explicitly (i.e. @Singular(\"sheep\"))");
explicitSingular = new String(pluralName);
}
}
}
char[] singularName = explicitSingular.toCharArray();
TypeReference type = ((AbstractVariableDeclaration) node.get()).type;
TypeReference[] typeArgs = null;
String typeName;
if (type instanceof ParameterizedSingleTypeReference) {
typeArgs = ((ParameterizedSingleTypeReference) type).typeArguments;
typeName = new String(((ParameterizedSingleTypeReference) type).token);
} else if (type instanceof ParameterizedQualifiedTypeReference) {
TypeReference[][] tr = ((ParameterizedQualifiedTypeReference) type).typeArguments;
if (tr != null) typeArgs = tr[tr.length - 1];
char[][] tokens = ((ParameterizedQualifiedTypeReference) type).tokens;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
if (i > 0) sb.append(".");
sb.append(tokens[i]);
}
typeName = sb.toString();
} else {
typeName = type.toString();
}
String targetFqn = EclipseSingularsRecipes.get().toQualified(typeName);
EclipseSingularizer singularizer = EclipseSingularsRecipes.get().getSingularizer(targetFqn);
if (singularizer == null) {
node.addError("Lombok does not know how to create the singular-form builder methods for type '" + typeName + "'; they won't be generated.");
return null;
}
return new SingularData(child, singularName, pluralName, typeArgs == null ? Collections.<TypeReference>emptyList() : Arrays.asList(typeArgs), targetFqn, singularizer, source);
}
return null;
}
}
| mit |
ottboy4/tictactoe | LibraryTests/src/ott/capstone/GrayscaleTest.java | 723 | package ott.capstone;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import ott.image.ColorEffects;
import ott.image.ColorEffects.ColorEffectType;
public class GrayscaleTest
{
public static void runDisplay() throws Exception
{
BufferedImage img = ImageIO.read(new File("Tulips.jpg"));
MainClass.display("Original", img);
img = ColorEffects.applyEffect(img, ColorEffectType.GRAYSCALE_LIGHTNESS);
MainClass.display("Lightness", img);
img = ColorEffects.applyEffect(img, ColorEffectType.GRAYSCALE_AVERAGE);
MainClass.display("Average", img);
img = ColorEffects.applyEffect(img, ColorEffectType.GRAYSCALE_LUMINOSITY);
MainClass.display("Luminosity", img);
}
}
| mit |
bwkimmel/jmist | jmist-core/src/main/java/ca/eandb/jmist/framework/path/PathInfo.java | 2452 | /**
* Java Modular Image Synthesis Toolkit (JMIST)
* Copyright (C) 2018 Bradley W. Kimmel
*
* 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 ca.eandb.jmist.framework.path;
import ca.eandb.jmist.framework.Scene;
import ca.eandb.jmist.framework.color.ColorModel;
import ca.eandb.jmist.framework.color.WavelengthPacket;
import ca.eandb.jmist.framework.scene.EmptyScene;
/**
* Represents the context in which a path is created.
* @author Brad Kimmel
*/
public final class PathInfo {
private final Scene scene;
private final WavelengthPacket wavelengthPacket;
private final double time;
public PathInfo(WavelengthPacket wavelengthPacket) {
this(EmptyScene.INSTANCE, wavelengthPacket, 0.0);
}
public PathInfo(WavelengthPacket wavelengthPacket, double time) {
this(EmptyScene.INSTANCE, wavelengthPacket, time);
}
public PathInfo(Scene scene, WavelengthPacket wavelengthPacket, double time) {
this.scene = scene;
this.wavelengthPacket = wavelengthPacket;
this.time = time;
}
public PathInfo(Scene scene, WavelengthPacket wavelengthPacket) {
this(scene, wavelengthPacket, 0.0);
}
public ColorModel getColorModel() {
return wavelengthPacket.getColorModel();
}
public WavelengthPacket getWavelengthPacket() {
return wavelengthPacket;
}
public Scene getScene() {
return scene;
}
public double getTime() {
return time;
}
}
| mit |
CCI-MIT/XCoLab | view/src/main/java/org/xcolab/view/moderation/ModerationController.java | 1578 | package org.xcolab.view.moderation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.xcolab.client.moderation.IModerationClient;
import org.xcolab.client.user.pojo.wrapper.UserWrapper;
import org.xcolab.util.enums.moderation.TargetType;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
public class ModerationController {
@Autowired
private IModerationClient moderationClient;
@PostMapping("/flagging/report")
public ResponseJson report(HttpServletRequest request, HttpServletResponse response,
@RequestParam TargetType targetType, @RequestParam long targetAdditionalId,
@RequestParam String reason, @RequestParam String comment, @RequestParam long targetId,
UserWrapper loggedInMember) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
moderationClient
.report(loggedInMember, targetId, targetAdditionalId, targetType, reason, comment);
return new ResponseJson(true);
}
private static class ResponseJson {
private final boolean success;
private ResponseJson(boolean success) {
this.success = success;
}
public boolean isSuccess() {
return success;
}
}
}
| mit |
Tamaized/VoidCraft | src/main/java/tamaized/voidcraft/common/blocks/BlockDreamBed.java | 2619 | package tamaized.voidcraft.common.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import tamaized.tammodized.registry.ITamRegistry;
import tamaized.voidcraft.common.events.VoidTickEvent;
import java.util.Random;
public class BlockDreamBed extends BlockBed implements ITamRegistry {
private final String name;
public BlockDreamBed(CreativeTabs tab, String n) {
super();
name = n;
setUnlocalizedName(name);
setLightLevel(1.0F);
setRegistryName(name);
this.setCreativeTab(tab);
}
public String getModelDir() {
return "blocks";
}
@Override
public void registerBlock(RegistryEvent.Register<Block> e) {
e.getRegistry().register(this);
}
@Override
public void registerItem(RegistryEvent.Register<Item> e) {
}
@Override
public void registerModel(ModelRegistryEvent e) {
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(new ResourceLocation(getRegistryName().getResourceDomain(), getModelDir() + "/" + getRegistryName().getResourcePath()), "inventory"));
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return null;
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return Items.AIR;
}
@Override
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.TRANSLUCENT;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
return EnumBlockRenderType.MODEL;
}
@Override
public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) {
return ItemStack.EMPTY;
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
if (!worldIn.isRemote)
VoidTickEvent.dream(playerIn);
return true;
}
}
| mit |
mrtowel/routedrawer_android | src/pl/towelrail/locate/http/TowelHttpResponse.java | 947 | package pl.towelrail.locate.http;
import java.io.Serializable;
/**
* Http response custom. First of all to be used with POST tasks to store created object remote id.
*/
public class TowelHttpResponse implements Serializable {
private int mStatusCode;
private String mBody;
private long mObjectId;
public TowelHttpResponse(int mStatusCode, String mBody, long mObjectId) {
this.mStatusCode = mStatusCode;
this.mBody = mBody;
this.mObjectId = mObjectId;
}
public int getmStatusCode() {
return mStatusCode;
}
public String getmBody() {
return mBody;
}
public long getmObjectId() {
return mObjectId;
}
@Override
public String toString() {
return "TowelHttpResponse{" +
"mStatusCode=" + mStatusCode +
", mBody='" + mBody + '\'' +
", mObjectId=" + mObjectId +
'}';
}
}
| mit |
mattem/formation-spring-boot-starter | src/main/java/me/mattem/formation/cache/objectdescriptors/AbstractObjectPropertyDescriptor.java | 114 | package me.mattem.formation.cache.objectdescriptors;
public abstract class AbstractObjectPropertyDescriptor {
} | mit |
msopentechcn/odata-producer-codegen-for-jdbc | odata2-codegen/src/main/java/com/msopentech/odatagen/PersistenceXMLProcessor.java | 5194 | /*******************************************************************************
* Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
* The MIT License (MIT)
* 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.msopentech.odatagen;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.msopentech.odatagen.infos.PathInfo;
public class PersistenceXMLProcessor {
private final String PERSISTENCE_ELEMENTSBYTAGNAME = "persistence-unit";
private boolean isFind = false;
public void updataPersistenceXML(PathInfo pathInfo) throws SAXException,
IOException, ParserConfigurationException,
TransformerConfigurationException, TransformerException,
TransformerFactoryConfigurationError {
/* Find persistence file real path */
pathInfo = findPersistenceXMLPath(pathInfo);
/* Add <class> elements */
addClassElements(pathInfo);
}
protected PathInfo findPersistenceXMLPath(PathInfo pathInfo)
throws FileNotFoundException {
File fi = new File(pathInfo.getRealPath());
if (!fi.isFile()) {
pathInfo = find(pathInfo, fi);
}
return pathInfo;
}
protected PathInfo find(PathInfo pathInfo, File fi) {
File[] files = fi.listFiles();
for (File f : files) {
if ((!isFind && f.isFile())
&& pathInfo.getPersistenceClassPath().contains(f.getName())) {
isFind = true;
pathInfo.setPersistenceClassPath(f.getPath());
return pathInfo;
}
if (!f.isFile()) {
pathInfo = find(pathInfo, f);
}
}
return pathInfo;
}
private void addClassElements(PathInfo pathInfo) throws SAXException,
IOException, ParserConfigurationException,
TransformerConfigurationException, TransformerException,
TransformerFactoryConfigurationError {
Document book = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(pathInfo.getPersistenceClassPath());
Node persistence_unit_Node = getPersistence_unit_Node(pathInfo, book);
/* Delect all <class> elements */
NodeList nodeList2 = persistence_unit_Node.getChildNodes();
int nodeListLength = nodeList2.getLength();
for (int k = 0; k < nodeListLength; k++) {
Node node2 = nodeList2.item(k);
if (node2 != null && node2.getNodeName().equals("class")) {
node2.getParentNode().removeChild(node2);
}
}
/* Add new <class> elements */
List<String> entityPathNameList = pathInfo.getEntityPackAndNames();
for (String entityPathName : entityPathNameList) {
Element element = book.createElement("class");
element.setTextContent(entityPathName);
persistence_unit_Node.appendChild(element);
}
TransformerFactory
.newInstance()
.newTransformer()
.transform(new DOMSource(book),
new StreamResult(pathInfo.getPersistenceClassPath()));
}
protected Node getPersistence_unit_Node(PathInfo pathInfo, Document book)
throws SAXException, IOException, ParserConfigurationException {
NodeList nodeList = book
.getElementsByTagName(PERSISTENCE_ELEMENTSBYTAGNAME);
int length = nodeList.getLength();
Node persistence_unit_Node = null;
for (int i = 0; i < length; i++) {
persistence_unit_Node = nodeList.item(i);
NamedNodeMap namedNodeMap = persistence_unit_Node.getAttributes();
int attrLength = namedNodeMap.getLength();
for (int j = 0; j < attrLength; j++) {
if (pathInfo.getPersistenceUnitName().equals(
namedNodeMap.item(j).getNodeValue())) {
break;
}
}
}
return persistence_unit_Node;
}
}
| mit |
BillyYccc/DesignPatternsExamples | BuilderDemo/src/test/java/com/billyyccc/builderdemotest/BuilderTest.java | 2411 | /*
* MIT License
*
* Copyright (c) 2017 BillyYuan
*
* 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.billyyccc.builderdemotest;
import com.billyyccc.builderdemo.*;
import org.junit.Test;
/**
* Created by Billy Yuan on 2017/5/1.
* Email: billy112487983@gmail.com
*/
public class BuilderTest {
@Test
public void builderTest1() {
CarBuilder carBuilder = new BenzCarBuilder();
//Director
CarDirector benzDirector = new CarDirector(carBuilder);
benzDirector.construct("米其林轮胎");
BenzCar benzCar1 = (BenzCar) carBuilder.build();
System.out.println(benzCar1.toString());
}
@Test
public void builderTest2() {
//有时候会省略Director,直接使用builder
AudiCar audiCar1 = new AudiCar.AudiCarBuilder().buildEngine()
.buildSystem()
.buildBrand()
.buildWheel("倍耐力轮胎")
.build();
System.out.println(audiCar1.toString());
}
@Test
public void builderTest3() {
//修改AudiCar的装配过程,先装配系统再装配发动机
AudiCar audiCar2 = new AudiCar.AudiCarBuilder().buildSystem()
.buildEngine()
.buildWheel("倍耐力轮胎")
.buildBrand()
.build();
System.out.println(audiCar2.toString());
}
}
| mit |
prism/Prism | src/main/java/com/helion3/prism/storage/mongodb/MongoRecords.java | 14751 | /*
* This file is part of Prism, licensed under the MIT License (MIT).
*
* Copyright (c) 2015 Helion3 http://helion3.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.helion3.prism.storage.mongodb;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import com.google.common.collect.Lists;
import com.helion3.prism.api.flags.Flag;
import com.helion3.prism.api.query.*;
import com.helion3.prism.api.records.Result;
import com.helion3.prism.util.PrimitiveArray;
import org.bson.Document;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.data.DataView;
import com.google.common.collect.Range;
import com.helion3.prism.Prism;
import com.helion3.prism.api.query.ConditionGroup.Operator;
import com.helion3.prism.api.storage.StorageAdapterRecords;
import com.helion3.prism.api.storage.StorageDeleteResult;
import com.helion3.prism.api.storage.StorageWriteResult;
import com.helion3.prism.util.DataQueries;
import com.helion3.prism.util.DataUtil;
import com.helion3.prism.util.DateUtil;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.WriteModel;
public class MongoRecords implements StorageAdapterRecords {
private final BulkWriteOptions bulkWriteOptions = new BulkWriteOptions().ordered(false);
private final String expiration = Prism.getInstance().getConfig().getStorageCategory().getExpireRecords();
private final boolean expires = Prism.getInstance().getConfig().getStorageCategory().isShouldExpire();
/**
* Converts a DataView to a Document, recursively if needed.
*
* @param view Data view/container.
* @return Document for Mongo storage.
*/
private Document documentFromView(DataView view) {
Document document = new Document();
Set<DataQuery> keys = view.getKeys(false);
for (DataQuery query : keys) {
String key = DataUtil.escapeQuery(query);
Object value = view.get(query).orElse(null);
if (value == null) {
// continue
} else if (value instanceof Collection) {
List<Object> convertedList = Lists.newArrayList();
for (Object object : (Collection<?>) value) {
if (object == null) {
// continue
} else if (object instanceof DataView) {
convertedList.add(documentFromView((DataView) object));
} else if (DataUtil.isPrimitiveType(object)) {
convertedList.add(object);
} else if (object.getClass().isArray()) {
document.append(key, new PrimitiveArray(object));
} else if (object.getClass().isEnum()) {
// Ignoring, this data should exist elsewhere in the document.
// this is ConnectedDirections and other vanilla manipulators
// convertedList.add(object.toString());
} else {
Prism.getInstance().getLogger().error("Unsupported list data type: " + object.getClass().getName());
}
}
if (!convertedList.isEmpty()) {
document.append(key, convertedList);
}
} else if (value instanceof DataView) {
document.append(key, documentFromView((DataView) value));
} else if (value.getClass().isArray()) {
document.append(key, new PrimitiveArray(value));
} else {
if (key.equals(DataQueries.Player.toString())) {
document.append(DataQueries.Player.toString(), value);
} else {
document.append(key, value);
}
}
}
return document;
}
/**
* Convert a mongo Document to a DataContainer.
* @param document Mongo document.
* @return Data container.
*/
private DataContainer documentToDataContainer(Document document) {
DataContainer result = DataContainer.createNew();
for (String key : document.keySet()) {
DataQuery query = DataUtil.unescapeQuery(key);
Object value = document.get(key);
if (value instanceof Document) {
PrimitiveArray primitiveArray = PrimitiveArray.of((Document) value);
if (primitiveArray != null) {
result.set(query, primitiveArray.getArray());
continue;
}
result.set(query, documentToDataContainer((Document) value));
} else {
result.set(query, value);
}
}
return result;
}
@Override
public StorageWriteResult write(List<DataContainer> containers) throws Exception {
MongoCollection<Document> collection = MongoStorageAdapter.getCollection(MongoStorageAdapter.collectionEventRecordsName);
// Build an array of documents
List<WriteModel<Document>> documents = new ArrayList<>();
for (DataContainer container : containers) {
Document document = documentFromView(container);
// Prism.getInstance().getLogger().debug(DataUtil.jsonFromDataView(container).toString());
// TTL
if (expires) {
document.append("Expires", DateUtil.parseTimeStringToDate(expiration, true));
}
// Insert
documents.add(new InsertOneModel<>(document));
}
// Write
collection.bulkWrite(documents, bulkWriteOptions);
// @todo implement real results, BulkWriteResult
return new StorageWriteResult();
}
/**
* Recursive method of building condition documents.
*
* @param fieldsOrGroups List<Condition>
* @return Document
*/
private Document buildConditions(List<Condition> fieldsOrGroups) {
Document conditions = new Document();
for (Condition fieldOrGroup : fieldsOrGroups) {
if (fieldOrGroup instanceof ConditionGroup) {
ConditionGroup group = (ConditionGroup) fieldOrGroup;
Document subDoc = buildConditions(group.getConditions());
if (group.getOperator().equals(Operator.OR)) {
conditions.append("$or", subDoc);
} else {
conditions.putAll(subDoc);
}
} else {
FieldCondition field = (FieldCondition) fieldOrGroup;
Document matcher;
if (conditions.containsKey(field.getFieldName().toString())) {
matcher = (Document) conditions.get(field.getFieldName().toString());
} else {
matcher = new Document();
}
// Match an array of items
if (field.getValue() instanceof List) {
matcher.append(field.getMatchRule().equals(MatchRule.INCLUDES) ? "$in" : "$nin", field.getValue());
conditions.put(field.getFieldName().toString(), matcher);
}
else if (field.getMatchRule().equals(MatchRule.EQUALS)) {
conditions.put(field.getFieldName().toString(), field.getValue());
}
else if (field.getMatchRule().equals(MatchRule.GREATER_THAN_EQUAL)) {
matcher.append("$gte", field.getValue());
conditions.put(field.getFieldName().toString(), matcher);
}
else if (field.getMatchRule().equals(MatchRule.LESS_THAN_EQUAL)) {
matcher.append("$lte", field.getValue());
conditions.put(field.getFieldName().toString(), matcher);
}
else if (field.getMatchRule().equals(MatchRule.BETWEEN)) {
if (!(field.getValue() instanceof Range)) {
throw new IllegalArgumentException("\"Between\" match value must be a Range.");
}
Range<?> range = (Range<?>) field.getValue();
Document between = new Document("$gte", range.lowerEndpoint()).append("$lte", range.upperEndpoint());
conditions.put(field.getFieldName().toString(), between);
}
}
}
return conditions;
}
@Override
public CompletableFuture<List<Result>> query(QuerySession session, boolean translate) throws Exception {
Query query = session.getQuery();
checkNotNull(query);
// Prepare results
List<Result> results = new ArrayList<>();
CompletableFuture<List<Result>> future = new CompletableFuture<>();
// Get collection
MongoCollection<Document> collection = MongoStorageAdapter.getCollection(MongoStorageAdapter.collectionEventRecordsName);
// Append all conditions
Document matcher = new Document("$match", buildConditions(query.getConditions()));
// Sorting. Newest first for rollback and oldest first for restore.
Document sortFields = new Document();
sortFields.put(DataQueries.Created.toString(), session.getSortBy().getValue());
Document sorter = new Document("$sort", sortFields);
// Offset/Limit
Document limit = new Document("$limit", query.getLimit());
// Build aggregators
final AggregateIterable<Document> aggregated;
if (!session.hasFlag(Flag.NO_GROUP)) {
// Grouping fields
Document groupFields = new Document();
groupFields.put(DataQueries.EventName.toString(), "$" + DataQueries.EventName);
groupFields.put(DataQueries.Player.toString(), "$" + DataQueries.Player);
groupFields.put(DataQueries.Cause.toString(), "$" + DataQueries.Cause);
groupFields.put(DataQueries.Target.toString(), "$" + DataQueries.Target);
// Entity
groupFields.put(DataQueries.Entity.toString(), "$" + DataQueries.Entity.then(DataQueries.EntityType));
// Day
groupFields.put("dayOfMonth", new Document("$dayOfMonth", "$" + DataQueries.Created));
groupFields.put("month", new Document("$month", "$" + DataQueries.Created));
groupFields.put("year", new Document("$year", "$" + DataQueries.Created));
Document groupHolder = new Document("_id", groupFields);
groupHolder.put(DataQueries.Count.toString(), new Document("$sum", 1));
Document group = new Document("$group", groupHolder);
// Aggregation pipeline
List<Document> pipeline = new ArrayList<>();
pipeline.add(matcher);
pipeline.add(group);
pipeline.add(sorter);
pipeline.add(limit);
aggregated = collection.aggregate(pipeline);
Prism.getInstance().getLogger().debug("MongoDB Query: " + pipeline);
} else {
// Aggregation pipeline
List<Document> pipeline = new ArrayList<>();
pipeline.add(matcher);
pipeline.add(sorter);
pipeline.add(limit);
aggregated = collection.aggregate(pipeline);
Prism.getInstance().getLogger().debug("MongoDB Query: " + pipeline);
}
// Iterate results and build our event record list
try (MongoCursor<Document> cursor = aggregated.iterator()) {
List<UUID> uuidsPendingLookup = new ArrayList<>();
while (cursor.hasNext()) {
// Mongo document
Document wrapper = cursor.next();
Document document = session.hasFlag(Flag.NO_GROUP) ? wrapper : (Document) wrapper.get("_id");
DataContainer data = documentToDataContainer(document);
if (!session.hasFlag(Flag.NO_GROUP)) {
data.set(DataQueries.Count, wrapper.get(DataQueries.Count.toString()));
}
// Build our result object
Result result = Result.from(wrapper.getString(DataQueries.EventName.toString()), !session.hasFlag(Flag.NO_GROUP));
// Determine the final name of the event source
if (document.containsKey(DataQueries.Player.toString())) {
String uuid = document.getString(DataQueries.Player.toString());
data.set(DataQueries.Cause, uuid);
if (translate) {
uuidsPendingLookup.add(UUID.fromString(uuid));
}
} else {
data.set(DataQueries.Cause, document.getString(DataQueries.Cause.toString()));
}
result.data = data;
results.add(result);
}
if (translate && !uuidsPendingLookup.isEmpty()) {
DataUtil.translateUuidsToNames(results, uuidsPendingLookup).thenAccept(future::complete);
} else {
future.complete(results);
}
}
return future;
}
/**
* Given a list of parameters, will remove all matching records.
*
* @param query Query conditions indicating what we're purging
* @return
*/
// @todo implement
@Override
public StorageDeleteResult delete(Query query) {
return new StorageDeleteResult();
}
}
| mit |
ngageoint/geopackage-mapcache-android | mapcache/src/main/java/mil/nga/mapcache/preferences/TileUrlFragment.java | 15856 | package mil.nga.mapcache.preferences;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import java.util.HashSet;
import java.util.Set;
import mil.nga.mapcache.R;
import mil.nga.mapcache.utils.ViewAnimation;
/**
* Fragment giving the user a way to modify a saved list of URLs, which will be used in the create
* tile layer wizard
*/
public class TileUrlFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {
/**
* Parent View
*/
private View urlView;
/**
* URL input text
*/
private EditText inputText;
/**
* Selected URL label
*/
private TextView selectedLabel;
/**
* Shared preferences
*/
private SharedPreferences prefs;
// /**
// * Clear all URLs
// */
// private Button clearButton;
/**
* Add new URL from the inputText field to the shared prefs
*/
private Button addButton;
/**
* Layout to hold a reference to all saved URLs
*/
private LinearLayout labelHolder;
/**
* Delete selected text
*/
// private TextView deleteSelected;
/**
* Edit mode button
*/
private TextView editModeText;
/**
* Tracks the state of delete visibility
*/
private boolean editMode = false;
/**
* Create the parent view and set up listeners
* @param inflater Layout inflator
* @param container Main container
* @param savedInstanceState Saved instance state
* @return Parent view for the fragment
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
urlView = inflater.inflate(R.layout.fragment_saved_tile_urls, container, false);
inputText = urlView.findViewById(R.id.new_url);
// clearButton = urlView.findViewById(R.id.clear_all);
addButton = urlView.findViewById(R.id.add_url);
addButton.setEnabled(false);
labelHolder = urlView.findViewById(R.id.item_list_layout);
// deleteSelected = urlView.findViewById(R.id.delete_selected_urls);
editModeText = urlView.findViewById(R.id.edit_mode_label);
selectedLabel = urlView.findViewById(R.id.selected_urls_label);
prefs = getPreferenceManager().getSharedPreferences();
setButtonListeners();
setInitialPrefLabels();
return urlView;
}
/**
* Gets the shared preferences setting for the current list
* @param defaultVal new list if null
* @return Set of type String
*/
private Set<String> getStringSet(Set<String> defaultVal) {
return this.prefs.getStringSet(getString(R.string.geopackage_create_tiles_label), defaultVal);
}
/**
* Save the given set to saved preferences
* @param set set of strings to save
* @return true after the commit is saved
*/
private boolean saveSet(Set<String> set){
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getString(R.string.geopackage_create_tiles_label), set);
return editor.commit();
}
/**
* Adds a String to the given set by making a copy of it, then saving to shared preferences
* @param originalSet original shared preference string set
* @param newUrl new url to add
* @return true after the commit is saved
*/
private boolean addStringToSet(Set<String> originalSet, String newUrl){
HashSet<String> prefList = new HashSet<>(originalSet);
if(prefList.contains(newUrl)){
Toast msg = Toast.makeText(getActivity(), "URL already exists", Toast.LENGTH_SHORT);
msg.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
View view = msg.getView();
view.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.DST_OVER);
msg.show();
return false;
}
prefList.add(newUrl);
return saveSet(prefList);
}
/**
* Gets the current shared prefs, copies it (leaving out the given string), then saves to shared prefs
* @param remove string to remove
* @return true once commit is finished
*/
private boolean removeStringFromSet(String remove){
Set<String> existing = getStringSet(new HashSet<String>());
HashSet<String> prefList = new HashSet<>();
if(existing.size() > 0){
for(String str : existing){
if(!str.equalsIgnoreCase(remove)){
prefList.add(str);
}
}
return saveSet(prefList);
}
return false;
}
/**
* Adds all the URLs from the loaded preferenes as labels in the view
*/
private void setInitialPrefLabels(){
Set<String> existing = getStringSet(new HashSet<String>());
if(existing.size() > 0){
for(String str : existing){
addUrlView(str);
}
}
}
/**
* Set button listeners for the Add Url button and Clear all button
*/
private void setButtonListeners(){
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String newUrl = inputText.getText().toString();
Set<String> existing = getStringSet(new HashSet<String>());
boolean saved = addStringToSet(existing, newUrl);
if (saved) {
if (editMode) {
showEditButtons();
}
addUrlView(newUrl);
}
}
});
// deleteSelected.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// // Keep track of rows that need to be deleted
// HashMap<String, LinearLayout> deleteViews = new HashMap<>();
// // Find rows that are checked and note the row number
// for (int i = 0; i < labelHolder.getChildCount(); i++) {
// LinearLayout itemRow = (LinearLayout)labelHolder.getChildAt(i);
// if(isItemRowChecked(itemRow)){
// deleteViews.put(getRowText(itemRow), itemRow);
// }
// }
// // Delete all checked rows
// Iterator it = deleteViews.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pair = (Map.Entry) it.next();
// if(removeStringFromSet(pair.getKey().toString())){
//// labelHolder.removeView((LinearLayout)pair.getValue());
// labelHolder = (LinearLayout)ViewAnimation.fadeOutAndRemove((LinearLayout)pair.getValue(), labelHolder, 250);
// }
// }
// setDeleteSelected();
// }
// });
inputText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String url = inputText.getText().toString();
if(url.isEmpty()){
addButton.setEnabled(false);
} else{
addButton.setEnabled(true);
}
}
});
editModeText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showEditButtons();
}
});
}
/**
* Shows or hides all the delete buttons next to each row of URLs
*/
private void showEditButtons(){
for (int i = 0; i < labelHolder.getChildCount(); i++) {
LinearLayout itemRow = (LinearLayout) labelHolder.getChildAt(i);
for (int j = 0; j < itemRow.getChildCount(); j++) {
if(itemRow.getChildAt(j) instanceof ImageButton){
ImageButton deleteButton = (ImageButton) itemRow.getChildAt(j);
if(!editMode) {
deleteButton.setVisibility(View.VISIBLE);
} else {
deleteButton.setVisibility(View.GONE);
}
}
}
}
editMode = !editMode;
if(editMode){
editModeText.setText("Done");
editModeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.nga_primary_light));
} else {
editModeText.setText("Edit");
editModeText.setTextColor(ContextCompat.getColor(getActivity(), R.color.nga_warning));
}
}
/**
* Creates a textView with the given string, and adds it to the item list
* @param text String to add to the list
*/
private void addUrlView(String text){
final String rowName = text;
// Create a new Layout to hold items
final LinearLayout itemRow = new LinearLayout(getContext());
itemRow.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.HORIZONTAL));
itemRow.setGravity(Gravity.CENTER);
// itemRow.setPadding(0,48,0, 48);
// itemRow.setBackground(getResources().getDrawable(R.drawable.delete_bg));
ImageButton deleteButton = new ImageButton(getContext());
deleteButton.setImageResource(R.drawable.delete_forever);
deleteButton.setBackground(null);
deleteButton.setVisibility(View.GONE);
deleteButton.setPadding(48,48,48, 48);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog deleteDialog = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle)
.setTitle(
getString(R.string.delete_url_title))
.setMessage(
getString(R.string.delete_url_message))
.setPositiveButton(getString(R.string.button_delete_label),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(removeStringFromSet(text)){
labelHolder = (LinearLayout)ViewAnimation.fadeOutAndRemove(itemRow, labelHolder, 250);
}
}
})
.setNegativeButton(getString(R.string.button_cancel_label),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).create();
deleteDialog.show();
}
});
// Create checkbox
CheckBox check = new CheckBox(getContext());
check.setPadding(16,0,64,0);
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// setDeleteSelected();
}
});
// Create text
TextView nameText = new TextView(getContext());
nameText.setText(text);
LinearLayout.LayoutParams textLayout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textLayout.setMargins(16, 16, 16, 16);
textLayout.gravity = Gravity.CENTER;
nameText.setLayoutParams(textLayout);
nameText.setPadding(32,32,32, 32);
nameText.setTextAppearance(getContext(), R.style.textAppearanceSubtitle1);
// Add everything
itemRow.addView(deleteButton);
// itemRow.addView(check);
itemRow.addView(nameText);
ViewAnimation.setSlideInFromRightAnimation(itemRow, 250);
labelHolder.addView(itemRow);
}
/**
* Find the checkbox in the item row and tell us if it's checked
* @param itemRow linearLayout containing a checkbox
* @return true if the checkbox is checked
*/
private boolean isItemRowChecked(LinearLayout itemRow){
for (int i = 0; i < itemRow.getChildCount(); i++) {
if(itemRow.getChildAt(i) instanceof CheckBox){
CheckBox check = (CheckBox) itemRow.getChildAt(i);
return check.isChecked();
}
}
return false;
}
/**
* Return true if any rows are checked
*/
private boolean isAnyRowChecked(){
for (int i = 0; i < labelHolder.getChildCount(); i++) {
LinearLayout itemRow = (LinearLayout)labelHolder.getChildAt(i);
if(isItemRowChecked(itemRow)){
return true;
}
}
return false;
}
// /**
// * Sets the delete selected text to active if any rows are checked, else it's disabled
// */
// private void setDeleteSelected(){
// if(isAnyRowChecked()){
// deleteSelected.setEnabled(true);
// deleteSelected.setTextColor(ContextCompat.getColor(getActivity(), R.color.nga_warning));
// } else {
// deleteSelected.setEnabled(false);
// deleteSelected.setTextColor(ContextCompat.getColor(getActivity(), R.color.black50));
// }
// }
/**
* Get the URL string from a row
* @param itemRow linear layout containing a checkbox and text field
* @return text from the text field
*/
private String getRowText(LinearLayout itemRow){
for (int i = 0; i < itemRow.getChildCount(); i++) {
if (itemRow.getChildAt(i) instanceof TextView && !(itemRow.getChildAt(i) instanceof CheckBox)) {
TextView urlText = (TextView)itemRow.getChildAt(i);
String text = urlText.getText().toString();
return text;
}
}
return null;
}
/**
* Delete a row from shared prefs and the Linear Layout
* @param itemRow LinearLayout of the row to be deleted
*/
private void deleteRow(View itemRow){
((ViewManager)itemRow.getParent()).removeView(itemRow);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return false;
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
}
}
| mit |
bg1bgst333/Sample | gson/Gson/toJson_android/GS/GS_/app/src/test/java/com/bgstation0/gson/sample/gs_/ExampleUnitTest.java | 391 | package com.bgstation0.gson.sample.gs_;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | mit |
LinDA-tools/RDF2Any | linda/src/main/java/de/unibonn/iai/eis/linda/converters/impl/results/JSONObjectsOutput.java | 3913 | package de.unibonn.iai.eis.linda.converters.impl.results;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import de.unibonn.iai.eis.linda.querybuilder.classes.RDFClass;
import de.unibonn.iai.eis.linda.querybuilder.classes.RDFClassProperty;
import de.unibonn.iai.eis.linda.querybuilder.objects.RDFObject;
import de.unibonn.iai.eis.linda.querybuilder.objects.RDFObjectProperty;
import de.unibonn.iai.eis.linda.querybuilder.objects.RDFObjectPropertyValue;
/**
* @author gsingharoy
*
*
* This class gives the JSON output when a class convert for JSON is
* called
*
**/
public class JSONObjectsOutput {
public String dataset;
public List<Object> classes;
public Map<String, Object> properties;
public List<Object> objects;
private Map<String, String> propertyDictionary;
private RDFClass forClass;
public JSONObjectsOutput(RDFClass forClass) {
// TODO Auto-generated constructor stub
this.dataset = forClass.dataset;
this.classes = new ArrayList<Object>();
this.properties = new HashMap<String, Object>();
this.objects = new ArrayList<Object>();
this.forClass = forClass;
generatePropertiesForOutput();
Map<String, Object> classDef = new HashMap<String, Object>();
classDef.put("uri", forClass.uri);
classDef.put("label", forClass.label);
List<String> classProperties = new ArrayList<String>();
@SuppressWarnings("rawtypes")
Iterator it = this.propertyDictionary.entrySet().iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pairs = (Map.Entry) it.next();
classProperties.add((String) pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
classDef.put("properties", classProperties);
this.classes.add(classDef);
}
private void generatePropertiesForOutput() {
this.propertyDictionary = new HashMap<String, String>();
for (RDFClassProperty prop : this.forClass.properties) {
String propVar = prop.getPropertyUnderscoreVariableName();
this.propertyDictionary.put(prop.uri, propVar);
Map<String, Object> propertyMap = new HashMap<String, Object>();
propertyMap.put("uri", prop.uri);
propertyMap.put("label", prop.label);
propertyMap.put("type", prop.type);
propertyMap.put("range", prop.range);
this.properties.put(propVar, propertyMap);
}
}
public void addObject(RDFObject object) {
Map<String, Object> objectMap = new HashMap<String, Object>();
Map<String, Object> objectPropertyMap = new HashMap<String, Object>();
for (RDFObjectProperty objectProp : object.properties) {
List<Object> objectPropertyValues = new ArrayList<Object>();
for (RDFObjectPropertyValue objectPropertyValue : objectProp.objects) {
objectPropertyValues.add(getNewObjectValueMap(objectProp,objectPropertyValue));
}
objectPropertyMap.put(
objectProp.predicate.getPropertyUnderscoreVariableName(),
objectPropertyValues);
}
objectMap.put("properties", objectPropertyMap);
objectMap.put("label", object.name);
objectMap.put("class",object.hasClass.uri);
objectMap.put("uri", object.uri);
this.objects.add(objectMap);
}
private Map getNewObjectValueMap(RDFObjectProperty objectProp, RDFObjectPropertyValue objectPropertyValue){
Map<String, String>objectPropertyValueMap = new HashMap<String, String>();
objectPropertyValueMap.put("value", objectPropertyValue.value);
if (objectProp.predicate.type.equalsIgnoreCase("data")) {
objectPropertyValueMap.put("type", "literal");
if (objectPropertyValue.additionalValue != null
&& !objectPropertyValue.additionalValue
.equalsIgnoreCase(""))
objectPropertyValueMap.put("xml_lang",
objectPropertyValue.additionalValue);
} else if (objectProp.predicate.type.equalsIgnoreCase("object")) {
objectPropertyValueMap.put("type", "uri");
}
return objectPropertyValueMap;
}
}
| mit |
Lordmau5/FFS | src/main/java/com/lordmau5/ffs/proxy/GuiHandler.java | 963 | package com.lordmau5.ffs.proxy;
import com.lordmau5.ffs.client.gui.GuiValve;
import com.lordmau5.ffs.tile.abstracts.AbstractTankTile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
/**
* Created by Dustin on 05.07.2015.
*/
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
TileEntity tile = world.getTileEntity(new BlockPos(x, y, z));
if ( tile == null || !(tile instanceof AbstractTankTile) ) {
return null;
}
return new GuiValve((AbstractTankTile) tile, ID == 1);
}
}
| mit |
costasdroid/project_euler | problem012/Solution012.java | 1233 | package problem012;
import java.util.ArrayList;
import java.util.List;
public class Solution012 {
static List<Long> list;
static List<Long> ocs;
public static void main(String[] args) {
Long t1 = System.currentTimeMillis();
long sum = 1;
for (int i = 2; i <= 100000; i++) {
list = new ArrayList<Long>();
ocs = new ArrayList<Long>();
sum = sum + i;
findPrimes(sum);
if (makeDivisorsFrom(ocs) > 500) {
System.out.println(sum);
break;
}
}
System.out.println("Time: " + (System.currentTimeMillis() - t1));
}
private static void findPrimes(long n) {
while (n > 1) {
Long i;
for (i = (long) 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (list.contains(i)) {
ocs.set(list.indexOf(i), ocs.get(list.indexOf(i)) + 1);
} else {
list.add(i);
ocs.add(1L);
}
n = n / i;
break;
}
}
if (i > Math.sqrt(n)) {
if (list.contains(n)) {
ocs.set(list.indexOf(n), ocs.get(list.indexOf(n)) + 1);
} else {
list.add(n);
ocs.add(1L);
}
break;
}
}
}
private static Long makeDivisorsFrom(List<Long> l) {
Long count = 1L;
for (Long i: l) {
count = count * (i + 1);
}
return count;
}
}
| mit |
HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/legacy/ComponentCollection.java | 587 | //$Id: ComponentCollection.java 4599 2004-09-26 05:18:27Z oneovthafew $
package org.hibernate.test.legacy;
import java.io.Serializable;
import java.util.List;
public class ComponentCollection implements Serializable {
private String str;
private List foos;
private List floats;
public List getFoos() {
return foos;
}
public String getStr() {
return str;
}
public void setFoos(List list) {
foos = list;
}
public void setStr(String string) {
str = string;
}
public List getFloats() {
return floats;
}
public void setFloats(List list) {
floats = list;
}
}
| mit |
klaun76/gwt-pixi | src/main/java/sk/mrtn/pixi/client/particles/Emitter.java | 6113 | package sk.mrtn.pixi.client.particles;
import com.google.auto.factory.AutoFactory;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import sk.mrtn.pixi.client.*;
import sk.mrtn.pixi.client.particles.config.EmitterConfig;
/**
* Created by klaun on 25/04/16.
* TODO: test and add constructors for PathParticle
*/
@AutoFactory
@JsType(isNative = true, namespace = "PIXI.particles")
public class Emitter {
@JsConstructor
public Emitter(Container container){}
/**
* suitable for AnimatedParticle
* @param container
* @param animatedParticleArtTextures
*/
@JsConstructor
public Emitter(Container container, AnimatedParticleArtTextures[] animatedParticleArtTextures, EmitterConfig config){}
/**
* suitable for AnimatedParticle
* @param container
* @param animatedParticleArtTextureNames
*/
@JsConstructor
public Emitter(Container container, AnimatedParticleArtTextureNames[] animatedParticleArtTextureNames, EmitterConfig config){}
/**
* suitable for Particle
* @param container
* @param textures
* @param config
*/
@JsConstructor
public Emitter(Container container, Texture[] textures, EmitterConfig config){}
/**
* suitable for Particle
* @param container
* @param textureNames
* @param config
*/
@JsConstructor
public Emitter(Container container, String[] textureNames, EmitterConfig config){}
// PUBLIC FIELDS
@JsProperty
public Texture[] particleImages;
@JsProperty
public int startAlpha;
@JsProperty
public int endAlpha;
@JsProperty
public int startSpeed;
@JsProperty
public int endSpeed;
@JsProperty
public Point acceleration;
@JsProperty
public int startScale;
@JsProperty
public int endScale;
@JsProperty
public int minimumScaleMultiplier;
@JsProperty
public int[] startColor;
@JsProperty
public int[] endColor;
@JsProperty
public int minLifetime;
@JsProperty
public int maxLifetime;
@JsProperty
public int minStartRotation;
@JsProperty
public int maxStartRotation;
@JsProperty
public boolean noRotation;
@JsProperty
public int minRotationSpeed;
@JsProperty
public int maxRotationSpeed;
@JsProperty
public int particleBlendMode;
/**
* An easing function for nonlinear interpolation of values.
* Accepts a single parameter of time as a value from 0-1, inclusive.
* Expected outputs are values from 0-1, inclusive.
* TODO: test to create specific type (Function)
*/
@JsProperty
public Object customEase;
/**
* Extra data for use in custom particles. The emitter doesn't look inside, but passes it on to the particle to use in init().
* TODO: test to create specific type (Object)
*/
@JsProperty
public Object extraData;
@JsProperty
public int maxParticles;
@JsProperty
public int emitterLifetime;
@JsProperty
public Point spawnPos;
/**
* How the particles will be spawned. Valid types are "point", "rectangle", "circle", "burst", "ring".
*/
@JsProperty
public String spawnType;
@JsProperty
public Rectangle spawnRect;
@JsProperty
public Circle spawnCircle;
@JsProperty
public int particlesPerWave;
@JsProperty
public int particleSpacing;
@JsProperty
public int angleStart;
@JsProperty
public int rotation;
/**
* The world position of the emitter's owner, to add spawnPos to when
* spawning particles. To change this, use updateOwnerPos().
* Default: {x:0, y:0}
*/
@JsProperty
public Point ownerPos;
@JsProperty
public boolean addAtBack;
@JsProperty
public int particleCount;
// PUBLIC METHODS
/**
* Recycles an individual particle.
* @param particle
* @return
*/
@JsMethod
public native void recycle(Particle particle);
/**
* Updates all particles spawned by this emitter and emits new ones.
* @param delta Time elapsed since the previous frame, in seconds.
* @return
*/
@JsMethod
public native void update(double delta);
/**
* Sets the rotation of the emitter to a new value.
* @param newRot - The new rotation, in degrees.
*/
@JsMethod
public native void rotate(double newRot);
/**
* Changes the spawn position of the emitter.
* @param x - The new x value of the spawn position for the emitter.
* @param y - The new y value of the spawn position for the emitter.
*/
@JsMethod
public native void updateSpawnPos(double x, double y);
/**
* Changes the position of the emitter's owner. You should call
* this if you are adding particles to the world display
* object that your emitter's owner is moving around in.
* @param x - The new x value of the emitter's owner.
* @param y - The new y value of the emitter's owner.
* @return
*/
@JsMethod
public native void updateOwnerPos(double x, double y);
/**
* TODO: create interface/class for config
* Sets up the emitter based on the config settings.
* @param textures - A texture or array of textures to use for the particles.
* @param config - A configuration object containing settings for the emitter.
*/
@JsMethod
public native void init(Texture[] textures, EmitterConfig config);
/**
* Prevents emitter position interpolation in the next update.
* This should be used if you made a major position change
* of your emitter's owner that was not normal movement.
* @return
*/
@JsMethod
public native void resetPositionTracking();
/**
* Kills all active particles immediately.
*/
@JsMethod
public native void cleanup();
/**
* Destroys the emitter and all of its particles.
* @return
*/
@JsMethod
public native void destroy();
}
| mit |
cookingfox/lapasse-java | lapasse-rx/src/test/java/com/cookingfox/lapasse/impl/facade/LaPasseRxFacadeTest.java | 5549 | package com.cookingfox.lapasse.impl.facade;
import com.cookingfox.lapasse.api.command.bus.RxCommandBus;
import com.cookingfox.lapasse.api.command.handler.RxCommandHandler;
import com.cookingfox.lapasse.api.event.handler.EventHandler;
import com.cookingfox.lapasse.api.state.manager.RxStateManager;
import com.cookingfox.lapasse.api.state.observer.StateChanged;
import com.cookingfox.lapasse.impl.command.bus.DefaultCommandBus;
import com.cookingfox.lapasse.impl.command.bus.DefaultRxCommandBus;
import com.cookingfox.lapasse.impl.facade.LaPasseRxFacade.Builder;
import com.cookingfox.lapasse.impl.state.manager.DefaultRxStateManager;
import com.cookingfox.lapasse.impl.state.manager.DefaultStateManager;
import fixtures.example.command.IncrementCount;
import fixtures.example.event.CountIncremented;
import fixtures.example.state.CountState;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* Unit tests for {@link LaPasseRxFacade}.
*/
public class LaPasseRxFacadeTest {
//----------------------------------------------------------------------------------------------
// TESTS: LaPasseRxFacade
//----------------------------------------------------------------------------------------------
@Test
public void methods_should_not_throw() throws Exception {
LaPasseRxFacade<CountState> facade = new Builder<>(new CountState(0)).build();
facade.setCommandObserveScheduler(Schedulers.immediate());
facade.setCommandSubscribeScheduler(Schedulers.immediate());
TestSubscriber<StateChanged<CountState>> subscriber = TestSubscriber.create();
facade.observeStateChanges().subscribe(subscriber);
facade.mapCommandHandler(IncrementCount.class, new RxCommandHandler<CountState, IncrementCount, CountIncremented>() {
@Override
public Observable<CountIncremented> handle(CountState state, IncrementCount command) {
return Observable.just(new CountIncremented(command.getCount()));
}
});
facade.mapEventHandler(CountIncremented.class, new EventHandler<CountState, CountIncremented>() {
@Override
public CountState handle(CountState previousState, CountIncremented event) {
return new CountState(previousState.getCount() + event.getCount());
}
});
facade.handleCommand(new IncrementCount(123));
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
}
//----------------------------------------------------------------------------------------------
// TESTS: Builder
//----------------------------------------------------------------------------------------------
@Test(expected = IllegalArgumentException.class)
public void setCommandBus_should_throw_if_not_rx_impl() throws Exception {
Builder<CountState> builder = new Builder<>(new CountState(0));
builder.setCommandBus(new DefaultCommandBus<>(builder.getMessageStore(),
builder.getEventBus(), builder.getLoggersHelper(), builder.getStateManager()));
}
@Test
public void setCommandBus_should_accept_rx_impl() throws Exception {
Builder<CountState> builder = new Builder<>(new CountState(0));
DefaultRxCommandBus<CountState> commandBus = new DefaultRxCommandBus<>(builder.getMessageStore(),
builder.getEventBus(), builder.getLoggersHelper(), builder.getStateManager());
builder.setCommandBus(commandBus);
assertSame(commandBus, builder.getCommandBus());
}
@Test(expected = IllegalArgumentException.class)
public void setStateManager_should_throw_if_not_rx_impl() throws Exception {
CountState initialState = new CountState(0);
Builder<CountState> builder = new Builder<>(initialState);
builder.setStateManager(new DefaultStateManager<>(initialState));
}
@Test
public void setStateManager_should_accept_rx_impl() throws Exception {
CountState initialState = new CountState(0);
Builder<CountState> builder = new Builder<>(initialState);
DefaultRxStateManager<CountState> stateManager = new DefaultRxStateManager<>(initialState);
builder.setStateManager(stateManager);
assertSame(stateManager, builder.getStateManager());
}
@Test
public void setters_should_return_rx_typed_builder() throws Exception {
Builder<CountState> builder = new Builder<>(new CountState(0));
Builder<CountState> fromSetEventBus = builder.setEventBus(builder.getEventBus());
Builder<CountState> fromSetLoggersHelper = builder.setLoggersHelper(builder.getLoggersHelper());
Builder<CountState> fromSetMessageStore = builder.setMessageStore(builder.getMessageStore());
assertSame(builder, fromSetEventBus);
assertSame(builder, fromSetLoggersHelper);
assertSame(builder, fromSetMessageStore);
}
@Test
public void getters_should_create_defaults_if_null() throws Exception {
Builder<CountState> builder = new Builder<>(new CountState(0));
builder.commandBus = null;
builder.stateManager = null;
RxCommandBus<CountState> commandBus = builder.getCommandBus();
RxStateManager<CountState> stateManager = builder.getStateManager();
assertNotNull(commandBus);
assertNotNull(stateManager);
}
}
| mit |
lalongooo/checktipsplitter | app/src/main/java/com/checktipsplitter/wizard/ui/SingleChoiceFragment.java | 4301 | /*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.checktipsplitter.wizard.ui;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.checktipsplitter.R;
import com.checktipsplitter.wizard.model.Page;
import com.checktipsplitter.wizard.model.SingleFixedChoicePage;
import com.checktipsplitter.ui.ActivityMain;
import java.util.ArrayList;
import java.util.List;
public class SingleChoiceFragment extends ListFragment {
private static final String ARG_KEY = "key";
private PageFragmentCallbacks mCallbacks;
private List<String> mChoices;
private String mKey;
private Page mPage;
public static SingleChoiceFragment create(String key) {
Bundle args = new Bundle();
args.putString(ARG_KEY, key);
SingleChoiceFragment fragment = new SingleChoiceFragment();
fragment.setArguments(args);
return fragment;
}
public SingleChoiceFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mKey = args.getString(ARG_KEY);
mPage = mCallbacks.onGetPage(mKey);
SingleFixedChoicePage fixedChoicePage = (SingleFixedChoicePage) mPage;
mChoices = new ArrayList<String>();
for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) {
mChoices.add(fixedChoicePage.getOptionAt(i));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());
final ListView listView = (ListView) rootView.findViewById(android.R.id.list);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_single_choice,
android.R.id.text1,
mChoices));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Pre-select currently selected item.
new Handler().post(new Runnable() {
@Override
public void run() {
String selection = mPage.getData().getString(Page.SIMPLE_DATA_KEY);
for (int i = 0; i < mChoices.size(); i++) {
if (mChoices.get(i).equals(selection)) {
listView.setItemChecked(i, true);
break;
}
}
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(((AppCompatActivity) activity).getSupportFragmentManager().getFragments().get(0) instanceof PageFragmentCallbacks)) {
throw new ClassCastException("Activity must implement PageFragmentCallbacks");
}
mCallbacks = (PageFragmentCallbacks) ((ActivityMain) activity).getSupportFragmentManager().getFragments().get(0);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
mPage.getData().putString(Page.SIMPLE_DATA_KEY,
getListAdapter().getItem(position).toString());
mPage.notifyDataChanged();
}
}
| mit |
ronaldoWang/My_XDroidMvp | app/src/main/java/cn/droidlover/xdroidmvp/sys/ui/SearchFragment.java | 7809 | package cn.droidlover.xdroidmvp.sys.ui;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.StringUtils;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.mvp.XFragment;
import cn.droidlover.xdroidmvp.sys.R;
import cn.droidlover.xdroidmvp.sys.event.supertension.cablemanage.CablemanageEvent;
import cn.droidlover.xdroidmvp.sys.ui.common.SearchJsonCommon;
import cn.droidlover.xdroidmvp.sys.ui.supertension.cablemanage.DlCableEquFragment;
import cn.droidlover.xdroidmvp.sys.ui.supertension.cablemanage.RightSideslipLay;
import cn.droidlover.xdroidmvp.sys.ui.tree.holder.HeaderHolder;
import cn.droidlover.xdroidmvp.sys.ui.tree.holder.IconTreeItemHolder;
import cn.droidlover.xdroidmvp.sys.ui.tree.holder.ProfileHolder;
/**
* Created by ronaldo on 2017/6/6.
*/
public class SearchFragment extends XFragment {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.main_drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.main_left_drawer_layout)
RelativeLayout leftMenulayout;
@BindView(R.id.main_right_drawer_layout)
RelativeLayout rightMessagelayout;
AndroidTreeView tView;//菜单视图
static String tag = "";//SearchEventTag
@Override
public void initData(Bundle savedInstanceState) {
}
@Override
public void initView(Bundle savedInstanceState) {
initEvent();
initLeftLayout();
//加载Toolbar
setHasOptionsMenu(true);
//StatusBarCompat.translucentStatusBar(getActivity());
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
openRightLayout();
break;
}
return true;
}
});
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerToggle.syncState();//初始化状态
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void initRightLayout(String jsonPath, String tag) {
this.tag = tag;
rightMessagelayout.removeAllViews();
if (!StringUtils.isEmpty(jsonPath)) {
RightSideslipLay menuHeaderView = new RightSideslipLay(getActivity(), jsonPath);
menuHeaderView.setCloseMenuCallBack(new RightSideslipLay.CloseMenuCallBack() {
@Override
public void setupCloseMean() {
openRightLayout();
}
});
menuHeaderView.setDoSearchCallBack(new RightSideslipLay.DoSearchCallBack() {
@Override
public void doSearch(Map<String, List> searchMap) {
BusProvider.getBus().post(new CablemanageEvent(searchMap, SearchFragment.tag));
}
});
rightMessagelayout.addView(menuHeaderView);
}
}
private void initLeftLayout() {
View menuView = getActivity().getLayoutInflater().inflate(R.layout.layout_search_menu, null);
final ViewGroup containerView = (ViewGroup) menuView.findViewById(R.id.ll_menu);
final TreeNode root = TreeNode.root();
TreeNode sbzl = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_person, "设备资料", null)).setViewHolder(new ProfileHolder(getActivity()));
TreeNode xsjl = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_person, "巡视记录", null)).setViewHolder(new ProfileHolder(getActivity()));
//TreeNode clark = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_person, "Clark Kent")).setViewHolder(new ProfileHolder(getActivity()));
//TreeNode barry = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_person, "Barry Allen")).setViewHolder(new ProfileHolder(getActivity()));
TreeNode dlsbzl = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_people, "电缆设备资料", "sbzl_dlsbzl")).setViewHolder(new HeaderHolder(getActivity()));
TreeNode tjsszl = new TreeNode(new IconTreeItemHolder.IconTreeItem(R.string.ic_place, "土鉴设施资料", "sbzl_tjsszl")).setViewHolder(new HeaderHolder(getActivity()));
sbzl.addChildren(dlsbzl, tjsszl);
root.addChildren(sbzl, xsjl);
tView = new AndroidTreeView(getActivity(), root);
tView.setDefaultAnimation(true);
tView.setDefaultContainerStyle(R.style.TreeNodeStyleDivided, true);
tView.setDefaultNodeClickListener(nodeClickListener);
tView.setDefaultViewHolder(IconTreeItemHolder.class);
containerView.addView(tView.getView());
leftMenulayout.addView(menuView);
}
private void initEvent() {
mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerStateChanged(int arg0) {
}
@Override
public void onDrawerSlide(View arg0, float arg1) {
}
@Override
public void onDrawerOpened(View arg0) {
}
@Override
public void onDrawerClosed(View arg0) {
}
});
}
//左边菜单开关事件
public void openLeftLayout() {
if (mDrawerLayout.isDrawerOpen(leftMenulayout)) {
mDrawerLayout.closeDrawer(leftMenulayout);
} else {
mDrawerLayout.openDrawer(leftMenulayout);
}
}
// 右边菜单开关事件
public void openRightLayout() {
if (mDrawerLayout.isDrawerOpen(rightMessagelayout)) {
mDrawerLayout.closeDrawer(rightMessagelayout);
} else {
mDrawerLayout.openDrawer(rightMessagelayout);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_list, menu);
}
private TreeNode.TreeNodeClickListener nodeClickListener = new TreeNode.TreeNodeClickListener() {
@Override
public void onClick(TreeNode node, Object value) {
IconTreeItemHolder.IconTreeItem item = (IconTreeItemHolder.IconTreeItem) value;
String url = item.url;
if (StringUtils.isEmpty(url)) {
return;
}
if ("sbzl_dlsbzl".equals(url)) {
initRightLayout(SearchJsonCommon.DlCableEqu, CablemanageEvent.dlCableEquFragment);
FragmentUtils.replaceFragment(getActivity().getSupportFragmentManager(), new DlCableEquFragment(), R.id.main_content_frame, true);
}
openLeftLayout();//点击菜单自动收缩左边
}
};
@Override
public int getLayoutId() {
return R.layout.fragment_search;
}
@Override
public Object newP() {
return null;
}
public static SearchFragment newInstance() {
return new SearchFragment();
}
}
| mit |
alexandros-s/dice-android-app | src/com/hexahedron/faterpgdice/events/TotalChangedEvent.java | 234 | package com.hexahedron.faterpgdice.events;
public class TotalChangedEvent {
private int mtotal;
public TotalChangedEvent(int total) {
mtotal = total;
}
public int getTotal() {
return mtotal;
}
}
| mit |
catedrasaes-umu/NoSQLDataEngineering | projects/es.um.nosql.streaminginference/src/es/um/nosql/streaminginference/NoSQLSchema/Type.java | 513 | /**
*/
package es.um.nosql.streaminginference.NoSQLSchema;
import java.io.Serializable;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Type</b></em>'.
* <!-- end-user-doc -->
*
*
* @see es.um.nosql.streaminginference.NoSQLSchema.NoSQLSchemaPackage#getType()
* @model abstract="true" superTypes="es.um.nosql.streaminginference.NoSQLSchema.Serializable"
* @generated
*/
public interface Type extends EObject, Serializable {
} // Type
| mit |
CS2103JAN2017-T09-B1/main | src/main/java/seedu/today/logic/parser/EditCommandParser.java | 4098 | package seedu.today.logic.parser;
import static seedu.today.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.ocpsoft.prettytime.shade.edu.emory.mathcs.backport.java.util.Arrays;
import seedu.today.commons.core.Messages;
import seedu.today.commons.exceptions.IllegalValueException;
import seedu.today.logic.LogicManager;
import seedu.today.logic.commands.Command;
import seedu.today.logic.commands.EditCommand;
import seedu.today.logic.commands.EditCommand.EditTaskDescriptor;
import seedu.today.logic.commands.IncorrectCommand;
import seedu.today.model.tag.UniqueTagList;
import seedu.today.model.task.DateTime;
import seedu.today.model.task.Name;
//@@author A0144422R
/**
* Parses input arguments and creates a new EditCommand object
*/
public class EditCommandParser extends SeperableParser {
/**
* Parses the given {@code String} of arguments in the context of the
* EditCommand and returns an EditCommand object for execution.
*/
public Command parse(String args, LogicManager logic) {
assert args != null;
this.args = args.trim();
String[] indexAndArguments = this.args.split("\\s+", 2);
if (indexAndArguments.length < 2) {
return new IncorrectCommand(MESSAGE_INVALID_COMMAND_FORMAT);
}
EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor();
Optional<String> index = ParserUtil.parseIndex(indexAndArguments[0]);
if (!index.isPresent()) {
return new IncorrectCommand(MESSAGE_INVALID_COMMAND_FORMAT);
}
this.args = indexAndArguments[1];
String tags[] = getTags();
try {
editTaskDescriptor.setTags(parseTagsForEdit(Arrays.asList(tags)));
} catch (IllegalValueException e1) {
return new IncorrectCommand(MESSAGE_INVALID_COMMAND_FORMAT);
}
// find and remove tags
// find and remove starting time and deadline if the syntax is "<name>
// from <starting time> to <deadline>"
List<Date> startingTimeAndDeadline = getStartingTimeAndDeadline();
if (startingTimeAndDeadline != null) {
editTaskDescriptor
.setStartingTime(Optional.of(new DateTime(startingTimeAndDeadline.get(CliSyntax.STARTING_INDEX))));
editTaskDescriptor
.setDeadline(Optional.of(new DateTime(startingTimeAndDeadline.get(CliSyntax.DEADLINE_INDEX))));
} else {
// find and remove starting time and deadline if the syntax is
// "<name> due <deadline>"
Date deadline = getDeadline();
if (deadline != null) {
editTaskDescriptor.setDeadline(Optional.of(new DateTime(deadline)));
}
}
if (!this.args.trim().equals("")) {
try {
editTaskDescriptor.setName(Optional.of(new Name(this.args.trim())));
} catch (IllegalValueException e) {
return new IncorrectCommand(e.getMessage());
}
}
if (!logic.isValidUIIndex(index.get())) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
return new EditCommand(logic.parseUIIndex(index.get()), editTaskDescriptor);
}
/**
* Parses {@code Collection<String> tags} into an
* {@code Optional<UniqueTagList>} if {@code tags} is non-empty. If
* {@code tags} contain only one element which is an empty string, it will
* be parsed into a {@code Optional<UniqueTagList>} containing zero tags.
*/
private Optional<UniqueTagList> parseTagsForEdit(Collection<String> tags) throws IllegalValueException {
assert tags != null;
if (tags.isEmpty()) {
return Optional.empty();
}
Collection<String> tagSet = tags.size() == 1 && tags.contains("") ? Collections.emptySet() : tags;
return Optional.of(ParserUtil.parseTags(tagSet));
}
}
| mit |
SpongePowered/Sponge | src/mixins/java/org/spongepowered/common/mixin/core/world/level/block/entity/SignBlockEntityMixin.java | 2647 | /*
* 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.mixin.core.world.level.block.entity;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.block.entity.SignBlockEntity;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.service.permission.PermissionService;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.bridge.commands.CommandSourceProviderBridge;
import org.spongepowered.common.bridge.permissions.SubjectBridge;
@Mixin(SignBlockEntity.class)
public abstract class SignBlockEntityMixin extends BlockEntityMixin implements SubjectBridge, CommandSourceProviderBridge {
@Shadow public abstract CommandSourceStack shadow$createCommandSourceStack(final @Nullable ServerPlayer player);
@Override
public String bridge$getSubjectCollectionIdentifier() {
return PermissionService.SUBJECTS_COMMAND_BLOCK;
}
@Override
public Tristate bridge$permDefault(final String permission) {
return Tristate.TRUE;
}
@Override
public CommandSourceStack bridge$getCommandSource(final Cause cause) {
return this.shadow$createCommandSourceStack(cause.first(ServerPlayer.class).orElse(null));
}
}
| mit |
conveyal/aggregate-disser | src/main/java/com/conveyal/disser/Disser.java | 17376 | package com.conveyal.disser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureSource;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.Feature;
import org.opengis.feature.GeometryAttribute;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.spatial.BBOX;
import org.opengis.geometry.BoundingBox;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.TopologyException;
public class Disser {
static boolean GEOM_TOLERANT = false;
public static void main(String[] args) throws Exception {
if( args.length < 5 ) {
System.out.println( "usage: cmd [--(discrete|shapefile)] indicator_shp indicator_fld diss_shp diss_fld output_fn" );
return;
}
int argOfs = 0;
boolean discrete = args[0].equals("--discrete");
boolean shapefile = args[0].equals("--shapefile");
if(discrete || shapefile){
argOfs=1;
}
String indicator_shp = args[argOfs+0];
String indFldExpression = args[argOfs+1];
String diss_shp = args[argOfs+2];
String dissFldExpression = args[argOfs+3];
String output_fn = args[argOfs+4];
//==== get indicator shapefile
FeatureSource<?, ?> indicatorSource = getFeatureSource(indicator_shp);
//==== get diss source
FeatureSource<?, ?> dissSource = getFeatureSource(diss_shp);
//==== make sure both shapefiles have the same CRS
CoordinateReferenceSystem crs1 = indicatorSource.getSchema().getCoordinateReferenceSystem();
CoordinateReferenceSystem crs2 = dissSource.getSchema().getCoordinateReferenceSystem();
if( !crs1.equals(crs2) ){
throw new Exception( "Coordinate systems don't match. "+crs1+"\n\n"+crs2 );
}
//==== loop through indicator shapefile, finding overlapping diss items
HashMap<Feature, ArrayList<Feature>> dissToInd = collectIndByDiss(
indicatorSource, dissSource);
if(dissToInd.size()==0){
System.out.println( "no overlaps found." );
return;
}
// register each diss with the inds, along with the ind's share of the diss's magnitude
HashMap<Feature, ArrayList<DissShare>> indDissShares = collectDissSharesByInd(
dissFldExpression, dissToInd);
// dole out the ind's magnitude in proportion to the diss's mag share, accumulating under the diss
HashMap<Feature, Double> dissMags = distributeIndToDisses(
indFldExpression, indDissShares);
// go through the dissMag list and emit points at centroids
if(shapefile){
writeToShapefile(output_fn, dissMags);
} else {
writeToCSV(discrete, output_fn, dissMags);
}
System.out.print("done.\n");
}
private static void writeToCSV(boolean discrete, String output_fn,
HashMap<Feature, Double> dissMags) throws FileNotFoundException,
UnsupportedEncodingException {
System.out.print( "printing to file..." );
PrintWriter writer = new PrintWriter(output_fn, "UTF-8");
writer.println("lon,lat,mag");
Random rand = new Random(); //could come in handy if we're doing a discrete output
for( Entry<Feature, Double> entry : dissMags.entrySet() ) {
Feature diss = entry.getKey();
Geometry dissGeom = (Geometry)diss.getDefaultGeometryProperty().getValue();
double mag = entry.getValue();
if(discrete){
// probabilistically round magnitude to an integer. This way if there's 5 disses with mag 0.2, on average
// one will be 1 and the others 0, instead of rounding all down to 0.
int discreteMag;
double remainder = mag-Math.floor(mag); //number between 0 and 1
if(remainder<rand.nextDouble()){
//remainder is smaller than random integer; relatively likely for small remainders
//so when this happens we'll round down
discreteMag = (int)Math.floor(mag);
} else {
discreteMag = (int)Math.ceil(mag);
}
BoundingBox bb = diss.getBounds();
for(int j=0; j<discreteMag; j++){
Point pt = getRandomPoint( bb, dissGeom );
if(pt==null){
continue; //something went wrong; act cool
}
writer.println( pt.getX()+","+pt.getY()+",1");
}
} else {
Point centroid = dissGeom.getCentroid();
if(mag>0){
writer.println( centroid.getX()+","+centroid.getY()+","+mag);
}
}
}
writer.flush();
writer.close();
}
private static void writeToShapefile(String output_fn,
HashMap<Feature, Double> dissMags) throws MalformedURLException,
IOException {
System.out.println( "printing to shapefile..." );
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", new File(output_fn).toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore outputStore = (ShapefileDataStore)dataStoreFactory.createNewDataStore(params);
outputStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
// build the type
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("diss");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("the_geom", MultiPolygon.class);
builder.length(16).add("mag", Float.class);
final SimpleFeatureType dissType = builder.buildFeatureType();
outputStore.createSchema(dissType);
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(dissType);
int j=0;
for(Entry<Feature, Double> entry : dissMags.entrySet()) {
if(j%1000==0){
System.out.println("writing feature "+j);
}
Feature diss = entry.getKey();
Geometry dissGeom = (Geometry)diss.getDefaultGeometryProperty().getValue();
double mag = entry.getValue();
featureBuilder.add(dissGeom);
featureBuilder.add(mag);
SimpleFeature feature = featureBuilder.buildFeature(null);
featureCollection.add(feature);
j++;
}
Transaction transaction = new DefaultTransaction("create");
String outputTypeName = outputStore.getTypeNames()[0];
SimpleFeatureSource featureSource = outputStore.getFeatureSource(outputTypeName);
if (featureSource instanceof SimpleFeatureStore)
{
System.out.println("committing");
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
featureStore.addFeatures(featureCollection);
transaction.commit();
transaction.close();
}
}
private static HashMap<Feature, Double> distributeIndToDisses(
String indicator_fld,
HashMap<Feature, ArrayList<DissShare>> indDissShares)
throws Exception {
System.out.println( "doling out ind magnitudes to disses" );
HashMap<Feature,Double> dissMags = new HashMap<Feature,Double>();
for( Entry<Feature, ArrayList<DissShare>> entry : indDissShares.entrySet() ){
Feature ind = entry.getKey();
ArrayList<DissShare> dissShares = entry.getValue();
// count up total shares
int totalDissMag = 0;
int totalDiss = 0;
for(DissShare dissShare : dissShares){
totalDissMag += dissShare.mag;
totalDiss += 1;
}
// get magnitude of ind
double indMag = getFieldsByExpression( indicator_fld, ind );
if(indMag==0.0){
continue;
}
// for every diss associated with ind
for( DissShare dissShare : dissShares ){
// find fraction of ind doleable to diss
double fraction;
if(totalDissMag>0){
fraction = dissShare.mag/totalDissMag;
} else {
// if all disses under ind have 0 magnitude, but the
// ind still has magnitude to dole out, dole out equally
// to all disses.
fraction = 1.0/totalDiss;
}
double doleable = indMag*fraction;
if(doleable==0.0){
continue;
}
// accumulate values doled out to disses
Double dissMag = dissMags.get(dissShare.diss);
if(dissMag==null){
dissMag = new Double(0);
}
dissMag += doleable;
dissMags.put(dissShare.diss,dissMag);
}
}
return dissMags;
}
private static HashMap<Feature, ArrayList<DissShare>> collectDissSharesByInd(
String dissFldExpression,
HashMap<Feature, ArrayList<Feature>> dissToInd) throws Exception {
System.out.println( "accumulating diss shares under inds" );
HashMap<Feature,ArrayList<DissShare>> indDissShares = new HashMap<Feature,ArrayList<DissShare>>();
for( Entry<Feature, ArrayList<Feature>> entry : dissToInd.entrySet() ){
Feature diss = entry.getKey();
ArrayList<Feature> inds = entry.getValue();
// determine diss's magnitude
double mag = getFieldsByExpression(dissFldExpression, diss);
Geometry dissGeo = (Geometry)diss.getDefaultGeometryProperty().getValue();
double dissGeoArea = dissGeo.getArea();
for(Feature ind : inds){
// find the fraction of diss overlapping each ind shape
Geometry indGeo = (Geometry)ind.getDefaultGeometryProperty().getValue();
Geometry overlap;
try{
overlap = dissGeo.intersection(indGeo);
} catch (TopologyException e){
if(GEOM_TOLERANT){
// something strange happened; carry on
continue;
} else{
throw e;
}
}
double overlapArea = overlap.getArea();
double fraction = overlapArea/dissGeoArea;
// assign the magnitude proportionately
double share = fraction*mag;
if(share==0.0){
continue;
}
// then register the diss feature's share with the ind feature
ArrayList<DissShare> shares = indDissShares.get(ind);
if(shares==null){
shares = new ArrayList<DissShare>();
indDissShares.put(ind, shares);
}
shares.add(new DissShare(diss,share));
}
}
return indDissShares;
}
private static HashMap<Feature, ArrayList<Feature>> collectIndByDiss(
FeatureSource<?, ?> indicatorSource, FeatureSource<?, ?> dissSource)
throws IOException {
HashMap<Feature,ArrayList<Feature>> dissToInd = new HashMap<Feature,ArrayList<Feature>>();
FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
FeatureType schema = dissSource.getSchema();
String geometryPropertyName = schema.getGeometryDescriptor().getLocalName();
CoordinateReferenceSystem dissCRS = schema.getGeometryDescriptor().getCoordinateReferenceSystem();
// get the part of the indicator file where diss items will be found
ReferencedEnvelope dissBBox = dissSource.getBounds();
String indicatorPropertyName = indicatorSource.getSchema().getGeometryDescriptor().getLocalName();
BBOX dissFilter = ff.bbox(ff.property(indicatorPropertyName), dissBBox);
FeatureCollection<?, ?> indCollection = indicatorSource.getFeatures(dissFilter);
FeatureIterator<?> indIterator = indCollection.features();
int n = indCollection.size();
System.out.println( "accumulating ind geoms under disses" );
int i=0;
while( indIterator.hasNext() ){
if(i%100==0){
System.out.print( "\r"+i+"/"+n+" ("+(100*(float)i)/n+"%)" );
}
Feature ind = (Feature) indIterator.next();
GeometryAttribute indGeoAttr = ind.getDefaultGeometryProperty();
Geometry indGeo = (Geometry)indGeoAttr.getValue();
// Get every diss geometry that intersects with the indicator geometry
ReferencedEnvelope bbox = new ReferencedEnvelope(dissCRS);
bbox.setBounds(indGeoAttr.getBounds());
BBOX filter = ff.bbox(ff.property(geometryPropertyName), bbox);
FeatureCollection<?, ?> dissCollection = dissSource.getFeatures(filter);
FeatureIterator<?> dissIterator = dissCollection.features();
// register the ind feature with the diss
while(dissIterator.hasNext()){
Feature diss = (Feature)dissIterator.next();
GeometryAttribute dissGeoAttr = diss.getDefaultGeometryProperty();
Geometry dissGeo = (Geometry)dissGeoAttr.getValue();
if(dissGeo.intersects(indGeo) || dissGeo.equals(indGeo)){
ArrayList<Feature> inds = dissToInd.get(diss);
if(inds==null){
inds = new ArrayList<Feature>();
dissToInd.put(diss, inds);
}
inds.add(ind);
}
}
dissIterator.close();
i++;
}
System.out.println(""); //print newline after the progress meter
return dissToInd;
}
private static FeatureSource<?, ?> getFeatureSource(String shp_filename)
throws MalformedURLException, IOException {
// construct shapefile factory
File file = new File( shp_filename );
Map<String,URL> map = new HashMap<String,URL>();
map.put( "url", file.toURI().toURL() );
DataStore dataStore = DataStoreFinder.getDataStore( map );
// get shapefile as generic 'feature source'
String typeName = dataStore.getTypeNames()[0];
FeatureSource<?, ?> source = dataStore.getFeatureSource( typeName );
return source;
}
private static double getFieldsByExpression(String fieldExpression,
Feature feature) throws Exception {
double mag=0;
String[] dissFlds = fieldExpression.split("\\+");
for(String dissFld : dissFlds ){
mag += parseField(dissFld.trim(), feature);
}
return mag;
}
private static double parseField(String diss_fld, Feature diss)
throws Exception {
double mag;
if(diss_fld.equals("::area::")){
mag = ((Geometry)diss.getDefaultGeometryProperty().getValue()).getArea();
} else {
Property magProp = diss.getProperty(diss_fld);
if(magProp==null){
String propStrings = "";
Collection<Property> props = diss.getProperties();
for( Property prop : props ){
propStrings += " "+prop.getName();
}
throw new Exception("Property '"+diss_fld+"' not found. Options are:"+propStrings+"." );
}
Class<?> cls = magProp.getType().getBinding();
Object propVal = diss.getProperty( diss_fld ).getValue();
if(propVal==null){
return 0;
}
if(cls.equals(Long.class)){
mag = (Long)propVal;
} else if(cls.equals(Integer.class)){
mag = (Integer)propVal;
} else if(cls.equals(Double.class)){
mag = (Double)propVal;
} else if(cls.equals(Float.class)){
mag = (Float)propVal;
} else {
throw new Exception( "Diss property has unkown type "+cls );
}
}
return mag;
}
private static Point getRandomPoint(BoundingBox bb, Geometry geom) {
Random rand = new Random();
GeometryFactory gf = new GeometryFactory();
Point pt = null;
for(int i=0; i<1000; i++){
double x = randdouble(rand, bb.getMinX(),bb.getMaxX());
double y = randdouble(rand, bb.getMinY(),bb.getMaxY());
pt = gf.createPoint( new Coordinate(x,y) );
if(geom.contains(pt)){
return pt;
}
}
return null;
}
private static double randdouble(Random rand, double minX, double maxX) {
return minX + rand.nextDouble()*(maxX-minX);
}
}
| mit |
Playtika/testcontainers-spring-boot | embedded-artifactory/src/test/java/com/playtika/test/artifactory/BaseEmbeddedArtifactoryTest.java | 941 | package com.playtika.test.artifactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = BaseEmbeddedArtifactoryTest.TestConfiguration.class
)
class BaseEmbeddedArtifactoryTest {
@Value("${embedded.artifactory.host}")
protected String artifactoryHost;
@Value("${embedded.artifactory.port}")
protected int artifactoryPort;
@Autowired
ConfigurableListableBeanFactory beanFactory;
@EnableAutoConfiguration
@Configuration
static class TestConfiguration {
}
} | mit |
btrekkie/reductions | src/com/github/btrekkie/reductions/pokemon/PokemonProblem.java | 3206 | package com.github.btrekkie.reductions.pokemon;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.github.btrekkie.programmatic_image.ProgrammaticImageFrame;
import com.github.btrekkie.reductions.bool.Literal;
import com.github.btrekkie.reductions.bool.ThreeSat;
import com.github.btrekkie.reductions.bool.ThreeSatClause;
import com.github.btrekkie.reductions.bool.Variable;
import com.github.btrekkie.reductions.planar.IPlanarGadget;
import com.github.btrekkie.reductions.planar.Point;
import com.github.btrekkie.reductions.planar.ThreeSatPlanarGadgetLayout;
/**
* A "Pokemon problem" instance, which is the problem of whether it is possible for the player to get from a given start
* location to a given finish location. This works for any version of Pokemon.
*/
public class PokemonProblem {
/**
* A map from each gadget to the position of its top-left corner. We regard the region not covered by gadgets as
* filled with tiles of type PokemonTile.ROCK.
*/
public Map<PokemonGadget, Point> gadgets;
public PokemonProblem(Map<PokemonGadget, Point> gadgets) {
this.gadgets = gadgets;
}
/**
* Returns a PokemonProblem that is equivalent to the specified 3-SAT problem, i.e. for which the player can reach
* the finish iff the 3-SAT problem has a satisfying assignment.
*/
public static PokemonProblem reduceFrom(ThreeSat threeSat) {
Map<IPlanarGadget, Point> gadgets = ThreeSatPlanarGadgetLayout.layout(
threeSat, Pokemon3SatPlanarGadgetFactory.instance, PokemonWireFactory.instance,
PokemonBarrierFactory.instance, new PokemonStartGadget(), 0, new PokemonFinishGadget(), 0);
Map<PokemonGadget, Point> pokemonGadgets = new LinkedHashMap<PokemonGadget, Point>();
for (Entry<IPlanarGadget, Point> entry : gadgets.entrySet()) {
pokemonGadgets.put((PokemonGadget)entry.getKey(), entry.getValue());
}
return new PokemonProblem(pokemonGadgets);
}
/** Displays a PokemonProblem created as a reduction from a 3-SAT problem. */
public static void main(String[] args) {
Variable variable1 = new Variable();
Variable variable2 = new Variable();
Variable variable3 = new Variable();
ThreeSatClause clause1 = new ThreeSatClause(
new Literal(variable1, false), new Literal(variable2, true), new Literal(variable3, false));
ThreeSatClause clause2 = new ThreeSatClause(
new Literal(variable1, false), new Literal(variable2, false), new Literal(variable2, true));
ThreeSatClause clause3 = new ThreeSatClause(
new Literal(variable1, true), new Literal(variable2, true), new Literal(variable3, true));
ThreeSatClause clause4 = new ThreeSatClause(
new Literal(variable1, true), new Literal(variable2, true), new Literal(variable3, true));
ThreeSat threeSat = new ThreeSat(Arrays.asList(clause1, clause2, clause3, clause4));
PokemonProblem problem = PokemonProblem.reduceFrom(threeSat);
new ProgrammaticImageFrame(new PokemonRenderer(problem)).setVisible(true);
}
}
| mit |
sogeti-java-nl/Assignments | 2015/SmithNumber/SmithNumberCaseTest/PrimeFactorsVogel.java | 897 | import java.util.ArrayList;
import java.util.List;
public class PrimeFactorsVogel {
public static List<Integer> primeFactors(int number) {
int n = number;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
return factors;
}
public static void main(String[] args) {
System.out.println("Primefactors of 600");
for (Integer integer : primeFactors(600)) {
System.out.println(integer);
}
System.out.println("Primefactors of 3");
for (Integer integer : primeFactors(3)) {
System.out.println(integer);
}
System.out.println("Primefactors of 32");
for (Integer integer : primeFactors(32)) {
System.out.println(integer);
}
}
}
| mit |
devromik/java-web-app-skeleton | app/src/test/java/net/devromik/app/MandatoryJvmPropertyNotDefinedExceptionTest.java | 484 | package net.devromik.app;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class MandatoryJvmPropertyNotDefinedExceptionTest {
@Test
public void messageShowsNotDefinedProperty() {
MandatoryJvmPropertyNotDefinedException exception = new MandatoryJvmPropertyNotDefinedException("propertyName");
assertThat(exception.getMessage(), is("Mandatory JVM property \"propertyName\" is not defined"));
}
} | mit |
jonesd/udanax-gold2java | abora-gold/src/generated-sources/translator/info/dgjones/abora/gold/be/ents/OrglRoot.java | 23521 | /*
* Abora-Gold
* Part of the Abora hypertext project: http://www.abora.org
* Copyright 2003, 2005 David G Jones
*
* Translated from Udanax-Gold source code: http://www.udanax.com
* Copyright 1979-1999 Udanax.com. All rights reserved
*/
package info.dgjones.abora.gold.be.ents;
import info.dgjones.abora.gold.arrange.Arrangement;
import info.dgjones.abora.gold.backrec.ResultRecorder;
import info.dgjones.abora.gold.be.basic.BeCarrier;
import info.dgjones.abora.gold.be.basic.BeEdition;
import info.dgjones.abora.gold.be.basic.BeLabel;
import info.dgjones.abora.gold.be.basic.BeRangeElement;
import info.dgjones.abora.gold.be.basic.ID;
import info.dgjones.abora.gold.be.canopy.BertCrum;
import info.dgjones.abora.gold.be.canopy.PropFinder;
import info.dgjones.abora.gold.be.canopy.SensorCrum;
import info.dgjones.abora.gold.be.ents.ActualOrglRoot;
import info.dgjones.abora.gold.be.ents.EmptyOrglRoot;
import info.dgjones.abora.gold.be.ents.HBottomCrum;
import info.dgjones.abora.gold.be.ents.HistoryCrum;
import info.dgjones.abora.gold.be.ents.Loaf;
import info.dgjones.abora.gold.be.ents.OPart;
import info.dgjones.abora.gold.be.ents.OrglRoot;
import info.dgjones.abora.gold.collection.basic.PrimDataArray;
import info.dgjones.abora.gold.collection.basic.PtrArray;
import info.dgjones.abora.gold.collection.steppers.Stepper;
import info.dgjones.abora.gold.collection.tables.ScruTable;
import info.dgjones.abora.gold.detect.FeFillRangeDetector;
import info.dgjones.abora.gold.fossil.RecorderFossil;
import info.dgjones.abora.gold.java.AboraBlockSupport;
import info.dgjones.abora.gold.java.AboraSupport;
import info.dgjones.abora.gold.java.exception.AboraRuntimeException;
import info.dgjones.abora.gold.java.exception.PasseException;
import info.dgjones.abora.gold.java.exception.SubclassResponsibilityException;
import info.dgjones.abora.gold.java.missing.HRoot;
import info.dgjones.abora.gold.java.missing.XnSensor;
import info.dgjones.abora.gold.java.missing.smalltalk.Set;
import info.dgjones.abora.gold.nkernel.FeRangeElement;
import info.dgjones.abora.gold.props.PropChange;
import info.dgjones.abora.gold.spaces.basic.CoordinateSpace;
import info.dgjones.abora.gold.spaces.basic.Dsp;
import info.dgjones.abora.gold.spaces.basic.Mapping;
import info.dgjones.abora.gold.spaces.basic.OrderSpec;
import info.dgjones.abora.gold.spaces.basic.Position;
import info.dgjones.abora.gold.spaces.basic.XnRegion;
import info.dgjones.abora.gold.tclude.TrailBlazer;
import info.dgjones.abora.gold.traces.TracePosition;
import info.dgjones.abora.gold.turtle.Agenda;
import info.dgjones.abora.gold.turtle.AgendaItem;
import info.dgjones.abora.gold.x.PrimSpec;
import info.dgjones.abora.gold.xcvr.Rcvr;
import info.dgjones.abora.gold.xcvr.Xmtr;
import info.dgjones.abora.gold.xpp.basic.Heaper;
public class OrglRoot extends OPart {
protected HBottomCrum myHCrum;
/*
udanax-top.st:9563:
OPart subclass: #OrglRoot
instanceVariableNames: 'myHCrum {HBottomCrum}'
classVariableNames: ''
poolDictionaries: ''
category: 'Xanadu-Be-Ents'!
*/
/*
udanax-top.st:9567:
(OrglRoot getOrMakeCxxClassDescription)
attributes: ((Set new) add: #SHEPHERD.PATRIARCH; add: #COPY; add: #DEFERRED; add: #DEFERRED.LOCKED; yourself)!
*/
/*
udanax-top.st:9816:
OrglRoot class
instanceVariableNames: ''!
*/
/*
udanax-top.st:9819:
(OrglRoot getOrMakeCxxClassDescription)
attributes: ((Set new) add: #SHEPHERD.PATRIARCH; add: #COPY; add: #DEFERRED; add: #DEFERRED.LOCKED; yourself)!
*/
public static void initializeClassAttributes() {
AboraSupport.findAboraClass(OrglRoot.class).setAttributes( new Set().add("SHEPHERDPATRIARCH").add("COPY").add("DEFERRED").add("DEFERREDLOCKED"));
/*
Generated during transformation: AddMethod
*/
}
public XnRegion attachTrailBlazer(TrailBlazer blazer) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9572:OrglRoot methodsFor: 'backfollow'!
{XnRegion} attachTrailBlazer: blazer {TrailBlazer}
self subclassResponsibility!
*/
}
/**
* check any recorders that might be triggered by a change in the stamp
*/
public void checkRecorders(PropFinder finder, SensorCrum scrum) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9576:OrglRoot methodsFor: 'backfollow'!
{void} checkRecorders: finder {PropFinder}
with: scrum {SensorCrum | NULL}
"check any recorders that might be triggered by a change in the stamp"
self subclassResponsibility!
*/
}
public void checkTrailBlazer(TrailBlazer blazer) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9582:OrglRoot methodsFor: 'backfollow'!
{void} checkTrailBlazer: blazer {TrailBlazer}
self subclassResponsibility!
*/
}
public TrailBlazer fetchTrailBlazer() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9586:OrglRoot methodsFor: 'backfollow'!
{TrailBlazer | NULL} fetchTrailBlazer
self subclassResponsibility!
*/
}
/**
* NOTE: The AgendaItem returned is not yet scheduled. Doing so is up to my caller.
*/
public AgendaItem propChanger(PropChange change) {
return myHCrum.propChanger(change);
/*
udanax-top.st:9590:OrglRoot methodsFor: 'backfollow'!
{AgendaItem} propChanger: change {PropChange}
"NOTE: The AgendaItem returned is not yet scheduled. Doing so is up to my caller."
^myHCrum propChanger: change!
*/
}
/**
* A Detector has been added to my parent. Walk down and trigger it on all non-partial stuff
*/
public void triggerDetector(FeFillRangeDetector detect) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9595:OrglRoot methodsFor: 'backfollow'!
{void} triggerDetector: detect {FeFillRangeDetector}
"A Detector has been added to my parent. Walk down and trigger it on all non-partial stuff"
self subclassResponsibility!
*/
}
/**
* Ensure the my bertCrum is not be leafward of newBCrum.
*/
public boolean updateBCrumTo(BertCrum newBCrum) {
if (myHCrum.propagateBCrum(newBCrum)) {
diskUpdate();
return true;
}
return false;
/*
udanax-top.st:9600:OrglRoot methodsFor: 'backfollow'!
{BooleanVar} updateBCrumTo: newBCrum {BertCrum}
"Ensure the my bertCrum is not be leafward of newBCrum."
(myHCrum propagateBCrum: newBCrum)
ifTrue:
[self diskUpdate.
^true].
^false!
*/
}
/**
* the kind of domain elements allowed
*/
public CoordinateSpace coordinateSpace() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9611:OrglRoot methodsFor: 'accessing'!
{CoordinateSpace} coordinateSpace
"the kind of domain elements allowed"
self subclassResponsibility!
*/
}
public int count() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9616:OrglRoot methodsFor: 'accessing'!
{IntegerVar} count
self subclassResponsibility!
*/
}
public XnRegion domain() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9619:OrglRoot methodsFor: 'accessing'!
{XnRegion} domain
self subclassResponsibility!
*/
}
/**
* get an individual element
*/
public FeRangeElement fetch(Position key, BeEdition edition) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9622:OrglRoot methodsFor: 'accessing'!
{FeRangeElement | NULL} fetch: key {Position} with: edition {BeEdition}
"get an individual element"
self subclassResponsibility!
*/
}
/**
* Get or Make the BeRangeElement at the location.
*/
public BeRangeElement getBe(Position key) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9627:OrglRoot methodsFor: 'accessing'!
{BeRangeElement} getBe: key {Position}
"Get or Make the BeRangeElement at the location."
self subclassResponsibility!
*/
}
public HistoryCrum hCrum() {
return myHCrum;
/*
udanax-top.st:9632:OrglRoot methodsFor: 'accessing'!
{HistoryCrum} hCrum
^myHCrum!
*/
}
/**
* This is primarily for the example routines.
*/
public TracePosition hCut() {
return myHCrum.hCut();
/*
udanax-top.st:9635:OrglRoot methodsFor: 'accessing'!
{TracePosition} hCut
"This is primarily for the example routines."
^myHCrum hCut!
*/
}
public void introduceEdition(BeEdition edition) {
myHCrum.introduceEdition(edition);
remember();
diskUpdate();
/*
udanax-top.st:9640:OrglRoot methodsFor: 'accessing'!
{void} introduceEdition: edition {BeEdition}
myHCrum introduceEdition: edition.
self remember.
self diskUpdate!
*/
}
public boolean isEmpty() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9646:OrglRoot methodsFor: 'accessing'!
{BooleanVar} isEmpty
self subclassResponsibility!
*/
}
/**
* Just search for now.
*/
public XnRegion keysLabelled(BeLabel label) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9649:OrglRoot methodsFor: 'accessing'!
{XnRegion} keysLabelled: label {BeLabel}
"Just search for now."
self subclassResponsibility!
*/
}
/**
* return a mapping from my data to corresponding stuff in the given trace
*/
public Mapping mapSharedTo(TracePosition trace) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9654:OrglRoot methodsFor: 'accessing'!
{Mapping} mapSharedTo: trace {TracePosition}
"return a mapping from my data to corresponding stuff in the given trace"
self subclassResponsibility!
*/
}
/**
* Return the owner for the given position in the receiver.
*/
public ID ownerAt(Position key) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9658:OrglRoot methodsFor: 'accessing'!
{ID} ownerAt: key {Position}
"Return the owner for the given position in the receiver."
self subclassResponsibility!
*/
}
public XnRegion rangeOwners(XnRegion positions) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9663:OrglRoot methodsFor: 'accessing'!
{XnRegion} rangeOwners: positions {XnRegion | NULL}
self subclassResponsibility!
*/
}
public void removeEdition(BeEdition stamp) {
myHCrum.removeEdition(stamp);
if (myHCrum.isEmpty()) {
/* Now we get into the risky part of deletion. Only Editions can keep OrglRoots around, so destroy the receiver. */
destroy();
}
else {
diskUpdate();
}
/*
udanax-top.st:9667:OrglRoot methodsFor: 'accessing'!
{void} removeEdition: stamp {BeEdition}
myHCrum removeEdition: stamp.
myHCrum isEmpty
ifTrue:
["Now we get into the risky part of deletion. Only Editions can keep OrglRoots around, so destroy the receiver."
self destroy]
ifFalse: [self diskUpdate]!
*/
}
/**
* Return the portiong whose owner couldn't be changed.
*/
public OrglRoot setAllOwners(ID owner) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9676:OrglRoot methodsFor: 'accessing'!
{OrglRoot} setAllOwners: owner {ID}
"Return the portiong whose owner couldn't be changed."
self subclassResponsibility!
*/
}
/**
* Return a region for all the stuff in this orgl that can backfollow to trace.
*/
public XnRegion sharedRegion(TracePosition trace) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9681:OrglRoot methodsFor: 'accessing'!
{XnRegion} sharedRegion: trace {TracePosition}
"Return a region for all the stuff in this orgl that can backfollow to trace."
self subclassResponsibility!
*/
}
/**
* Return a simple region that encloses the domain of the receiver.
*/
public XnRegion simpleDomain() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9686:OrglRoot methodsFor: 'accessing'!
{XnRegion} simpleDomain
"Return a simple region that encloses the domain of the receiver."
self subclassResponsibility!
*/
}
/**
* Return the owner for the given position in the receiver.
*/
public PrimSpec specAt(Position key) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9691:OrglRoot methodsFor: 'accessing'!
{PrimSpec} specAt: key {Position}
"Return the owner for the given position in the receiver."
self subclassResponsibility!
*/
}
public XnRegion usedDomain() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9696:OrglRoot methodsFor: 'accessing'!
{XnRegion} usedDomain
self subclassResponsibility!
*/
}
/**
* Return a stepper of bundles according to the order.
*/
public Stepper bundleStepper(XnRegion region, OrderSpec order) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9701:OrglRoot methodsFor: 'operations'!
{Stepper} bundleStepper: region {XnRegion} with: order {OrderSpec}
"Return a stepper of bundles according to the order."
self subclassResponsibility!
*/
}
public OrglRoot combine(OrglRoot orgl) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9706:OrglRoot methodsFor: 'operations'!
{OrglRoot} combine: orgl {OrglRoot}
self subclassResponsibility!
*/
}
public OrglRoot copy(XnRegion externalRegion) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9710:OrglRoot methodsFor: 'operations'!
{OrglRoot} copy: externalRegion {XnRegion}
self subclassResponsibility!
*/
}
/**
* This does the 'now' part of setting up a recorder, once the 'later' part has been set up.
* It does a walk south on the O-tree, then walks back north on all the H-trees, filtered by
* the Bert canopy.
*/
public void delayedFindMatching(PropFinder finder, RecorderFossil fossil, ResultRecorder recorder) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9714:OrglRoot methodsFor: 'operations'!
{void} delayedFindMatching: finder {PropFinder}
with: fossil {RecorderFossil}
with: recorder {ResultRecorder}
"This does the 'now' part of setting up a recorder, once the 'later' part has been set up.
It does a walk south on the O-tree, then walks back north on all the H-trees, filtered by the Bert canopy."
self subclassResponsibility!
*/
}
/**
* Go ahead and actually store the recorder in the sensor canopy. However, instead of
* propogating the props immediately, accumulate all those agenda items into the 'agenda'
* parameter. This is done instead of scheduling them directly because our client needs to
* schedule something else following all the prop propogation.
*/
public void storeRecordingAgents(RecorderFossil recorder, Agenda agenda) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9723:OrglRoot methodsFor: 'operations'!
{void} storeRecordingAgents: recorder {RecorderFossil}
with: agenda {Agenda}
"Go ahead and actually store the recorder in the sensor canopy. However, instead of propogating the props immediately, accumulate all those agenda items into the 'agenda' parameter. This is done instead of scheduling them directly because our client needs to schedule something else following all the prop propogation."
self subclassResponsibility!
*/
}
/**
* Return a copy with externalDsp added to the receiver's dsp.
*/
public OrglRoot transformedBy(Dsp externalDsp) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9729:OrglRoot methodsFor: 'operations'!
{OrglRoot} transformedBy: externalDsp {Dsp}
"Return a copy with externalDsp added to the receiver's dsp."
self subclassResponsibility!
*/
}
/**
* Return a copy with externalDsp removed from the receiver's dsp.
*/
public OrglRoot unTransformedBy(Dsp externalDsp) {
throw new SubclassResponsibilityException();
/*
udanax-top.st:9734:OrglRoot methodsFor: 'operations'!
{OrglRoot} unTransformedBy: externalDsp {Dsp}
"Return a copy with externalDsp removed from the receiver's dsp."
self subclassResponsibility!
*/
}
public void dismantle() {
AboraBlockSupport.enterConsistent(3);
try {
super.dismantle();
myHCrum = null;
}
finally {
AboraBlockSupport.exitConsistent();
}
/*
udanax-top.st:9741:OrglRoot methodsFor: 'protected:'!
{void} dismantle
DiskManager consistent: 3 with:
[super dismantle.
myHCrum _ NULL]!
*/
}
public OrglRoot(SensorCrum scrum) {
super(scrum);
myHCrum = HBottomCrum.make();
/*
udanax-top.st:9748:OrglRoot methodsFor: 'create'!
create: scrum {SensorCrum | NULL}
super create: scrum.
myHCrum _ HBottomCrum make.!
*/
}
public int contentsHash() {
return super.contentsHash() ^ myHCrum.hashForEqual();
/*
udanax-top.st:9754:OrglRoot methodsFor: 'testing'!
{UInt32} contentsHash
^super contentsHash
bitXor: myHCrum hashForEqual!
*/
}
/**
* @deprecated
*/
public ScruTable asDataTable() {
throw new PasseException();
/*
udanax-top.st:9761:OrglRoot methodsFor: 'smalltalk: passe'!
{ScruTable} asDataTable
self passe!
*/
}
/**
* @deprecated
*/
public ScruTable asTable() {
throw new PasseException();
/*
udanax-top.st:9765:OrglRoot methodsFor: 'smalltalk: passe'!
{ScruTable} asTable
self passe!
*/
}
/**
* @deprecated
*/
public void checkRecorders(BeEdition edition, PropFinder finder, SensorCrum scrum) {
throw new PasseException();
/*
udanax-top.st:9769:OrglRoot methodsFor: 'smalltalk: passe'!
{void} checkRecorders: edition {BeEdition}
with: finder {PropFinder}
with: scrum {SensorCrum | NULL}
self passe "fewer args"!
*/
}
/**
* @deprecated
*/
public void delayedFindMatching(PropFinder finder, RecorderFossil recorder) {
throw new PasseException();
/*
udanax-top.st:9774:OrglRoot methodsFor: 'smalltalk: passe'!
{void} delayedFindMatching: finder {PropFinder}
with: recorder {RecorderFossil}
self passe "extra argument"!
*/
}
/**
* @deprecated
*/
public FeRangeElement fetch(Position key) {
throw new PasseException();
/*
udanax-top.st:9779:OrglRoot methodsFor: 'smalltalk: passe'!
{FeRangeElement | NULL} fetch: key {Position}
self passe!
*/
}
/**
* @deprecated
*/
public ScruTable findMatching(PropFinder finder) {
throw new PasseException();
/*
udanax-top.st:9783:OrglRoot methodsFor: 'smalltalk: passe'!
{ScruTable of: ID and: BeEdition} findMatching: finder {PropFinder}
self passe!
*/
}
/**
* @deprecated
*/
public void inform(Position key, HRoot value) {
throw new PasseException();
/*
udanax-top.st:9787:OrglRoot methodsFor: 'smalltalk: passe'!
{void} inform: key {Position} with: value {HRoot}
self passe!
*/
}
/**
* @deprecated
*/
public void introduceStamp(BeEdition stamp) {
throw new PasseException();
/*
udanax-top.st:9791:OrglRoot methodsFor: 'smalltalk: passe'!
{void} introduceStamp: stamp {BeEdition}
self passe.!
*/
}
/**
* @deprecated
*/
public void propChanged(PropChange change) {
throw new PasseException();
/*
udanax-top.st:9794:OrglRoot methodsFor: 'smalltalk: passe'!
{void} propChanged: change {PropChange}
self passe!
*/
}
/**
* @deprecated
*/
public void removeStamp(BeEdition stamp) {
throw new PasseException();
/*
udanax-top.st:9798:OrglRoot methodsFor: 'smalltalk: passe'!
{void} removeStamp: stamp {BeEdition}
self passe.!
*/
}
/**
* @deprecated
*/
public void wait(XnSensor sensor) {
throw new PasseException();
/*
udanax-top.st:9801:OrglRoot methodsFor: 'smalltalk: passe'!
{void} wait: sensor {XnSensor}
self passe!
*/
}
public OrglRoot(Rcvr receiver) {
super(receiver);
myHCrum = (HBottomCrum) receiver.receiveHeaper();
/*
udanax-top.st:9807:OrglRoot methodsFor: 'generated:'!
create.Rcvr: receiver {Rcvr}
super create.Rcvr: receiver.
myHCrum _ receiver receiveHeaper.!
*/
}
public void sendSelfTo(Xmtr xmtr) {
super.sendSelfTo(xmtr);
xmtr.sendHeaper(myHCrum);
/*
udanax-top.st:9811:OrglRoot methodsFor: 'generated:'!
{void} sendSelfTo: xmtr {Xmtr}
super sendSelfTo: xmtr.
xmtr sendHeaper: myHCrum.!
*/
}
/**
* create a new orgl root
*/
public static OrglRoot makeCoordinateSpace(CoordinateSpace cs) {
/* This should definitely be cached!! We make them all the time probably. */
Someone.thingToDo();
AboraBlockSupport.enterConsistent(4);
try {
return new EmptyOrglRoot(cs);
}
finally {
AboraBlockSupport.exitConsistent();
}
/*
udanax-top.st:9824:OrglRoot class methodsFor: 'creation'!
make.CoordinateSpace: cs {CoordinateSpace}
"create a new orgl root"
"This should definitely be cached!! We make them all the time probably."
self thingToDo.
DiskManager consistent: 4 with:
[^EmptyOrglRoot create: cs]!
*/
}
public static OrglRoot makeXnRegion(XnRegion region) {
if (region.isEmpty()) {
return OrglRoot.make(region.coordinateSpace());
}
return ActualOrglRoot.make((Loaf.makeXnRegion(region)), region);
/*
udanax-top.st:9832:OrglRoot class methodsFor: 'creation'!
make.XnRegion: region {XnRegion}
region isEmpty ifTrue:
[^OrglRoot make: region coordinateSpace].
^ActualOrglRoot make: (Loaf make.XnRegion: region) with: region!
*/
}
public static OrglRoot make(XnRegion keys, OrderSpec ordering, PtrArray values) {
Stepper stepper;
OrglRoot result;
int i;
result = OrglRoot.makeCoordinateSpace(ordering.coordinateSpace());
Someone.hack();
/* This should make a balanced tree directly. */
i = 0;
stepper = keys.stepper(ordering);
Stepper stomper = stepper;
for (; stomper.hasValue(); stomper.step()) {
Position key = (Position) stomper.fetch();
if (key == null) {
continue ;
}
BeCarrier element;
XnRegion region;
FeRangeElement fe = (FeRangeElement) (values.fetch(i));
if (fe != null ) {
element = fe.carrier();
}
else {
throw new AboraRuntimeException(AboraRuntimeException.MUST_NOT_HAVE_NULL_ELEMENTS);
}
region = key.asRegion();
result = result.combine((ActualOrglRoot.make((Loaf.makeRegion(region, element)), region)));
i = i + 1;
}
stomper.destroy();
return result;
/*
udanax-top.st:9838:OrglRoot class methodsFor: 'creation'!
{OrglRoot} make: keys {XnRegion}
with: ordering {OrderSpec}
with: values {PtrArray of: FeRangeElement}
| stepper {Stepper} result {OrglRoot} i {Int32} |
result _ OrglRoot make.CoordinateSpace: ordering coordinateSpace.
self hack. "This should make a balanced tree directly."
i _ Int32Zero.
stepper _ keys stepper: ordering.
stepper forEach:
[:key {Position} |
| element {BeCarrier} region {XnRegion} |
(values fetch: i)
notNULL: [:fe {FeRangeElement} | element _ fe carrier]
else: [Heaper BLAST: #MustNotHaveNullElements].
region _ key asRegion.
result _ result combine:
(ActualOrglRoot
make: (Loaf make.Region: region with: element)
with: region).
i _ i + 1].
^result!
*/
}
/**
* Make an Orgl from a bunch of Data. The data is
* guaranteed to be of a reasonable size.
*/
public static OrglRoot makeData(PrimDataArray values, Arrangement arrangement) {
return ActualOrglRoot.make((Loaf.make(values, arrangement)), arrangement.region());
/*
udanax-top.st:9861:OrglRoot class methodsFor: 'creation'!
{OrglRoot} makeData: values {PrimDataArray} with: arrangement {Arrangement}
"Make an Orgl from a bunch of Data. The data is
guaranteed to be of a reasonable size."
^ActualOrglRoot
make: (Loaf make: values with: arrangement)
with: arrangement region!
*/
}
/**
* Make an Orgl from a bunch of Data. The data is
* guaranteed to be of a reasonable size.
*/
public static OrglRoot makeData(XnRegion keys, OrderSpec ordering, PrimDataArray values) {
return ActualOrglRoot.make((Loaf.make(values, (ordering.arrange(keys)))), keys);
/*
udanax-top.st:9869:OrglRoot class methodsFor: 'creation'!
{OrglRoot} makeData: keys {XnRegion} with: ordering {OrderSpec} with: values {PrimDataArray}
"Make an Orgl from a bunch of Data. The data is
guaranteed to be of a reasonable size."
^ActualOrglRoot
make: (Loaf make: values with: (ordering arrange: keys))
with: keys!
*/
}
/**
* create a new orgl root
*/
public static OrglRoot make(Heaper it) {
if (it instanceof CoordinateSpace) {
return makeCoordinateSpace((CoordinateSpace) it);
}
if (it instanceof XnRegion) {
return makeXnRegion((XnRegion) it);
}
throw new UnsupportedOperationException();
/*
udanax-top.st:9879:OrglRoot class methodsFor: 'smalltalk:'!
{OrglRoot} make: it {Heaper}
"create a new orgl root"
(it isKindOf: CoordinateSpace) ifTrue: [^self make.CoordinateSpace: it].
(it isKindOf: XnRegion) ifTrue: [^self make.XnRegion: it].
^self make.ScruTable: (it cast: ScruTable)!
*/
}
public OrglRoot() {
/*
Generated during transformation
*/
}
}
| mit |
xinerd/algorithm | LeetCode/src/cn/fmachine/lintcode/medium/ReorderArrayToConstructTheMinimumNumber.java | 2507 | package cn.fmachine.lintcode.medium;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
/**
* Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.
* <p>
* Notice
* <p>
* The result may be very large, so you need to return a string instead of an integer.
* <p>
* Have you met this question in a real interview? Yes
* Example
* Given [3, 32, 321], there are 6 possible numbers can be constructed by reordering the array:
* <p>
* 3+32+321=332321
* 3+321+32=332132
* 32+3+321=323321
* 32+321+3=323213
* 321+3+32=321332
* 321+32+3=321323
* So after reordering, the minimum number is 321323, and return it.
* <p>
* Challenge
* Do it in O(nlogn) time complexity.
* <p>
* Tags
* Array
* Related Problems
* Medium Delete Digits
* <p>
* algorithm
* Author: XIN MING
* Date: 10/23/16
*
* time O(nlgn)
*/
public class ReorderArrayToConstructTheMinimumNumber {
@Test
public void minNumberTest() throws Exception {
int[] case1 = {0, 4, 32, 31, 40, 0};
Assert.assertEquals("3132404", minNumber(case1));
int[] case2 = {3, 32};
Assert.assertEquals("323", minNumber(case2));
}
/**
* @param nums n non-negative integer array
* @return a string
*/
public String minNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return "";
}
String[] candidates = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
candidates[i] = String.valueOf(nums[i]);
}
Arrays.sort(candidates, new Comparator<String>() {
@Override
public int compare(String a, String b) {
String ab = a.concat(b);
String ba = b.concat(a);
return ab.compareTo(ba);
}
}
);
String result = "";
for (String i : candidates) {
result = result.concat(i);
}
int i = 0;
while (i < nums.length && result.charAt(i) == '0') {
i++;
}
if (i == nums.length) return "0";
return result.substring(i);
}
}
class Cmp implements Comparator<String> {
@Override
public int compare(String a, String b) {
String ab = a.concat(b);
String ba = b.concat(a);
return ba.compareTo(ab);
}
}
| mit |
FranckW/projet1_opl | server/repositoryTest/test/Maison.java | 38 | package test;
public class Maison {
}
| mit |
qkcoder/Assembler | app/src/androidTest/java/com/qk/assembler/ExampleInstrumentedTest.java | 733 | package com.qk.assembler;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.qk.assembler", appContext.getPackageName());
}
}
| mit |
Azure/azure-sdk-for-java | sdk/spring/azure-spring-boot/src/samples/java/com/azure/spring/aad/webapi/SampleController.java | 6284 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.aad.webapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.function.client.WebClient;
import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId;
import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient;
@RestController
public class SampleController {
private static final Logger LOGGER = LoggerFactory.getLogger(SampleController.class);
private static final String GRAPH_ME_ENDPOINT = "https://graph.microsoft.com/v1.0/me";
private static final String CUSTOM_LOCAL_FILE_ENDPOINT = "http://localhost:8082/webapiB";
private static final String CUSTOM_LOCAL_READ_ENDPOINT = "http://localhost:8083/webapiC";
@Autowired
private WebClient webClient;
@Autowired
private OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository;
/**
* Call the graph resource, return user information
*
* @return Response with graph data
*/
@PreAuthorize("hasAuthority('SCOPE_Obo.Graph.Read')")
@GetMapping("call-graph-with-repository")
public String callGraphWithRepository() {
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
OAuth2AuthorizedClient graph = oAuth2AuthorizedClientRepository
.loadAuthorizedClient("graph", principal, sra.getRequest());
return callMicrosoftGraphMeEndpoint(graph);
}
/**
* Call the graph resource with annotation, return user information
*
* @param graph authorized client for Graph
* @return Response with graph data
*/
// BEGIN: readme-sample-callGraph
@PreAuthorize("hasAuthority('SCOPE_Obo.Graph.Read')")
@GetMapping("call-graph")
public String callGraph(@RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient graph) {
return callMicrosoftGraphMeEndpoint(graph);
}
// END: readme-sample-callGraph
/**
* Call custom resources, combine all the response and return.
*
* @param webapiBClient authorized client for Custom
* @return Response Graph and Custom data.
*/
// BEGIN: readme-sample-callCustom
@PreAuthorize("hasAuthority('SCOPE_Obo.WebApiA.ExampleScope')")
@GetMapping("webapiA/webapiB")
public String callCustom(
@RegisteredOAuth2AuthorizedClient("webapiB") OAuth2AuthorizedClient webapiBClient) {
return callWebApiBEndpoint(webapiBClient);
}
// END: readme-sample-callCustom
/**
* Call microsoft graph me endpoint
*
* @param graph Authorized Client
* @return Response string data.
*/
private String callMicrosoftGraphMeEndpoint(OAuth2AuthorizedClient graph) {
if (null != graph) {
String body = webClient
.get()
.uri(GRAPH_ME_ENDPOINT)
.attributes(oauth2AuthorizedClient(graph))
.retrieve()
.bodyToMono(String.class)
.block();
LOGGER.info("Response from Graph: {}", body);
return "Graph response " + (null != body ? "success." : "failed.");
} else {
return "Graph response failed.";
}
}
/**
* Call custom local file endpoint
*
* @param webapiBClient Authorized Client
* @return Response string data.
*/
private String callWebApiBEndpoint(OAuth2AuthorizedClient webapiBClient) {
if (null != webapiBClient) {
String body = webClient
.get()
.uri(CUSTOM_LOCAL_FILE_ENDPOINT)
.attributes(oauth2AuthorizedClient(webapiBClient))
.retrieve()
.bodyToMono(String.class)
.block();
LOGGER.info("Response from webapiB: {}", body);
return "webapiB response " + (null != body ? "success." : "failed.");
} else {
return "webapiB response failed.";
}
}
/**
* Access to protected data through client credential flow. The access token is obtained by webclient, or
* <p>@RegisteredOAuth2AuthorizedClient("webapiC")</p>. In the end, these two approaches will be executed to
* DefaultOAuth2AuthorizedClientManager#authorize method, get the access token.
*
* @return Respond to protected data.
*/
// BEGIN: readme-sample-callClientCredential
@PreAuthorize("hasAuthority('SCOPE_Obo.WebApiA.ExampleScope')")
@GetMapping("webapiA/webapiC")
public String callClientCredential() {
String body = webClient
.get()
.uri(CUSTOM_LOCAL_READ_ENDPOINT)
.attributes(clientRegistrationId("webapiC"))
.retrieve()
.bodyToMono(String.class)
.block();
LOGGER.info("Response from Client Credential: {}", body);
return "client Credential response " + (null != body ? "success." : "failed.");
}
// END: readme-sample-callClientCredential
}
| mit |
AlwaysRightInstitute/StaticCMS | org/opengroupware/pubexport/elements/OGoPubHTMLElement.java | 6070 | package org.opengroupware.pubexport.elements;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.getobjects.appserver.core.WOAssociation;
import org.getobjects.appserver.core.WOContext;
import org.getobjects.appserver.core.WODynamicElement;
import org.getobjects.appserver.core.WOElement;
import org.getobjects.appserver.core.WOElementWalker;
import org.getobjects.appserver.core.WORequest;
import org.getobjects.appserver.core.WOResponse;
import org.getobjects.appserver.elements.WOCompoundElement;
import org.getobjects.appserver.elements.WOGenericContainer;
import org.getobjects.appserver.elements.WOGenericElement;
import org.getobjects.appserver.elements.WOHTMLDynamicElement;
import org.getobjects.appserver.elements.WOHyperlink;
import org.getobjects.appserver.elements.WOImage;
import org.opengroupware.pubexport.associations.OGoPubURLAssociation;
import org.opengroupware.pubexport.parsers.OGoPubXHTMLParser;
/*
* OGoPubHTMLElement
*
* TODO: document
*/
public class OGoPubHTMLElement extends WOHTMLDynamicElement {
protected static final Log log = LogFactory.getLog("OGoPubHTMLElement");
protected WOElement wrappedElement;
public OGoPubHTMLElement
(String _name, Map<String, WOAssociation> _assocs, WOElement _template)
{
super(_name, _assocs, _template);
this.wrappedElement = this.buildWrappedElement(_name, _assocs, _template);
}
protected WODynamicElement buildWrappedElement
(String _name, Map<String, WOAssociation> _assocs, WOElement _template)
{
_assocs.put("elementName", this.tagNameAssociation(_name));
patchLinkAssociations(_name, _assocs);
//System.err.println("BUILD: " + _assocs);
WODynamicElement elem = this.isContainerTag(_name, _template)
? new WOGenericContainer(_name, _assocs, _template)
: new WOGenericElement(_name, _assocs, _template);
return elem;
}
public boolean isContainerTag(String _tag, WOElement _template) {
if (_template != null)
return true;
if (_tag != null) {
String[] tags = OGoPubXHTMLParser.containerElements;
for (int i = 0; i < tags.length; i += 2) {
if (_tag.equals(tags[i + 1]))
return true;
}
}
return false;
}
public WOAssociation tagNameAssociation(String _name) {
return WOAssociation.associationWithValue(_name);
}
@Override
public void setExtraAttributes(Map<String, WOAssociation> _attrs) {
if (this.wrappedElement instanceof WODynamicElement)
((WODynamicElement)this.wrappedElement).setExtraAttributes(_attrs);
}
/* factory */
public static final WOAssociation trueAssociation =
WOAssociation.associationWithValue(Boolean.TRUE);
public static WOElement build
(String _name, Map<String, WOAssociation> _assocs, List<WOElement> _tmpl)
{
WOElement child = null;
if ("img".equals(_name)) {
if (!_assocs.containsKey("disableOnMissingLink"))
_assocs.put("disableOnMissingLink", trueAssociation);
patchLinkAssociations(_name, _assocs);
return new WOImage(_name, _assocs, null);
}
/* consolidate template */
if (_tmpl != null) {
if (_tmpl.size() == 0)
child = null;
else if (_tmpl.size() == 1)
child = _tmpl.get(0);
else
child = new WOCompoundElement(_tmpl);
}
/* check for special elements */
if ("a".equals(_name)) {
/* either a real link or an anchor, eg: <a name="abc"> </a> */
if (!_assocs.containsKey("name")) {
/* hide a tag when the link is missing/incorrect */
if (!_assocs.containsKey("disableOnMissingLink"))
_assocs.put("disableOnMissingLink", trueAssociation);
patchLinkAssociations(_name, _assocs);
return new WOHyperlink(_name, _assocs, child);
}
else if (_assocs.containsKey("href"))
log.warn("link has a name *and* a href: " + _assocs);
}
/* per default use a generic element */
return new OGoPubHTMLElement(_name, _assocs, child);
}
public static void patchLinkAssociations
(String _tag, Map<String, WOAssociation> _assocs)
{
if (_assocs == null)
return;
_tag = _tag.toLowerCase();
/* "src" */
if ("a".equals(_tag) || "link".equals(_tag)) {
WOAssociation a = _assocs.get("href");
if (a != null && a.isValueConstant())
_assocs.put("href", new OGoPubURLAssociation(a));
}
else if ("img".equals(_tag) || "script".equals(_tag) ||
"input".equals(_tag)) {
WOAssociation a = _assocs.get("src");
if (a != null && a.isValueConstant())
_assocs.put("src", new OGoPubURLAssociation(a));
}
else if ("table".equals(_tag) || "td".equals(_tag) || "body".equals(_tag)) {
WOAssociation a = _assocs.get("background");
if (a != null && a.isValueConstant())
_assocs.put("background", new OGoPubURLAssociation(a));
}
else if ("form".equals(_tag)) {
WOAssociation a = _assocs.get("action");
if (a != null && a.isValueConstant())
_assocs.put("action", new OGoPubURLAssociation(a));
}
}
/* request handling */
@Override
public void takeValuesFromRequest(WORequest _rq, WOContext _ctx) {
if (this.wrappedElement != null)
this.wrappedElement.takeValuesFromRequest(_rq, _ctx);
}
@Override
public Object invokeAction(WORequest _rq, WOContext _ctx) {
if (this.wrappedElement == null)
return null;
return this.wrappedElement.invokeAction(_rq, _ctx);
}
/* template walking */
@Override
public void walkTemplate(WOElementWalker _walker, WOContext _ctx) {
if (this.wrappedElement != null)
this.wrappedElement.walkTemplate(_walker, _ctx);
}
/* generate response */
@Override
public void appendToResponse(WOResponse _r, WOContext _ctx) {
if (this.wrappedElement != null)
this.wrappedElement.appendToResponse(_r, _ctx);
}
}
| mit |
junicorn/roo | src/main/java/social/roo/model/entity/Setting.java | 481 | package social.roo.model.entity;
import com.blade.jdbc.annotation.Table;
import com.blade.jdbc.core.ActiveRecord;
import lombok.Data;
/**
* 系统配置
*
* @author biezhi
* @date 2017/8/1
*/
@Table(value = "roo_setting", pk = "skey")
@Data
public class Setting extends ActiveRecord{
/**
* 配置键
*/
private String skey;
/**
* 配置值
*/
private String svalue;
/**
* 0禁用 1正常
*/
private Integer state;
}
| mit |
sebastienhouzet/nabaztag-source-code | server/OS/net/violet/platform/xmpp/packet/IQCommandPacket.java | 5121 | package net.violet.platform.xmpp.packet;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.xmlpull.v1.XmlPullParser;
/**
* Classe pour gérer les IQ de type "command" <command
* xmlns='http://jabber.org/protocol/commands' node='getconfig'
* action='execute'/>
*
* @author pgerlach
*/
public class IQCommandPacket extends IQ {
/**
* Les différents type de commandes comprises par le lapin
*/
public enum Type {
getConfig,
getRunningState
};
public static String ELEMENT = "command";
public static String NAMESPACE = "http://jabber.org/protocol/commands";
protected Type mType;
public static final IQProvider IQ_PROVIDER = new Provider();
private static final class Provider implements IQProvider {
/**
* Constructeur par défaut.
*/
private Provider() {
// This space for rent.
}
public IQ parseIQ(XmlPullParser inParser) throws Exception {
final StringBuilder var = new StringBuilder();
boolean inValue = false;
Type type = null;
int eventType = inParser.getEventType();
final Map<String, String> result = new HashMap<String, String>();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if ("command".equals(inParser.getName())) {
final String node = inParser.getAttributeValue(null, "node");
if ("getconfig".equals(node)) {
type = Type.getConfig;
} else if ("getrunningstate".equals(node)) {
type = Type.getRunningState;
}
}
if ("field".equals(inParser.getName())) {
var.append(inParser.getAttributeValue(null, "var"));
} else if ("value".equals(inParser.getName())) {
inValue = true;
}
} else if (eventType == XmlPullParser.TEXT) {
if (inValue && (var.length() > 0)) {
result.put(var.toString(), inParser.getText());
var.setLength(0);
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("x".equals(inParser.getName())) {
break;
} else if ("value".equals(inParser.getName())) {
inValue = false;
}
} else if (eventType == XmlPullParser.END_DOCUMENT) {
break;
}
eventType = inParser.next();
}
if (type == Type.getConfig) {
// désencoder certains champs qui sont en base64 (voir le
// bytecode du lapin pour savoir lesquels)
final String[] toDecode = { "wifi_ssid", "login", "password" };
for (final String key : toDecode) {
if (result.containsKey(key)) {
final String val = result.get(key);
if (null != val) {
final byte[] decoded = Base64.decodeBase64(val.getBytes());
result.put(key, new String(decoded));
}
}
}
}
IQCommandPacket res = null;
if (null != type) {
res = new IQCommandPacket(type, result);
}
return res;
}
}
/**
* chaine de description de la config
*/
private final Map<String, String> mInfos = new HashMap<String, String>();
/**
* Constructeur par défaut.
*/
public IQCommandPacket(Type type) {
this.mType = type;
}
public IQCommandPacket(Type type, Map<String, String> config) {
this.mType = type;
this.mInfos.putAll(config);
}
public String getElementName() {
return IQCommandPacket.ELEMENT;
}
public String getNamespace() {
return IQCommandPacket.NAMESPACE;
}
public Map<String, String> getInfos() {
return this.mInfos;
}
@Override
public String getChildElementXML() {
final StringBuilder xmlChild = new StringBuilder();
xmlChild.append("<command xmlns='http://jabber.org/protocol/commands' node='");
switch (this.mType) {
case getConfig:
xmlChild.append("getconfig");
break;
case getRunningState:
xmlChild.append("getrunningstate");
break;
}
xmlChild.append("' action='execute'/>");
return xmlChild.toString();
}
/**
* Fonction utilitaire pour permettre d'afficher un paquet sous forme HTML
*
* @return la représentation du paquet en html
*/
public static String formatToHtml(Map<String, String> infos, Type type) {
final StringBuilder res = new StringBuilder();
final String[] fields;
final String[] fieldsGetConfig = { "bytecode_revision", "wifi_ssid", "wifi_crypt", "net_dhcp", "net_ip", "net_mask", "net_gateway", "net_dns", "server_url", "login", "proxy_enabled", "proxy_ip", "proxy_port" };
final String[] fieldsGetRunningState = { "connection_mode", "net_ip", "net_mask", "net_gateway", "net_dns", "sState", "sResource", "gItState", "gSleepState", "gStreamingState", "gProcessingState", "gProcessingWaitState", "gBusyState", "gItApp" };
switch (type) {
case getConfig:
fields = fieldsGetConfig;
break;
case getRunningState:
fields = fieldsGetRunningState;
break;
default:
fields = new String[0];
}
res.append("<table>");
for (final String key : fields) {
res.append("<tr><td>");
res.append(key);
res.append("</td><td>");
res.append(infos.get(key));
res.append("</td></tr>");
}
res.append("</table>");
return res.toString();
}
}
| mit |
nantaphop/AomYim-Pantip | app/src/main/java/com/nantaphop/pantipfanapp/event/ChooseTopicTypeEvent.java | 127 | package com.nantaphop.pantipfanapp.event;
/**
* Created by nantaphop on 16-Oct-14.
*/
public class ChooseTopicTypeEvent {
}
| mit |
kmycode/Keyline | src/keyline/damodel/GroupAccess.java | 267 | /*
* 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 keyline.damodel;
/**
*
* @author KMY
*/
public class GroupAccess {
}
| mit |
InnovateUKGitHub/innovation-funding-service | common/ifs-resources/src/main/java/org/innovateuk/ifs/competition/builder/UpcomingCompetitionSearchResultItemBuilder.java | 1615 | package org.innovateuk.ifs.competition.builder;
import org.innovateuk.ifs.competition.resource.search.UpcomingCompetitionSearchResultItem;
import java.util.List;
import java.util.function.BiConsumer;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.setField;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds;
public class UpcomingCompetitionSearchResultItemBuilder extends CompetitionSearchResultItemBuilder<UpcomingCompetitionSearchResultItem, UpcomingCompetitionSearchResultItemBuilder> {
private UpcomingCompetitionSearchResultItemBuilder(List<BiConsumer<Integer, UpcomingCompetitionSearchResultItem>> newMultiActions) {
super(newMultiActions);
}
public static UpcomingCompetitionSearchResultItemBuilder newUpcomingCompetitionSearchResultItem() {
return new UpcomingCompetitionSearchResultItemBuilder(emptyList()).with(uniqueIds());
}
public UpcomingCompetitionSearchResultItemBuilder withStartDateDisplay(String... startDates) {
return withArray((startDate, competition) -> setField("startDateDisplay", startDate, competition), startDates);
}
@Override
protected UpcomingCompetitionSearchResultItemBuilder createNewBuilderWithActions(List<BiConsumer<Integer, UpcomingCompetitionSearchResultItem>> actions) {
return new UpcomingCompetitionSearchResultItemBuilder(actions);
}
@Override
protected UpcomingCompetitionSearchResultItem createInitial() {
return newInstance(UpcomingCompetitionSearchResultItem.class);
}
}
| mit |
github/codeql | java/ql/test/stubs/apache-commons-collections4-4.4/org/apache/commons/collections4/list/UnmodifiableList.java | 1581 | // Generated automatically from org.apache.commons.collections4.list.UnmodifiableList for testing purposes
package org.apache.commons.collections4.list;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Predicate;
import org.apache.commons.collections4.Unmodifiable;
import org.apache.commons.collections4.list.AbstractSerializableListDecorator;
public class UnmodifiableList<E> extends AbstractSerializableListDecorator<E> implements Unmodifiable
{
protected UnmodifiableList() {}
public E remove(int p0){ return null; }
public E set(int p0, E p1){ return null; }
public Iterator<E> iterator(){ return null; }
public List<E> subList(int p0, int p1){ return null; }
public ListIterator<E> listIterator(){ return null; }
public ListIterator<E> listIterator(int p0){ return null; }
public UnmodifiableList(List<? extends E> p0){}
public boolean add(Object p0){ return false; }
public boolean addAll(Collection<? extends E> p0){ return false; }
public boolean addAll(int p0, Collection<? extends E> p1){ return false; }
public boolean remove(Object p0){ return false; }
public boolean removeAll(Collection<? extends Object> p0){ return false; }
public boolean removeIf(Predicate<? super E> p0){ return false; }
public boolean retainAll(Collection<? extends Object> p0){ return false; }
public static <E> List<E> unmodifiableList(List<? extends E> p0){ return null; }
public void add(int p0, E p1){}
public void clear(){}
}
| mit |
JCThePants/NucleusFramework | src/com/jcwhatever/nucleus/storage/settings/PropertyDefinition.java | 6332 | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.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.jcwhatever.nucleus.storage.settings;
import com.jcwhatever.nucleus.mixins.INamed;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.converters.Converter;
import com.jcwhatever.nucleus.utils.validate.IValidator;
import javax.annotation.Nullable;
/**
* A definition of a possible configuration property.
*/
public class PropertyDefinition implements INamed, Comparable<PropertyDefinition> {
private final String _name;
private final PropertyValueType _type;
private final String _description;
private final boolean _hasDefaultValue;
private final Object _defaultValue;
private Converter<?> _converter;
private Converter<?> _unconverter;
private IValidator<Object> _validator;
/**
* Constructor.
*
* <p>Defines a property without a default value.</p>
*
* @param name The property name.
* @param type The value type.
* @param description The description of the property.
*/
public PropertyDefinition(String name, PropertyValueType type, String description) {
PreCon.notNullOrEmpty(name);
PreCon.notNull(type);
PreCon.notNull(description);
_name = name;
_type = type;
_description = description;
_hasDefaultValue = false;
_defaultValue = null;
}
/**
* Constructor.
*
* <p>Defines a property with a default value.</p>
*
* @param name The property name.
* @param type The value type.
* @param defaultValue The default value.
* @param description The description of the property.
*/
public PropertyDefinition(String name, PropertyValueType type,
@Nullable Object defaultValue, String description) {
PreCon.notNullOrEmpty(name);
PreCon.notNull(type);
PreCon.notNull(description);
_name = name;
_type = type;
_description = description;
_hasDefaultValue = true;
_defaultValue = defaultValue;
if (defaultValue != null && !type.isAssignable(defaultValue)) {
throw new RuntimeException("Invalid default value type. Should be: " + type.getTypeClass().getName());
}
}
@Override
public String getName() {
return _name;
}
/**
* Get the value type of the property.
*/
public PropertyValueType getValueType() {
return _type;
}
/**
* Get the property description.
*/
public String getDescription() {
return _description;
}
/**
* Get the default value.
*
* <p>Use {@link #hasDefaultValue} to check first. Default value may be null.</p>
*
* @return The default value (which may be null) or null if there is no default value.
*/
@Nullable
public Object getDefaultValue() {
return _defaultValue;
}
/**
* Determine if the setting has a default value.
*
* <p>A default value could be null.</p>
*/
public boolean hasDefaultValue() {
return _hasDefaultValue;
}
/**
* Get the value converter, if any.
*
* @return The converter or null if not set.
*/
@Nullable
public Converter<?> getConverter() {
return _converter;
}
/**
* Set the value converter.
*
* @param converter The value converter or null to remove.
*/
public void setConverter(@Nullable Converter<?> converter) {
_converter = converter;
}
/**
* Get the value unconverter, if any.
*
* @return The converter or null if not set.
*/
@Nullable
public Converter<?> getUnconverter() {
return _unconverter;
}
/**
* Set the value unconverter.
*
* @param converter The value converter or null to remove.
*/
public void setUnconverter(@Nullable Converter<?> converter) {
_unconverter = converter;
}
/**
* Get the value validator.
*
* @return The validator or null if not set.
*/
@Nullable
public IValidator<Object> getValidator() {
return _validator;
}
/**
* Set the value validator.
*
* <p>Used to validate a value before setting the property.</p>
*
* @param validator The value validator or null to remove.
*/
public void setValidator(@Nullable IValidator<Object> validator) {
_validator = validator;
}
@Override
public int compareTo(PropertyDefinition o) {
return getName().compareTo(o.getName());
}
@Override
public int hashCode() {
return _name.hashCode() ^ _type.hashCode() ^ _description.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PropertyDefinition) {
PropertyDefinition def = (PropertyDefinition)obj;
return def._name.equals(_name) &&
def._type.equals(_type) &&
def._description.equals(_description);
}
return false;
}
}
| mit |
Gohla/persistent-graph | impl-pcollections/src/main/java/nl/gohla/graph/persistent/internal/pcollections/tree/PCTreeGraphBuilder.java | 988 | package nl.gohla.graph.persistent.internal.pcollections.tree;
import javax.annotation.Nullable;
import nl.gohla.graph.persistent.IGraph;
import nl.gohla.graph.persistent.IGraphBuilder;
public class PCTreeGraphBuilder<V, E> implements IGraphBuilder<V, E> {
private IGraph<V, E> graph;
public PCTreeGraphBuilder() {
this.graph = new PCTreeGraph<V, E>();
}
@Override public IGraphBuilder<V, E> addNode(int node, @Nullable V nodeLabel) {
graph = graph.addNode(node, nodeLabel);
return this;
}
@Override public IGraphBuilder<V, E> addEdge(int srcNode, int dstNode, E edgeLabel) {
graph = graph.addEdge(srcNode, dstNode, edgeLabel);
return this;
}
@Override public IGraphBuilder<V, E> addSelfEdge(int node, E edgeLabel) {
graph = graph.addSelfEdge(node, edgeLabel);
return this;
}
@Override public IGraph<V, E> build() {
return graph;
}
}
| mit |
alv-ch/alv-ch-sysinfos.api | src/main/java/ch/alv/sysinfos/web/rest/system/MaxUploadSizeExceededException.java | 109 | package ch.alv.sysinfos.web.rest.system;
class MaxUploadSizeExceededException extends RuntimeException {
}
| mit |
zeebo404/jni-registry | src/com/ice/jni/registry/RegMultiStringValue.java | 3047 | /*
** Java native interface to the Windows Registry API.
**
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
package com.ice.jni.registry;
import java.io.PrintWriter;
/**
* The RegMultiStringValue class represents a multiple
* string, or string array, value in the registry
* (REG_MULTI_SZ).
*
* @version 3.1.3
* @see com.ice.jni.registry.Registry
* @see com.ice.jni.registry.RegistryKey
*/
public class RegMultiStringValue extends RegistryValue {
String[] data;
int dataLen;
public RegMultiStringValue(RegistryKey key, String name) {
super(key, name, RegistryValue.REG_MULTI_SZ);
this.data = null;
this.dataLen = 0;
}
public RegMultiStringValue(RegistryKey key, String name, int type) {
super(key, name, type);
this.data = null;
this.dataLen = 0;
}
public RegMultiStringValue(RegistryKey key, String name, String[] data) {
super(key, name, RegistryValue.REG_MULTI_SZ);
this.setData(data);
}
public String[] getData() {
return this.data;
}
public int getLength() {
return this.dataLen;
}
public void setData(String[] data) {
this.data = data;
this.dataLen = data.length;
}
public byte[] getByteData() {
int len = this.getByteLength();
int ri = 0;
byte[] result = new byte[len];
for (int i = 0; i < this.dataLen; ++i) {
byte[] strBytes = this.data[i].getBytes();
for (int j = 0; j < strBytes.length; ++j)
result[ri++] = strBytes[j];
result[ri++] = 0;
}
return result;
}
public int getByteLength() {
int len = 0;
for (int i = 0; i < this.dataLen; ++i)
len += this.data[i].length() + 1;
return len;
}
public void setByteData(byte[] data) {
int start;
int count = 0;
for (int i = 0; i < data.length; ++i) {
if (data[i] == 0)
count++;
}
int si = 0;
String[] newData = new String[count];
for (int i = start = 0; i < data.length; ++i) {
if (data[i] == 0) {
newData[si] = new String(data, start, (i - start));
start = si;
}
}
this.setData(newData);
}
public void export(PrintWriter out) {
byte[] hexData;
int dataLen = 0;
out.println("\"" + this.getName() + "\"=hex(7):\\");
for (int i = 0; i < this.data.length; ++i) {
dataLen += this.data[i].length() + 1;
}
++dataLen;
int idx = 0;
hexData = new byte[dataLen];
for (int i = 0; i < this.data.length; ++i) {
int strLen = this.data[i].length();
byte[] strBytes = this.data[i].getBytes();
System.arraycopy
(strBytes, 0, hexData, idx, strLen);
idx += strLen;
hexData[idx++] = 0;
}
hexData[idx++] = 0;
RegistryValue.exportHexData(out, hexData);
}
} | mit |
kenyonduan/amazon-mws | src/main/java/com/elcuk/jaxb/PowerPlugType.java | 1938 | /* */ package com.elcuk.jaxb;
/* */
/* */ import javax.xml.bind.annotation.XmlEnum;
/* */ import javax.xml.bind.annotation.XmlEnumValue;
/* */ import javax.xml.bind.annotation.XmlType;
/* */
/* */ @XmlType(name="PowerPlugType")
/* */ @XmlEnum
/* */ public enum PowerPlugType
/* */ {
/* 43 */ TYPE_A_2_PIN_JP("type_a_2pin_jp"),
/* */
/* 45 */ TYPE_E_2_PIN_FR("type_e_2pin_fr"),
/* */
/* 47 */ TYPE_J_3_PIN_CH("type_j_3pin_ch"),
/* */
/* 49 */ TYPE_A_2_PIN_NA("type_a_2pin_na"),
/* */
/* 51 */ TYPE_EF_2_PIN_EU("type_ef_2pin_eu"),
/* */
/* 53 */ TYPE_K_3_PIN_DK("type_k_3pin_dk"),
/* */
/* 55 */ TYPE_B_3_PIN_JP("type_b_3pin_jp"),
/* */
/* 57 */ TYPE_F_2_PIN_DE("type_f_2pin_de"),
/* */
/* 59 */ TYPE_L_3_PIN_IT("type_l_3pin_it"),
/* */
/* 61 */ TYPE_B_3_PIN_NA("type_b_3pin_na"),
/* */
/* 63 */ TYPE_G_3_PIN_UK("type_g_3pin_uk"),
/* */
/* 65 */ TYPE_M_3_PIN_ZA("type_m_3pin_za"),
/* */
/* 67 */ TYPE_C_2_PIN_EU("type_c_2pin_eu"),
/* */
/* 69 */ TYPE_H_3_PIN_IL("type_h_3pin_il"),
/* */
/* 71 */ TYPE_N_3_PIN_BR("type_n_3pin_br"),
/* */
/* 73 */ TYPE_D_3_PIN_IN("type_d_3pin_in"),
/* */
/* 75 */ TYPE_I_3_PIN_AU("type_i_3pin_au");
/* */
/* */ private final String value;
/* */
/* */ private PowerPlugType(String v) {
/* 80 */ this.value = v;
/* */ }
/* */
/* */ public String value() {
/* 84 */ return this.value;
/* */ }
/* */
/* */ public static PowerPlugType fromValue(String v) {
/* 88 */ for (PowerPlugType c : values()) {
/* 89 */ if (c.value.equals(v)) {
/* 90 */ return c;
/* */ }
/* */ }
/* 93 */ throw new IllegalArgumentException(v);
/* */ }
/* */ }
/* Location: /Users/mac/Desktop/jaxb/
* Qualified Name: com.elcuk.jaxb.PowerPlugType
* JD-Core Version: 0.6.2
*/ | mit |
sriharshachilakapati/SilenceEngine | tests/src/main/java/com/shc/silenceengine/tests/GameTest.java | 2289 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 Sri Harsha Chilakapati
*
* 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.shc.silenceengine.tests;
import com.shc.silenceengine.core.SilenceEngine;
import com.shc.silenceengine.input.Keyboard;
import com.shc.silenceengine.logging.Logger;
/**
* @author Sri Harsha Chilakapati
*/
public class GameTest extends SilenceTest
{
private Logger logger;
@Override
public void init()
{
logger = SilenceEngine.log.getLogger("GameTest");
SilenceEngine.display.setTitle("GameTest");
logger.info("Test initialized successfully");
}
@Override
public void update(float delta)
{
logger.info("Update event!! Delta is " + delta);
if (Keyboard.isKeyTapped(Keyboard.KEY_ESCAPE))
SilenceEngine.display.close();
}
@Override
public void render(float delta)
{
logger.info("Render event!! Delta is " + delta);
}
@Override
public void resized()
{
logger.info("Resize event!! Size is " + SilenceEngine.display.getWidth() + "x" + SilenceEngine.display.getHeight());
}
@Override
public void dispose()
{
logger.info("Dispose event!! Success.");
}
}
| mit |
DIKU-Steiner/ProGAL | src/ProGAL/dataStructures/rangeSearching/RangeSearchDataStructure.java | 230 | package ProGAL.dataStructures.rangeSearching;
import java.util.List;
import ProGAL.geomNd.Point;
public interface RangeSearchDataStructure {
// public void addPoint(Point p);
public List<Point> query(Point low, Point high);
}
| mit |
sel-utils/java | src/main/java/sul/protocol/java340/clientbound/WindowProperty.java | 2864 | /*
* This file was automatically generated by sel-utils and
* released under the MIT License.
*
* License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
* Repository: https://github.com/sel-project/sel-utils
* Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/java340.xml
*/
package sul.protocol.java340.clientbound;
import sul.utils.*;
public class WindowProperty extends Packet {
public static final int ID = (int)21;
public static final boolean CLIENTBOUND = true;
public static final boolean SERVERBOUND = false;
@Override
public int getId() {
return ID;
}
// property
public static final short FURNANCE_FIRE_ICON = (short)0;
public static final short FURNACE_MAX_FUEL_BURN_TIME = (short)1;
public static final short FURNACE_PROGRESS_ARROW = (short)2;
public static final short FURNCE_MAX_PROGRESS = (short)3;
public static final short ENCHANTMENT_LEVEL_REQUIREMENT_TOP = (short)0;
public static final short ENCHANTMENT_LEVEL_REQUIREMENT_MIDDLE = (short)1;
public static final short ENCHANTMENT_LEVEL_REQUIREMENT_BOTTOM = (short)2;
public static final short ENCHANTMENT_SEED = (short)3;
public static final short ENCHANTMENT_ID_TOP = (short)4;
public static final short ENCHANTMENT_ID_MIDDLE = (short)5;
public static final short ENCHANTMENT_ID_BOTTOM = (short)6;
public static final short ENCHANTMENT_LEVEL_TOP = (short)7;
public static final short ENCHANTMENT_LEVEL_MIDDLE = (short)8;
public static final short ENCHANTMENT_LEVEL_BOTTOM = (short)9;
public static final short BEACON_POWER_LEVEL = (short)0;
public static final short BEACON_FIRST_EFFECT = (short)1;
public static final short BEACON_SECOND_EFFECT = (short)2;
public static final short ANVIL_REPAIR_COST = (short)0;
public static final short BREWING_STAND_BREW_TIME = (short)0;
public byte window;
public short property;
public short value;
public WindowProperty() {}
public WindowProperty(byte window, short property, short value) {
this.window = window;
this.property = property;
this.value = value;
}
@Override
public int length() {
return 6;
}
@Override
public byte[] encode() {
this._buffer = new byte[this.length()];
this.writeVaruint(ID);
this.writeBigEndianByte(window);
this.writeBigEndianShort(property);
this.writeBigEndianShort(value);
return this.getBuffer();
}
@Override
public void decode(byte[] buffer) {
this._buffer = buffer;
this.readVaruint();
window=readBigEndianByte();
property=readBigEndianShort();
value=readBigEndianShort();
}
public static WindowProperty fromBuffer(byte[] buffer) {
WindowProperty ret = new WindowProperty();
ret.decode(buffer);
return ret;
}
@Override
public String toString() {
return "WindowProperty(window: " + this.window + ", property: " + this.property + ", value: " + this.value + ")";
}
} | mit |
jmiettinen/wikilinks | src/main/java/fi/eonwe/wikilinks/utils/IntQueue.java | 4563 | package fi.eonwe.wikilinks.utils;
import java.io.IOException;
import java.util.function.IntConsumer;
import com.google.common.primitives.Ints;
/**
*/
public class IntQueue {
private final boolean isGrowing;
private int head;
private int tail;
private int[] buffer;
private IntQueue(int initialSize, boolean isGrowing) {
this.buffer = new int[initialSize + 1];
this.isGrowing = isGrowing;
}
public static IntQueue growingQueue(int startSize) {
return new IntQueue(startSize, true);
}
public static IntQueue fixedSizeQueue(int maxLength) {
return new IntQueue(maxLength, false);
}
public boolean addLast(int value) {
int oldTail = this.tail;
int[] buffer = this.buffer;
int len = buffer.length;
int newTail = incrementIndex(oldTail, len);
if (size() == capacity()) {
if (isGrowing) {
doGrow();
oldTail = this.tail;
buffer = this.buffer;
len = buffer.length;
} else {
return false;
}
newTail = incrementIndex(oldTail, len);
}
buffer[oldTail] = value;
this.tail = newTail;
return true;
}
private void doGrow() {
int newSize = Ints.saturatedCast(Math.max(8, buffer.length * 3L / 2));
int[] newBuffer = new int[newSize];
final int[] oldBuffer = this.buffer;
final int oldHead = head;
final int oldTail = tail;
final int newTail = size();
final int newHead = 0;
this.buffer = newBuffer;
if (oldHead < oldTail) {
System.arraycopy(oldBuffer, oldHead, newBuffer, 0, oldTail - oldHead);
} else {
final int sizeToEnd = oldBuffer.length - oldHead;
System.arraycopy(oldBuffer, oldHead, newBuffer, 0, sizeToEnd);
System.arraycopy(oldBuffer, 0, newBuffer, sizeToEnd, oldTail);
}
this.head = newHead;
this.tail = newTail;
}
public void forEach(IntConsumer consumer) {
forEach(buffer, head, tail, consumer);
}
private static void forEach(int[] buffer, int head, int tail, IntConsumer consumer) {
final int len = buffer.length;
for (int current = head; current != tail; current = incrementIndex(current, len)) {
consumer.accept(buffer[current]);
}
}
public int removeFirst() {
final int oldHead = this.head;
final int[] buffer = this.buffer;
final int result = buffer[oldHead];
this.head = incrementIndex(oldHead, buffer.length);
return result;
}
public int peekFirst() {
return this.buffer[this.head];
}
private static int incrementIndex(int oldIndex, int onePastMax) {
int nextIndex = oldIndex + 1;
if (nextIndex == onePastMax) return 0;
return nextIndex;
}
public int size() {
final int head = this.head;
final int tail = this.tail;
int size = tail - head;
return size < 0 ? size + buffer.length : size;
}
public <T extends Appendable> T printTo(T output) throws IOException {
final boolean[] isFirst = { true };
IgnoringAppendable out = new IgnoringAppendable(output);
out.append("[ ");
forEach(val -> {
if (!isFirst[0]) {
out.append(", ");
} else {
isFirst[0] = false;
}
out.append(String.valueOf(val));
});
out.append(" ]");
if (out.exception != null) throw out.exception;
return output;
}
private static class IgnoringAppendable {
private final Appendable wrapped;
private IOException exception;
public IgnoringAppendable(Appendable wrapped) {
this.wrapped = wrapped;
}
public void append(CharSequence chars) {
if (exception == null) {
try {
wrapped.append(chars);
} catch (IOException e) {
exception = e;
}
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
try {
printTo(sb);
} catch (IOException e) {
throw new Error(e);
}
return sb.toString();
}
public boolean isEmpty() {
return size() == 0;
}
public int capacity() {
return buffer.length - 1;
}
}
| mit |
terrason/interior | src/main/java/org/terramagnet/interior/module/commerce/CustomerService.java | 219 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.terramagnet.interior.module.commerce;
/**
*
* @author lee
*/
public interface CustomerService {
}
| mit |
Time5-Desenho/Wikalendario | app/src/main/java/com/time2desenho/wikalendario/controller/GroupController.java | 2048 | package com.time2desenho.wikalendario.controller;
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.time2desenho.wikalendario.dao.GroupDatabaseHelper;
import com.time2desenho.wikalendario.model.Group;
import com.time2desenho.wikalendario.model.User;
import com.time2desenho.wikalendario.util.ManyToManyDAOFacade;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class GroupController {
private ArrayList<Group> groups;
private GroupDatabaseHelper groupDatabaseHelper;
private Dao<Group, Long> groupDao;
public GroupController(Context context){
groupDatabaseHelper = new GroupDatabaseHelper(context);
try {
groupDao = groupDatabaseHelper.getDAO();
}catch(SQLException e){
e.printStackTrace();
}
}
public ArrayList<Group> getGroups() {
return groups;
}
public void setGroups(ArrayList<Group> groups) {
this.groups = groups;
}
public void createGroup(Group group) throws IllegalArgumentException{
try {
groupDao.create(group);
}catch(SQLException e){
e.printStackTrace();
}
}
public Group readGroup(Long id, Context context){
Group group = new Group();
try {
group = groupDao.queryForId(id);
ManyToManyDAOFacade manyToManyDAOFacade = new ManyToManyDAOFacade(context);
List<User> users = manyToManyDAOFacade.getUsers(group);
group.setUsers(users);
} catch (SQLException e) {
e.printStackTrace();
}
return group;
}
public void updateGroup(Group group, Long id){
try {
group.setId(id);
groupDao.update(group);
}catch(SQLException e){
e.printStackTrace();
}
}
public void deleteGroup(Group group){
try {
groupDao.delete(group);
}catch(SQLException e){
e.printStackTrace();
}
}
}
| mit |
GoodforGod/dummymaker | src/test/java/io/dummymaker/export/CaseParameterizedTest.java | 1557 | package io.dummymaker.export;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* "default comment"
*
* @author GoodforGod
* @since 21.04.2018
*/
@RunWith(Parameterized.class)
public class CaseParameterizedTest extends Assert {
private String initial;
private String expected;
private Cases caseUsed;
public CaseParameterizedTest(String initial, String expected, Cases caseUsed) {
this.initial = initial;
this.expected = expected;
this.caseUsed = caseUsed;
}
@Parameters(name = "Case used - {2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "MyTomEx", "MyTomEx", Cases.DEFAULT },
{ "MyTomEx", "mytomex", Cases.LOW_CASE },
{ "MyTomEx", "MYTOMEX", Cases.UPPER_CASE },
{ "MyTomEx", "my-tom-ex", Cases.KEBAB_CASE },
{ "MyTomEx", "MY-TOM-EX", Cases.UPPER_KEBAB_CASE },
{ "MyTomEx", "my_tom_ex", Cases.SNAKE_CASE },
{ "MyTomEx", "MY_TOM_EX", Cases.UPPER_SNAKE_CASE },
{ "MyTomEx", "myTomEx", Cases.CAMEL_CASE },
{ "myTomEx", "MyTomEx", Cases.PASCAL_CASE },
});
}
@Test
public void checkCase() {
final String result = caseUsed.value().format(initial);
assertEquals(expected, result);
}
}
| mit |
brainysmith/scs-lib | src/test/java/com/identityblitz/scs/SCSessionImplTest.java | 5946 | package com.identityblitz.scs;
import com.identityblitz.scs.error.SCSBrokenException;
import com.identityblitz.scs.error.SCSException;
import com.identityblitz.scs.error.SCSExpiredException;
import junit.framework.Assert;
import org.apache.commons.codec.binary.Base64;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Date;
public class SCSessionImplTest {
@BeforeClass
public static void setUp() throws Throwable {
System.setProperty("com.identityblitz.scs.crypto.encodingKey", "30313233343536373839616263646566");
System.setProperty("com.identityblitz.scs.crypto.hmacKey", "3031323334353637383930313233343536373839");
System.setProperty("com.identityblitz.scs.sessionMaxAgeInSec", Long.toString(7 * 365 * 86400L));
System.setProperty("com.identityblitz.scs.cookieDomain", "blitz.com");
}
@Test
public void scsEncodingTest() throws SCSException {
final String originalScs = "XBgdUDDGBuT8KuNlVXY6gOAkMXDeSkN6diVF5z778kI|MTM5NjM0ODcyMA|U0gxQVNDQkMxMjg|PZ84RGBeLN_S9n-sViQTnQ|BURedPx1UPuq0LTKRaPHuvqOcPM";
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final byte[] iv = Base64.decodeBase64("PZ84RGBeLN_S9n-sViQTnQ");
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("PZ84RGBeLN_S9n-sViQTnQ", encKey, hmacKey);
SCSession session = new SCSessionImpl(state, new Date(1396348720L * 1000), false, cryptoService);
Assert.assertEquals(originalScs, session.asString());
}
@Test
public void scsCompressedEncodingTest() throws SCSException {
final String originalScs = "OJHgHjTcJWLjDZ-ks8DE1MECshGta84lK4-lT49LfOk|MTM5NjM1MDUxMw|U0gxQVNDQkMxMjg|uWArYb9mV08tboY8DSVylA|2iOPyF4jP7RCkPYBAFHudo7XnFw";
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final byte[] iv = Base64.decodeBase64("uWArYb9mV08tboY8DSVylA");
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("uWArYb9mV08tboY8DSVylA", encKey, hmacKey);
SCSession session = new SCSessionImpl(state, new Date(1396350513L * 1000), true, cryptoService);
Assert.assertEquals(originalScs, session.asString());
}
@Test
public void scsDecodingTest() throws SCSException {
final String originalScs = "XBgdUDDGBuT8KuNlVXY6gOAkMXDeSkN6diVF5z778kI|MTM5NjM0ODcyMA|U0gxQVNDQkMxMjg|PZ84RGBeLN_S9n-sViQTnQ|BURedPx1UPuq0LTKRaPHuvqOcPM";
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final long atime = 1396348720;
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("PZ84RGBeLN_S9n-sViQTnQ", encKey, hmacKey);
SCSession session = new SCSessionImpl(false, cryptoService, originalScs, null);
Assert.assertEquals(state, session.getData());
Assert.assertEquals(new Date(atime * 1000), session.getAtime());
Assert.assertEquals(cryptoService.getTid("someService"), session.getTid());
org.junit.Assert.assertArrayEquals(cryptoService.generateIv(session.getTid()), session.getIv());
}
@Test
public void scsCompressedDecodingTest() throws SCSException {
final String originalScs = "OJHgHjTcJWLjDZ-ks8DE1MECshGta84lK4-lT49LfOk|MTM5NjM1MDUxMw|U0gxQVNDQkMxMjg|uWArYb9mV08tboY8DSVylA|2iOPyF4jP7RCkPYBAFHudo7XnFw";
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final long atime = 1396350513;
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("uWArYb9mV08tboY8DSVylA", encKey, hmacKey);
SCSession session = new SCSessionImpl(true, cryptoService, originalScs, null);
Assert.assertEquals(originalScs, session.asString());
Assert.assertEquals(state, session.getData());
Assert.assertEquals(new Date(atime * 1000), session.getAtime());
Assert.assertEquals(cryptoService.getTid("someService"), session.getTid());
org.junit.Assert.assertArrayEquals(cryptoService.generateIv(session.getTid()), session.getIv());
}
@Test(expected = SCSBrokenException.class)
public void scsBrokenMacDecodingTest() throws SCSException {
final String originalScs = "XBgdUDDGBuT8KuNlVXY6gOAkMXDeSkN6diVF5z778kI|MTM5NjM0ODcyMA|U0gxQVNDQkMxMjg|PZ84RGBeLN_S9n-sViQTnQ|BURedPx1UPuq0LTLRaPHuvqOcPM";
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final long atime = 1396348720;
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("PZ84RGBeLN_S9n-sViQTnQ", encKey, hmacKey);
SCSession session = new SCSessionImpl(false, cryptoService, originalScs, null);
}
@Test(expected = SCSExpiredException.class)
public void scsExpirationOptionTest() throws SCSException {
final String state = "some state value";
final byte[] encKey = "0123456789abcdef".getBytes();
final byte[] hmacKey = "01234567890123456789".getBytes();
final Date atime = new Date(System.currentTimeMillis() - 7 * 60 * 1000);
SimpleCryptoService cryptoService = new SimpleCryptoService();
cryptoService.init("PZ84RGBeLN_S9n-sViQTnQ", encKey, hmacKey);
SCSession session = new SCSessionImpl(state, atime, false, cryptoService);
new SCSessionImpl(false, cryptoService, session.asString(), 3 * 60L);
}
}
| mit |
bcvsolutions/CzechIdMng | Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/domain/InstanceIdentifiable.java | 631 | package eu.bcvsolutions.idm.core.api.domain;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;
/**
* Interface for records that own server instance identifier (server instance related records).
*
* @author Radek Tomiška
* @since 11.1.0
*/
public interface InstanceIdentifiable {
String PROPERTY_INSTANCE_ID = ConfigurationService.PROPERTY_INSTANCE_ID;
/**
* Get server instance identifier.
*
* @return server instance identifier
*/
String getInstanceId();
/**
* Set server instance identifier.
*
* @param instanceId instance identifier
*/
void setInstanceId(String instanceId);
}
| mit |
markspanbroek/rip | src/test/java/rip/RequestWriterTest.java | 1599 | package rip;
import org.junit.Test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLConnection;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyByte;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.*;
public class RequestWriterTest {
RequestWriter requestWriter = new RequestWriter();
@Test(expected = ConnectionFailure.class)
public void throwsOnFailureWhileWriting() throws IOException {
URLConnection connection = mock(URLConnection.class);
OutputStream stream = createFailingOutputStream();
when(connection.getOutputStream()).thenReturn(stream);
requestWriter.write(connection, "");
}
@Test(expected = ConnectionFailure.class)
public void throwsOnFailureWhileConnecting() throws IOException {
URLConnection connection = createFailingConnection();
requestWriter.write(connection, "");
}
private OutputStream createFailingOutputStream() throws IOException {
OutputStream stream = mock(OutputStream.class);
doThrow(new IOException()).when(stream).write(anyByte());
doThrow(new IOException()).when(stream).write(any(byte[].class));
doThrow(new IOException()).when(stream).write(any(byte[].class), anyInt(), anyInt());
return stream;
}
private URLConnection createFailingConnection() throws IOException {
URLConnection connection = mock(URLConnection.class);
when(connection.getOutputStream()).thenThrow(new IOException());
return connection;
}
}
| mit |
sholev/SoftUni | Fundamentals-2.0/JavaFundamentals/Homework/JavaSyntax/src/org/softuni/_07_RandomizeNumbersFromNtoM.java | 575 | package org.softuni;
import java.util.Random;
import java.util.Scanner;
public class _07_RandomizeNumbersFromNtoM {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random RNG = new Random();
System.out.print("N M = ");
Integer N = in.nextInt();
Integer M = in.nextInt();
Integer min = Math.min(N, M);
Integer max = Math.max(N, M);
for (int i = 0; i <= Math.abs(N - M) ; i++) {
System.out.printf("%d ", RNG.nextInt((max - min) + 1) + min);
}
}
}
| mit |
tectiv3/react-native-aes | android/src/main/java/com/tectiv3/aes/RCTAes.java | 7809 | package com.tectiv3.aes;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.InvalidKeyException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.Mac;
import org.spongycastle.crypto.digests.SHA512Digest;
import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.util.encoders.Hex;
import android.util.Base64;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
public class RCTAes extends ReactContextBaseJavaModule {
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
public static final String HMAC_SHA_256 = "HmacSHA256";
public static final String HMAC_SHA_512 = "HmacSHA512";
private static final String KEY_ALGORITHM = "AES";
public RCTAes(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "RCTAes";
}
@ReactMethod
public void encrypt(String data, String key, String iv, String algorithm, Promise promise) {
try {
String result = encrypt(data, key, iv);
promise.resolve(result);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void decrypt(String data, String pwd, String iv, String algorithm, Promise promise) {
try {
String strs = decrypt(data, pwd, iv);
promise.resolve(strs);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void pbkdf2(String pwd, String salt, Integer cost, Integer length, Promise promise) {
try {
String strs = pbkdf2(pwd, salt, cost, length);
promise.resolve(strs);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void hmac256(String data, String pwd, Promise promise) {
try {
String strs = hmacX(data, pwd, HMAC_SHA_256);
promise.resolve(strs);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void hmac512(String data, String pwd, Promise promise) {
try {
String strs = hmacX(data, pwd, HMAC_SHA_512);
promise.resolve(strs);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void sha256(String data, Promise promise) {
try {
String result = shaX(data, "SHA-256");
promise.resolve(result);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void sha1(String data, Promise promise) {
try {
String result = shaX(data, "SHA-1");
promise.resolve(result);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void sha512(String data, Promise promise) {
try {
String result = shaX(data, "SHA-512");
promise.resolve(result);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void randomUuid(Promise promise) {
try {
String result = UUID.randomUUID().toString();
promise.resolve(result);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
@ReactMethod
public void randomKey(Integer length, Promise promise) {
try {
byte[] key = new byte[length];
SecureRandom rand = new SecureRandom();
rand.nextBytes(key);
String keyHex = bytesToHex(key);
promise.resolve(keyHex);
} catch (Exception e) {
promise.reject("-1", e.getMessage());
}
}
private String shaX(String data, String algorithm) throws Exception {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(data.getBytes());
byte[] digest = md.digest();
return bytesToHex(digest);
}
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789abcdef".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String pbkdf2(String pwd, String salt, Integer cost, Integer length)
throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException
{
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
gen.init(pwd.getBytes("UTF_8"), salt.getBytes("UTF_8"), cost);
byte[] key = ((KeyParameter) gen.generateDerivedParameters(length)).getKey();
return bytesToHex(key);
}
private static String hmacX(String text, String key, String algorithm)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException
{
byte[] contentData = text.getBytes("UTF_8");
byte[] akHexData = Hex.decode(key);
Mac sha_HMAC = Mac.getInstance(algorithm);
SecretKey secret_key = new SecretKeySpec(akHexData, algorithm);
sha_HMAC.init(secret_key);
return bytesToHex(sha_HMAC.doFinal(contentData));
}
final static IvParameterSpec emptyIvSpec = new IvParameterSpec(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
private static String encrypt(String text, String hexKey, String hexIv) throws Exception {
if (text == null || text.length() == 0) {
return null;
}
byte[] key = Hex.decode(hexKey);
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, hexIv == null ? emptyIvSpec : new IvParameterSpec(Hex.decode(hexIv)));
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeToString(encrypted, Base64.NO_WRAP);
}
private static String decrypt(String ciphertext, String hexKey, String hexIv) throws Exception {
if(ciphertext == null || ciphertext.length() == 0) {
return null;
}
byte[] key = Hex.decode(hexKey);
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, hexIv == null ? emptyIvSpec : new IvParameterSpec(Hex.decode(hexIv)));
byte[] decrypted = cipher.doFinal(Base64.decode(ciphertext, Base64.NO_WRAP));
return new String(decrypted, "UTF-8");
}
}
| mit |
opennars/opennars | src/test/java/org/opennars/ops/TestSystemOperator.java | 4260 | package org.opennars.ops;
import org.junit.Test;
import org.opennars.entity.Sentence;
import org.opennars.interfaces.NarseseConsumer;
import org.opennars.io.events.AnswerHandler;
import org.opennars.language.Term;
import org.opennars.main.Nar;
import static org.junit.Assert.assertTrue;
/**
* (integration) testing of the ^system op
*/
public class TestSystemOperator {
@Test
public void testOpCall() throws Exception {
{ // 0 parameters, boolean result
Nar nar = new Nar();
nar.addPlugin(new org.opennars.operator.misc.System());
test0Ret(nar, "bool");
nar.cycles(500);
// check result of call
MyAnswerHandler handler = new MyAnswerHandler();
nar.ask("<{?0}-->res>",handler);
nar.cycles(100);
assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
}
{ // 1 parameters, boolean result
Nar nar = new Nar();
nar.addPlugin(new org.opennars.operator.misc.System());
test1Ret(nar, "bool");
nar.cycles(500);
// check result of call
MyAnswerHandler handler = new MyAnswerHandler();
nar.ask("<{?0}-->res>",handler);
nar.cycles(100);
assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
}
{ // 2 parameters, boolean result
Nar nar = new Nar();
nar.addPlugin(new org.opennars.operator.misc.System());
test2Ret(nar, "bool");
nar.cycles(500);
// check result of call
MyAnswerHandler handler = new MyAnswerHandler();
nar.ask("<{?0}-->res>",handler);
nar.cycles(100);
assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
}
{ // 3 parameters, boolean result
Nar nar = new Nar();
nar.addPlugin(new org.opennars.operator.misc.System());
test3Ret(nar, "bool");
nar.cycles(700);
// check result of call
MyAnswerHandler handler = new MyAnswerHandler();
nar.ask("<{?0}-->res>",handler);
nar.cycles(200);
assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
}
}
/**
*
* @param consumer
* @param expectedResultType datatype of the expected result
*/
private static void test0Ret(NarseseConsumer consumer, String expectedResultType) {
//consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ls, $ret)) =/> <{$ret}-->res>>.");
consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, $ret)) =/> <{$ret}-->res>>.");
consumer.addInput("<cond0-->Cond0>. :|:");
consumer.addInput("<{#0}-->res>!");
}
private static void test1Ret(NarseseConsumer consumer, String expectedResultType) {
consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, $ret)) =/> <{$ret}-->res>>.");
consumer.addInput("<cond0-->Cond0>. :|:");
consumer.addInput("<{#0}-->res>!");
}
private static void test2Ret(NarseseConsumer consumer, String expectedResultType) {
consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, Arg1, $ret)) =/> <{$ret}-->res>>.");
consumer.addInput("<cond0-->Cond0>. :|:");
consumer.addInput("<{#0}-->res>!");
}
private static void test3Ret(NarseseConsumer consumer, String expectedResultType) {
consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, Arg1, Arg2, $ret)) =/> <{$ret}-->res>>.");
consumer.addInput("<cond0-->Cond0>. :|:");
consumer.addInput("<{#0}-->res>!");
}
static class MyAnswerHandler extends AnswerHandler {
public Term lastAnswerTerm = null;
@Override
public void onSolution(Sentence belief) {
lastAnswerTerm = belief.term;
}
}
}
| mit |
yangyangv2/leet-code | problems/src/main/java/prob683/k/empty/slots/Solution.java | 987 | package prob683.k.empty.slots;
import java.util.Map;
import java.util.TreeMap;
public class Solution {
public int kEmptySlots(int[] flowers, int k) {
TreeMap<Integer, Integer> tm = new TreeMap<>();
int n = flowers.length, loc = 0;
tm.put(0, n - 1);
for(int i = 0; i < n; i ++){
loc = flowers[i] - 1;
Map.Entry<Integer, Integer> entry = tm.floorEntry(loc);
tm.remove(loc);
int start1 = entry.getKey(), end1 = loc - 1;
int start2 = loc + 1, end2 = entry.getValue();
if(start1 != 0 && end1 != n - 1 && end1 - start1 + 1 == k)
return i + 1;
else{
if(start1 <= end1) tm.put(start1, end1);
}
if(start2 != 0 && end2 != n - 1 && end2 - start2 + 1 == k){
return i + 1;
} else {
if(start2 <= end2) tm.put(start2, end2);
}
}
return -1;
}
}
| mit |
ayush9398/Angelhacks | Android App/app/src/main/java/com/example/ashut/getitnow/myAds.java | 504 | package com.example.ashut.getitnow;
/**
* Created by ashut on 07-05-2017.
*/
public class myAds {
private String mMiwokTranslation,mDefaultTranslation;
public myAds(String MiwokTranslation,String DefaultTranslation)
{
mDefaultTranslation=DefaultTranslation;
mMiwokTranslation=MiwokTranslation;
}
public String getMiwokTranslation(){
return mMiwokTranslation;
}
public String getDefaultTranslation(){
return mDefaultTranslation;
}
}
| mit |
pavelkalinin/commons | src/main/java/xyz/enhorse/commons/Validate.java | 15045 | package xyz.enhorse.commons;
/**
* Utility class with methods to validate, set default values and etc.
* @author <a href="mailto:pavel13kalinin@gmail.com">Pavel Kalinin</a>
* 21.01.2016
*/
@SuppressWarnings({"unused", "ResultOfMethodCallIgnored"})
public class Validate {
private static final String IS_NOT_LESS_THAN = " is not less than ";
private static final String IS_NOT_GREATER_THAN = " is not greater than ";
private static final String IS_GREATER_THAN = " is greater than ";
private static final String IS_LESS_THAN = " is less than ";
private Validate() {
}
public static <T> T notNull(String parameter, T value) {
if (value == null) {
throw new IllegalArgumentException("\"" + parameter + "\" is not allowed to be null.");
}
return value;
}
public static <T> T defaultIfNull(T checkedValue, T defaultValue) {
if (checkedValue == null) {
return defaultValue;
}
return checkedValue;
}
public static <T> T defaultIfNull(T checkedValue, DefaultsProducer<T> producer) {
if (checkedValue == null) {
if (producer != null) {
return producer.getDefault();
} else {
throw new IllegalArgumentException("Can't get a default value " +
"because a default values producer isn't defined.");
}
}
return checkedValue;
}
public static String defaultIfNullOrEmpty(String checkedValue, String defaultValue) {
if ((checkedValue == null) || (checkedValue.isEmpty())) {
return defaultValue;
}
return checkedValue;
}
public static String notNullOrEmpty(String parameter, String value) {
String content = notNull(parameter, value);
if (content.isEmpty()) {
throw new IllegalArgumentException("\"" + parameter + "\" is not allowed to be empty.");
}
return content;
}
public static String identifier(String parameter, String value) {
String content = notNullOrEmpty(parameter, value);
for (char current : value.toCharArray()) {
if (!Character.isJavaIdentifierPart(current)) {
throw new IllegalArgumentException("\"" + parameter
+ "\" contains illegal symbol \'" + current + '\'');
}
}
return content;
}
public static String urlSafe(String parameter, String value) {
String content = notNullOrEmpty(parameter, value);
for (char current : value.toCharArray()) {
if ((!((current >= 'A' && current <= 'Z') || (current >= 'a' && current <= 'z')))
&& (!Character.isDigit(current))
&& ("-._".indexOf(current) < 0)) {
throw new IllegalArgumentException("\"" + parameter
+ "\" contains a not URL safe symbol \'" + current + '\'');
}
}
return content;
}
public static <T> T required(String parameter, T value) {
if (value == null) {
throw new IllegalStateException("\"" + parameter + "\" is required, but was not defined.");
}
return value;
}
//less
public static byte less(String parameter, byte value, byte boundary) {
if (value >= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
public static short less(String parameter, short value, short boundary) {
if (value >= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
public static int less(String parameter, int value, int boundary) {
if (value >= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
public static long less(String parameter, long value, long boundary) {
if (value >= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
public static float less(String parameter, float value, float boundary) {
if (Float.compare(value, boundary) >= 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
public static double less(String parameter, double value, double boundary) {
if (Double.compare(value, boundary) >= 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_LESS_THAN + boundary);
}
return value;
}
//greater
public static byte greater(String parameter, byte value, byte boundary) {
if (value <= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static short greater(String parameter, short value, short boundary) {
if (value <= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static int greater(String parameter, int value, int boundary) {
if (value <= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static long greater(String parameter, long value, long boundary) {
if (value <= boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static double greater(String parameter, float value, float boundary) {
if (Float.compare(value, boundary) <= 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static double greater(String parameter, double value, double boundary) {
if (Double.compare(value, boundary) <= 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
//lessOrEquals
public static byte lessOrEquals(String parameter, byte value, byte boundary) {
if (value > boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_GREATER_THAN + boundary);
}
return value;
}
public static short lessOrEquals(String parameter, short value, short boundary) {
if (value > boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_GREATER_THAN + boundary);
}
return value;
}
public static int lessOrEquals(String parameter, int value, int boundary) {
if (value > boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_GREATER_THAN + boundary);
}
return value;
}
public static long lessOrEquals(String parameter, long value, long boundary) {
if (value > boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_GREATER_THAN + boundary);
}
return value;
}
public static double lessOrEquals(String parameter, float value, float boundary) {
if (Float.compare(value, boundary) > 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static double lessOrEquals(String parameter, double value, double boundary) {
if (Double.compare(value, boundary) > 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
//greaterOrEquals
public static byte greaterOrEquals(String parameter, byte value, byte boundary) {
if (value < boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_LESS_THAN + boundary);
}
return value;
}
public static short greaterOrEquals(String parameter, short value, short boundary) {
if (value < boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_LESS_THAN + boundary);
}
return value;
}
public static int greaterOrEquals(String parameter, int value, int boundary) {
if (value < boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_LESS_THAN + boundary);
}
return value;
}
public static long greaterOrEquals(String parameter, long value, long boundary) {
if (value < boundary) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_LESS_THAN + boundary);
}
return value;
}
public static double greaterOrEquals(String parameter, float value, float boundary) {
if (Float.compare(value, boundary) < 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
public static double greaterOrEquals(String parameter, double value, double boundary) {
if (Double.compare(value, boundary) < 0) {
throw new IllegalArgumentException("\"" + parameter + "\"=" + value + IS_NOT_GREATER_THAN + boundary);
}
return value;
}
//inRangeExclusive
public static byte inRangeExclusive(String parameter, byte value, byte min, byte max) {
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
public static short inRangeExclusive(String parameter, short value, short min, short max) {
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
public static int inRangeExclusive(String parameter, int value, int min, int max) {
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
public static long inRangeExclusive(String parameter, long value, long min, long max) {
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
public static double inRangeExclusive(String parameter, float value, float min, float max) {
Validate.lessOrEquals("minimum", min, max);
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
public static double inRangeExclusive(String parameter, double value, double min, double max) {
Validate.less(parameter, value, max);
Validate.greater(parameter, value, min);
return value;
}
//inRangeInclusive
public static byte inRangeInclusive(String parameter, byte value, byte min, byte max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
public static short inRangeInclusive(String parameter, short value, short min, short max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
public static int inRangeInclusive(String parameter, int value, int min, int max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
public static long inRangeInclusive(String parameter, long value, long min, long max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
public static double inRangeInclusive(String parameter, float value, float min, float max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
public static double inRangeInclusive(String parameter, double value, double min, double max) {
Validate.lessOrEquals(parameter, value, max);
Validate.greaterOrEquals(parameter, value, min);
return value;
}
//minimumIfLess
public static byte minimumIfLess(byte value, byte boundary) {
return (value > boundary) ? value : boundary;
}
public static short minimumIfLess(short value, short boundary) {
return (value > boundary) ? value : boundary;
}
public static int minimumIfLess(int value, int boundary) {
return (value > boundary) ? value : boundary;
}
public static long minimumIfLess(long value, long boundary) {
return (value > boundary) ? value : boundary;
}
public static float minimumIfLess(float value, float boundary) {
return (Float.compare(value, boundary) > 0) ? value : boundary;
}
public static double minimumIfLess(double value, double boundary) {
return (Double.compare(value, boundary) > 0) ? value : boundary;
}
public static <T extends Comparable<T>> T minimumIfLess(T value, T boundary) {
if (value == null) {
return boundary;
}
if (boundary == null) {
return value;
}
return (value.compareTo(boundary) > 0) ? value : boundary;
}
//maximumIfGreater
public static byte maximumIfGreater(byte value, byte boundary) {
return (value < boundary) ? value : boundary;
}
public static short maximumIfGreater(short value, short boundary) {
return (value < boundary) ? value : boundary;
}
public static int maximumIfGreater(int value, int boundary) {
return (value < boundary) ? value : boundary;
}
public static long maximumIfGreater(long value, long boundary) {
return (value < boundary) ? value : boundary;
}
public static float maximumIfGreater(float value, float boundary) {
return (Float.compare(value, boundary) < 0) ? value : boundary;
}
public static double maximumIfGreater(double value, double boundary) {
return (Double.compare(value, boundary) < 0) ? value : boundary;
}
public static <T extends Comparable<T>> T maximumIfGreater(T value, T boundary) {
if (value == null) {
return boundary;
}
if (boundary == null) {
return value;
}
return (value.compareTo(boundary) < 0) ? value : boundary;
}
}
| mit |
markuscandido/estudo-trilha-testes | uaiMockServer (uaiHebert Fork)/uaiMockServer-master/src/test/java/test/com/uaihebert/uaimockserver/util/StringUtilsTest.java | 342 | package test.com.uaihebert.uaimockserver.util;
import com.uaihebert.uaimockserver.util.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
public class StringUtilsTest {
@Test
public void isNotEmptyWorkingWhenEmpty() {
assertFalse("return false when blank", StringUtils.isNotBlank(""));
}
} | mit |
almex/Raildelays | batch/src/test/java/be/raildelays/batch/ExcelFileUtilsTest.java | 1719 | package be.raildelays.batch;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Almex
*/
public class ExcelFileUtilsTest {
private LocalDate previous = null;
@Before
public void setUp() throws Exception {
}
@Test
public void testGetFile() throws Exception {
File expected = new File("./prefix 20000101.exe");
File actual = ExcelFileUtils.getFile(new File("./"), "prefix", LocalDate.of(2000, 1, 1), ".exe");
assertEquals(expected, actual);
}
@Test
public void testGetFile1() throws Exception {
File expected = new File("./prefix suffix.exe");
File actual = ExcelFileUtils.getFile(new File("./"), "prefix", "suffix", ".exe");
assertEquals(expected, actual);
}
@Test
public void testGetFileName() throws Exception {
String expected = "foo";
String actual = ExcelFileUtils.getFileName(new File("./foo.bar"));
assertEquals(expected, actual);
}
@Test
public void testGetFileExtension() throws Exception {
String expected = ".bar";
String actual = ExcelFileUtils.getFileExtension(new File("foo.bar"));
assertEquals(expected, actual);
}
@Test
public void testGenerateListOfDates() throws Exception {
List<LocalDate> actual = ExcelFileUtils.generateListOfDates();
actual.forEach(localDate -> {
if (previous != null) {
assertTrue(previous.isBefore(localDate));
}
previous = localDate;
});
}
} | mit |