code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
/*
* LBFGS.java
*
* Copyright (C) 2016 Pavel Prokhorov ([email protected])
*
* 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 org.interactiverobotics.ml.optimization;
import static org.interactiverobotics.ml.optimization.OptimizationResult.Status.*;
import org.apache.log4j.Logger;
import org.interactiverobotics.math.Vector;
import java.util.Objects;
/**
* Limited-memory BFGS.
*
* https://en.wikipedia.org/wiki/Limited-memory_BFGS
*
* Liu, D. C.; Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization".
* Mathematical Programming B. 45 (3): 503–528. doi:10.1007/BF01589116.
*
*/
public final class LBFGS extends AbstractOptimizer implements Optimizer {
private static final Logger LOG = Logger.getLogger(LBFGS.class);
public LBFGS(final OptimizableFunction function) {
this.function = Objects.requireNonNull(function);
}
private final OptimizableFunction function;
/**
* Maximum number of iterations.
*/
private int maxIterations = 100;
/**
* The number of corrections to approximate the inverse Hessian matrix.
*/
private int m = 6;
/**
* Epsilon for convergence test.
* Controls the accuracy of with which the solution is to be found.
*/
private double epsilon = 1.0E-5;
/**
* Distance (in iterations) to calculate the rate of decrease of the function.
* Used in delta convergence test.
*/
private int past = 3;
/**
* Minimum rate of decrease of the function.
* Used in delta convergence test.
*/
private double delta = 1.0E-5;
/**
* Maximum number of line search iterations.
*/
private int maxLineSearchIterations = 100;
/**
* Continue optimization if line search returns {@code MAX_ITERATION_REACHED}.
*/
private boolean continueOnMaxLineSearchIterations = false;
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public double getEpsilon() {
return epsilon;
}
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
public int getPast() {
return past;
}
public void setPast(int past) {
this.past = past;
}
public double getDelta() {
return delta;
}
public void setDelta(double delta) {
this.delta = delta;
}
public int getMaxLineSearchIterations() {
return maxLineSearchIterations;
}
public void setMaxLineSearchIterations(int maxLineSearchIterations) {
this.maxLineSearchIterations = maxLineSearchIterations;
}
public boolean isContinueOnMaxLineSearchIterations() {
return continueOnMaxLineSearchIterations;
}
public void setContinueOnMaxLineSearchIterations(boolean continueOnMaxLineSearchIterations) {
this.continueOnMaxLineSearchIterations = continueOnMaxLineSearchIterations;
}
@Override
public OptimizationResult optimize() {
LOG.debug("Limited-memory BFGS optimize...");
final BacktrackingLineSearch lineSearch = new BacktrackingLineSearch(function);
lineSearch.setMaxIterations(maxLineSearchIterations);
final State[] states = new State[m];
for (int i = 0; i < m; i ++) {
states[i] = new State();
}
int currentStateIndex = 0;
final double[] pastValues;
if (past > 0) {
pastValues = new double[past];
pastValues[0] = function.getValue();
} else {
pastValues = null;
}
Vector parameters = function.getParameters();
Vector gradient = function.getValueGradient();
final double initialGradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Initial gradient norm = " + initialGradientNorm);
if (initialGradientNorm <= epsilon) {
LOG.debug("Already minimized");
return new OptimizationResult(ALREADY_MINIMIZED, parameters, function.getValue(), 0);
}
Vector direction = gradient.copy().neg();
double step = Vector.dotProduct(direction, direction);
Vector prevParameters, prevGradient;
OptimizationResult.Status status = MAX_ITERATION_REACHED;
int iteration;
for (iteration = 1; iteration <= maxIterations; iteration ++) {
LOG.debug("Iteration " + iteration);
// save previous Parameters and Gradient
prevParameters = parameters.copy();
prevGradient = gradient.copy();
// search for optimal Step
LOG.debug("Direction: " + direction + " Step = " + step);
lineSearch.setDirection(direction);
lineSearch.setInitialStep(step);
final OptimizationResult lineSearchResult = lineSearch.optimize();
if (!lineSearchResult.hasConverged()) {
LOG.error("Line search not converged: " + lineSearchResult.getStatus());
final boolean continueOptimization =
(lineSearchResult.getStatus() == MAX_ITERATION_REACHED) && continueOnMaxLineSearchIterations;
if (!continueOptimization) {
// step back
function.setParameters(prevParameters);
status = lineSearchResult.getStatus();
break;
}
}
parameters = function.getParameters();
gradient = function.getValueGradient();
final double value = function.getValue();
final boolean stop = fireOptimizerStep(parameters, value, direction, iteration);
if (stop) {
LOG.debug("Stop");
status = STOP;
break;
}
// test for convergence
final double gradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0);
LOG.debug("Gradient norm = " + gradientNorm);
if (gradientNorm <= epsilon) {
LOG.debug("Success");
status = SUCCESS;
break;
}
// delta convergence test
if (past > 0) {
if (iteration > past) {
// relative improvement from the past
final double rate = (pastValues[iteration % past] - value) / value;
if (rate < delta) {
status = STOP;
break;
}
}
pastValues[iteration % past] = value;
}
// update S and Y
final State currentState = states[currentStateIndex];
currentState.s = parameters.copy().sub(prevParameters);
currentState.y = gradient.copy().sub(prevGradient);
final double ys = Vector.dotProduct(currentState.y, currentState.s);
final double yy = Vector.dotProduct(currentState.y, currentState.y);
currentState.ys = ys;
currentStateIndex = (currentStateIndex + 1) % m;
// update Direction
direction = gradient.copy();
int availableStates = Math.min(iteration, m);
LOG.debug("Available states = " + availableStates);
int j = currentStateIndex;
for (int i = 0; i < availableStates; i ++) {
j = (j + m - 1) % m;
final State t = states[j];
t.alpha = Vector.dotProduct(t.s, direction) / t.ys;
direction.sub(t.y.copy().scale(t.alpha));
}
direction.scale(ys / yy);
for (int i = 0; i < availableStates; i ++) {
final State t = states[j];
final double beta = Vector.dotProduct(t.y, direction) / t.ys;
direction.add(t.s.copy().scale(t.alpha - beta));
j = (j + 1) % m;
}
direction.neg();
step = 1.0;
}
final Vector finalParameters = function.getParameters();
final double finalValue = function.getValue();
LOG.debug("Status = " + status + " Final Value = " + finalValue + " Parameters: " + finalParameters
+ " Iteration = " + iteration);
return new OptimizationResult(status, finalParameters, finalValue, iteration);
}
private static class State {
public double alpha;
public Vector s;
public Vector y;
public double ys;
}
}
| pavelvpster/Math | src/main/java/org/interactiverobotics/ml/optimization/LBFGS.java | Java | gpl-3.0 | 9,413 |
package cn.bjsxt.oop.staticInitBlock;
public class Parent001 /*extends Object*/ {
static int aa;
static {
System.out.println(" 静态初始化Parent001");
aa=200;
}
}
| yangweijun213/Java | J2SE300/28_51OO/src/cn/bjsxt/oop/staticInitBlock/Parent001.java | Java | gpl-3.0 | 184 |
/*
* Copyright (C) 2018 Johan Dykstrom
*
* 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 se.dykstrom.jcc.common.ast;
import java.util.Objects;
/**
* Abstract base class for different types of jump statements, such as GOTO or GOSUB.
*
* @author Johan Dykstrom
*/
public abstract class AbstractJumpStatement extends AbstractNode implements Statement {
private final String jumpLabel;
protected AbstractJumpStatement(int line, int column, String jumpLabel) {
super(line, column);
this.jumpLabel = jumpLabel;
}
/**
* Returns the label to jump to.
*/
public String getJumpLabel() {
return jumpLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractJumpStatement that = (AbstractJumpStatement) o;
return Objects.equals(jumpLabel, that.jumpLabel);
}
@Override
public int hashCode() {
return Objects.hash(jumpLabel);
}
}
| dykstrom/jcc | src/main/java/se/dykstrom/jcc/common/ast/AbstractJumpStatement.java | Java | gpl-3.0 | 1,652 |
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of Contao.
*
* Contao 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, version 3 of the License.
*
* Contao 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 Contao. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.contao.manager;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.entity.Player;
import de.minestar.contao.core.Settings;
import de.minestar.contao.data.ContaoGroup;
import de.minestar.contao.data.User;
import de.minestar.core.MinestarCore;
import de.minestar.core.units.MinestarPlayer;
public class PlayerManager {
private Map<String, User> onlineUserMap = new HashMap<String, User>();
private Map<ContaoGroup, TreeSet<User>> groupMap = new HashMap<ContaoGroup, TreeSet<User>>();
public PlayerManager() {
for (ContaoGroup cGroup : ContaoGroup.values()) {
groupMap.put(cGroup, new TreeSet<User>());
}
}
public void addUser(User user) {
onlineUserMap.put(user.getMinecraftNickname().toLowerCase(), user);
groupMap.get(user.getGroup()).add(user);
}
public void removeUser(String userName) {
User user = onlineUserMap.remove(userName.toLowerCase());
groupMap.get(user.getGroup()).remove(user);
}
public User getUser(Player player) {
return getUser(player.getName());
}
public User getUser(String userName) {
return onlineUserMap.get(userName.toLowerCase());
}
public String getGroupAsString(ContaoGroup contaoGroup) {
Set<User> groupMember = groupMap.get(contaoGroup);
if (groupMember.isEmpty())
return null;
StringBuilder sBuilder = new StringBuilder();
// BUILD HEAD
sBuilder.append(Settings.getColor(contaoGroup));
sBuilder.append(contaoGroup.getDisplayName());
sBuilder.append('(');
sBuilder.append(getGroupSize(contaoGroup));
sBuilder.append(") : ");
// ADD USER
for (User user : groupMember) {
sBuilder.append(user.getMinecraftNickname());
sBuilder.append(", ");
}
// DELETE THE LAST COMMATA
sBuilder.delete(0, sBuilder.length() - 2);
return sBuilder.toString();
}
public int getGroupSize(ContaoGroup contaoGroup) {
return groupMap.get(contaoGroup).size();
}
public void changeGroup(User user, ContaoGroup newGroup) {
groupMap.get(user.getGroup()).remove(user);
groupMap.get(newGroup).add(user);
setGroup(user, newGroup);
}
public void setGroup(User user, ContaoGroup newGroup) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(user.getMinecraftNickname());
if (mPlayer != null) {
mPlayer.setGroup(newGroup.getMinestarGroup());
}
}
public boolean canBeFree(User probeUser) {
// TODO: Implement requirements
return false;
}
}
| Minestar/Contao | src/main/java/de/minestar/contao/manager/PlayerManager.java | Java | gpl-3.0 | 3,520 |
package org.grovecity.drizzlesms.jobs.requirements;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.grovecity.drizzlesms.service.KeyCachingService;
import org.whispersystems.jobqueue.requirements.RequirementListener;
import org.whispersystems.jobqueue.requirements.RequirementProvider;
public class MasterSecretRequirementProvider implements RequirementProvider {
private final BroadcastReceiver newKeyReceiver;
private RequirementListener listener;
public MasterSecretRequirementProvider(Context context) {
this.newKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (listener != null) {
listener.onRequirementStatusChanged();
}
}
};
IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT);
context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null);
}
@Override
public void setListener(RequirementListener listener) {
this.listener = listener;
}
}
| DrizzleSuite/DrizzleSMS | src/org/grovecity/drizzlesms/jobs/requirements/MasterSecretRequirementProvider.java | Java | gpl-3.0 | 1,144 |
/*
* Copyright (C) 2017 Josua Frank
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package dfmaster.general;
import dfmaster.json.JSONValue;
import dfmaster.xml.XMLDocument;
import dfmaster.xml.XMLElement;
/**
* This is the abstract type for all data that can be created or parsed. This
* could be as example a {@link JSONValue}, a {@link XMLDocument} or a
* {@link XMLElement}
*
* @author Josua Frank
*/
public class AData {
}
| Sharknoon/dfMASTER | dfMASTER/src/main/java/dfmaster/general/AData.java | Java | gpl-3.0 | 1,113 |
package io.valhala.javamon.pokemon.skeleton;
import io.valhala.javamon.pokemon.Pokemon;
import io.valhala.javamon.pokemon.type.Type;
public abstract class Paras extends Pokemon {
public Paras() {
super("Paras", 35, 70, 55, 25, 55, true, 46,Type.BUG,Type.GRASS);
// TODO Auto-generated constructor stub
}
}
| mirgantrophy/Pokemon | src/io/valhala/javamon/pokemon/skeleton/Paras.java | Java | gpl-3.0 | 316 |
package de.unikiel.inf.comsys.neo4j.inference.sail;
/*
* #%L
* neo4j-sparql-extension
* %%
* Copyright (C) 2014 Niclas Hoyer
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import de.unikiel.inf.comsys.neo4j.inference.QueryRewriter;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.parser.ParsedBooleanQuery;
import org.openrdf.repository.sail.SailBooleanQuery;
import org.openrdf.repository.sail.SailRepositoryConnection;
/**
* A subclass of {@link SailBooleanQuery} with a public constructor to
* pass in a boolean query containing a tuple expression.
*
* The original constructor of {@link SailBooleanQuery} is protected, thus
* it is not possible to create a new boolean query from a parsed query
* that is used to create a query from a {@link TupleExpr}.
*
* @see QueryRewriter
*/
public class SailBooleanExprQuery extends SailBooleanQuery {
public SailBooleanExprQuery(ParsedBooleanQuery booleanQuery, SailRepositoryConnection sailConnection) {
super(booleanQuery, sailConnection);
}
}
| niclashoyer/neo4j-sparql-extension | src/main/java/de/unikiel/inf/comsys/neo4j/inference/sail/SailBooleanExprQuery.java | Java | gpl-3.0 | 1,670 |
package redsgreens.Pigasus;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
/**
* Handle events for all Player related events
* @author redsgreens
*/
public class PigasusPlayerListener implements Listener {
private final Pigasus plugin;
public PigasusPlayerListener(Pigasus instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event)
// catch player+entity events, looking for wand usage on an entity
{
Entity entity = event.getRightClicked();
// return if something not allowed was clicked
if(plugin.Config.getHoveringChance(entity) == -1) return;
Player player = event.getPlayer();
// return if the click was with something other than the wand
if(player.getItemInHand().getType() != plugin.Config.WandItem) return;
// check for permission
if(!plugin.isAuthorized(player, "wand") && !plugin.isAuthorized(player, "wand." + PigasusFlyingEntity.getType(entity).name().toLowerCase()))
{
if(plugin.Config.ShowErrorsInClient)
player.sendMessage("§cErr: " + plugin.Name + ": you don't have permission.");
return;
}
// checks passed, make this pig fly!
plugin.Manager.addEntity(entity);
}
}
| redsgreens/Pigasus | src/redsgreens/Pigasus/PigasusPlayerListener.java | Java | gpl-3.0 | 1,558 |
package fi.metatavu.edelphi.jsons.queries;
import java.util.Locale;
import fi.metatavu.edelphi.smvcj.SmvcRuntimeException;
import fi.metatavu.edelphi.smvcj.controllers.JSONRequestContext;
import fi.metatavu.edelphi.DelfoiActionName;
import fi.metatavu.edelphi.EdelfoiStatusCode;
import fi.metatavu.edelphi.dao.querydata.QueryReplyDAO;
import fi.metatavu.edelphi.dao.querylayout.QueryPageDAO;
import fi.metatavu.edelphi.dao.users.UserDAO;
import fi.metatavu.edelphi.domainmodel.actions.DelfoiActionScope;
import fi.metatavu.edelphi.domainmodel.querydata.QueryReply;
import fi.metatavu.edelphi.domainmodel.querylayout.QueryPage;
import fi.metatavu.edelphi.domainmodel.resources.Query;
import fi.metatavu.edelphi.domainmodel.resources.QueryState;
import fi.metatavu.edelphi.domainmodel.users.User;
import fi.metatavu.edelphi.i18n.Messages;
import fi.metatavu.edelphi.jsons.JSONController;
import fi.metatavu.edelphi.query.QueryPageHandler;
import fi.metatavu.edelphi.query.QueryPageHandlerFactory;
import fi.metatavu.edelphi.utils.ActionUtils;
import fi.metatavu.edelphi.utils.QueryDataUtils;
public class SaveQueryAnswersJSONRequestController extends JSONController {
public SaveQueryAnswersJSONRequestController() {
super();
setAccessAction(DelfoiActionName.ACCESS_PANEL, DelfoiActionScope.PANEL);
}
@Override
public void process(JSONRequestContext jsonRequestContext) {
UserDAO userDAO = new UserDAO();
QueryPageDAO queryPageDAO = new QueryPageDAO();
QueryReplyDAO queryReplyDAO = new QueryReplyDAO();
Long queryPageId = jsonRequestContext.getLong("queryPageId");
QueryPage queryPage = queryPageDAO.findById(queryPageId);
Query query = queryPage.getQuerySection().getQuery();
Messages messages = Messages.getInstance();
Locale locale = jsonRequestContext.getRequest().getLocale();
if (query.getState() == QueryState.CLOSED)
throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_CLOSED, messages.getText(locale, "exception.1027.cannotSaveReplyQueryClosed"));
if (query.getState() == QueryState.EDIT) {
if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString()))
throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_IN_EDIT_STATE, messages.getText(locale, "exception.1028.cannotSaveReplyQueryInEditState"));
}
else {
User loggedUser = null;
if (jsonRequestContext.isLoggedIn())
loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId());
QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query);
if (queryReply == null) {
throw new SmvcRuntimeException(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant"));
}
queryReplyDAO.updateLastModified(queryReply, loggedUser);
QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply);
QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType());
queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply);
}
}
}
| Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/jsons/queries/SaveQueryAnswersJSONRequestController.java | Java | gpl-3.0 | 3,237 |
package org.craftercms.studio.api.dto;
public class UserTest {
public void testGetUserId() throws Exception {
}
public void testSetUserId() throws Exception {
}
public void testGetPassword() throws Exception {
}
public void testSetPassword() throws Exception {
}
}
| craftercms/studio3 | api/src/test/java/org/craftercms/studio/api/dto/UserTest.java | Java | gpl-3.0 | 305 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. GarcÃa ([email protected])
A. Fernández ([email protected])
J. Luengo ([email protected])
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 keel.Algorithms.Genetic_Rule_Learning.RMini;
import java.util.StringTokenizer;
import org.core.Fichero;
import java.util.StringTokenizer;
/**
* <p>Title: Main Class of the Program</p>
*
* <p>Description: It reads the configuration file (data-set files and parameters) and launch the algorithm</p>
*
* <p>Company: KEEL</p>
*
* @author Jesús Jiménez
* @version 1.0
*/
public class Main {
private parseParameters parameters;
/** Default Constructor */
public Main() {
}
/**
* It launches the algorithm
* @param confFile String it is the filename of the configuration file.
*/
private void execute(String confFile) {
parameters = new parseParameters();
parameters.parseConfigurationFile(confFile);
RMini method = new RMini(parameters);
method.execute();
}
/**
* Main Program
* @param args It contains the name of the configuration file<br/>
* Format:<br/>
* <em>algorith = <algorithm name></em><br/>
* <em>inputData = "<training file>" "<validation file>" "<test file>"</em> ...<br/>
* <em>outputData = "<training file>" "<test file>"</em> ...<br/>
* <br/>
* <em>seed = value</em> (if used)<br/>
* <em><Parameter1> = <value1></em><br/>
* <em><Parameter2> = <value2></em> ... <br/>
*/
public static void main(String args[]) {
Main program = new Main();
System.out.println("Executing Algorithm.");
program.execute(args[0]);
}
} | SCI2SUGR/KEEL | src/keel/Algorithms/Genetic_Rule_Learning/RMini/Main.java | Java | gpl-3.0 | 2,637 |
/*
* Jinx is Copyright 2010-2020 by Jeremy Brooks and Contributors
*
* Jinx 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.
*
* Jinx 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 Jinx. If not, see <http://www.gnu.org/licenses/>.
*/
package net.jeremybrooks.jinx.api;
import net.jeremybrooks.jinx.Jinx;
import net.jeremybrooks.jinx.JinxException;
import net.jeremybrooks.jinx.JinxUtils;
import net.jeremybrooks.jinx.response.Response;
import net.jeremybrooks.jinx.response.photos.notes.Note;
import java.util.Map;
import java.util.TreeMap;
/**
* Provides access to the flickr.photos.notes API methods.
*
* @author Jeremy Brooks
* @see <a href="https://www.flickr.com/services/api/">Flickr API documentation</a> for more details.
*/
public class PhotosNotesApi {
private Jinx jinx;
public PhotosNotesApi(Jinx jinx) {
this.jinx = jinx;
}
/**
* Add a note to a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages.
* <br>
* This method requires authentication with 'write' permission.
*
* @param photoId (Required) The id of the photo to add a note to.
* @param noteX (Required) The left coordinate of the note.
* @param noteY (Required) The top coordinate of the note.
* @param noteWidth (Required) The width of the note.
* @param noteHeight (Required) The height of the note.
* @param noteText (Required) The text of the note.
* @return object with the ID for the newly created note.
* @throws JinxException if required parameters are missing, or if there are any errors.
* @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.add.html">flickr.photos.notes.add</a>
*/
public Note add(String photoId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException {
JinxUtils.validateParams(photoId, noteText);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.add");
params.put("photo_id", photoId);
params.put("note_x", Integer.toString(noteX));
params.put("note_y", Integer.toString(noteY));
params.put("note_w", Integer.toString(noteWidth));
params.put("note_h", Integer.toString(noteHeight));
params.put("note_text", noteText);
return jinx.flickrPost(params, Note.class);
}
/**
* Edit a note on a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages.
* <br>
* This method requires authentication with 'write' permission.
*
* @param noteId (Required) The id of the note to edit.
* @param noteX (Required) The left coordinate of the note.
* @param noteY (Required) The top coordinate of the note.
* @param noteWidth (Required) The width of the note.
* @param noteHeight (Required) The height of the note.
* @param noteText (Required) The text of the note.
* @return object with the status of the requested operation.
* @throws JinxException if required parameters are missing, or if there are any errors.
* @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.edit.html">flickr.photos.notes.edit</a>
*/
public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException {
JinxUtils.validateParams(noteId, noteText);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.edit");
params.put("note_id", noteId);
params.put("note_x", Integer.toString(noteX));
params.put("note_y", Integer.toString(noteY));
params.put("note_w", Integer.toString(noteWidth));
params.put("note_h", Integer.toString(noteHeight));
params.put("note_text", noteText);
return jinx.flickrPost(params, Response.class);
}
/**
* Delete a note from a photo.
* <br>
* This method requires authentication with 'write' permission.
*
* @param noteId (Required) The id of the note to delete.
* @return object with the status of the requested operation.
* @throws JinxException if required parameters are missing, or if there are any errors.
* @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.delete.html">flickr.photos.notes.delete</a>
*/
public Response delete(String noteId) throws JinxException {
JinxUtils.validateParams(noteId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photos.notes.delete");
params.put("note_id", noteId);
return jinx.flickrPost(params, Response.class);
}
}
| jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PhotosNotesApi.java | Java | gpl-3.0 | 5,049 |
package de.jotschi.geo.osm.tags;
import org.w3c.dom.Node;
public class OsmMember {
String type, ref, role;
public OsmMember(Node node) {
ref = node.getAttributes().getNamedItem("ref").getNodeValue();
role = node.getAttributes().getNamedItem("role").getNodeValue();
type = node.getAttributes().getNamedItem("type").getNodeValue();
}
public String getType() {
return type;
}
public String getRef() {
return ref;
}
public String getRole() {
return role;
}
}
| Jotschi/libTinyOSM | src/main/java/de/jotschi/geo/osm/tags/OsmMember.java | Java | gpl-3.0 | 490 |
/*******************************************************************************
* This file is part of RedReader.
*
* RedReader 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.
*
* RedReader 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 RedReader. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.quantumbadger.redreader.io;
import org.quantumbadger.redreader.common.collections.WeakReferenceListManager;
public class UpdatedVersionListenerNotifier<K, V extends WritableObject<K>>
implements WeakReferenceListManager.ArgOperator<UpdatedVersionListener<K, V>, V> {
@Override
public void operate(final UpdatedVersionListener<K, V> listener, final V data) {
listener.onUpdatedVersion(data);
}
}
| QuantumBadger/RedReader | src/main/java/org/quantumbadger/redreader/io/UpdatedVersionListenerNotifier.java | Java | gpl-3.0 | 1,255 |
/* Copyright David Strachan Buchan 2013
* This file is part of BounceBallGame.
BounceBallGame 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.
BounceBallGame 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 BounceBallGame. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.ashndave;
import javax.swing.JFrame;
import uk.co.ashndave.game.GameLoop;
import uk.co.ashndave.game.Renderable;
import uk.co.ashndave.game.Updateable;
public class KeepyUppy {
private static final String BriefLicence1 = "Copyright (C) 2013 David Strachan Buchan.";
private static final String BriefLicence2 = "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.";
private static final String BriefLicence3 = "This is free software: you are free to change and redistribute it.";
private static final String BriefLicence4 = "There is NO WARRANTY, to the extent permitted by law.";
private static final String BriefLicence5 = "Written by David Strachan Buchan.";
private static final String[] BriefLicence = new String[]{BriefLicence1, BriefLicence2,BriefLicence3,BriefLicence4,BriefLicence5};
private Thread animator;
private GameLoop looper;
private GamePanel gamePanel;
private static KeepyUppy game;
/**
* @param args
*/
public static void main(String[] args) {
printLicence();
game = new KeepyUppy();
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
game.createAndShowGUI();
}
});
}
private static void printLicence() {
for(String licence : BriefLicence) {
System.out.println(licence);
}
}
protected void createAndShowGUI() {
gamePanel = new GamePanel();
looper = new GameLoop(gamePanel, gamePanel);
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(gamePanel);
frame.pack();
frame.setVisible(true);
animator = new Thread(looper);
animator.start();
}
}
| davidsbuchan/BounceBallGame | src/uk/co/ashndave/KeepyUppy.java | Java | gpl-3.0 | 2,378 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sshd.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.Pair;
/**
* A wrapper that exposes a read-only {@link Map} access to the system
* properties. Any attempt to modify it will throw {@link UnsupportedOperationException}.
* The mapper uses the {@link #SYSPROPS_MAPPED_PREFIX} to filter and access'
* only these properties, ignoring all others
*
* @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a>
*/
public final class SyspropsMapWrapper implements Map<String, Object> {
/**
* Prefix of properties used by the mapper to identify SSHD related settings
*/
public static final String SYSPROPS_MAPPED_PREFIX = "org.apache.sshd.config";
/**
* The one and only wrapper instance
*/
public static final SyspropsMapWrapper INSTANCE = new SyspropsMapWrapper();
/**
* A {@link PropertyResolver} with no parent that exposes the system properties
*/
public static final PropertyResolver SYSPROPS_RESOLVER = new PropertyResolver() {
@Override
public Map<String, Object> getProperties() {
return SyspropsMapWrapper.INSTANCE;
}
@Override
public PropertyResolver getParentPropertyResolver() {
return null;
}
@Override
public String toString() {
return "SYSPROPS";
}
};
private SyspropsMapWrapper() {
super();
}
@Override
public void clear() {
throw new UnsupportedOperationException("sysprops#clear() N/A");
}
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(Object value) {
// not the most efficient implementation, but we do not expect it to be called much
Properties props = System.getProperties();
for (String key : props.stringPropertyNames()) {
if (!isMappedSyspropKey(key)) {
continue;
}
Object v = props.getProperty(key);
if (Objects.equals(v, value)) {
return true;
}
}
return false;
}
@Override
public Set<Entry<String, Object>> entrySet() {
Properties props = System.getProperties();
// return a copy in order to avoid concurrent modifications
Set<Entry<String, Object>> entries =
new TreeSet<Entry<String, Object>>(Pair.<String, Object>byKeyEntryComparator());
for (String key : props.stringPropertyNames()) {
if (!isMappedSyspropKey(key)) {
continue;
}
Object v = props.getProperty(key);
if (v != null) {
entries.add(new Pair<>(getUnmappedSyspropKey(key), v));
}
}
return entries;
}
@Override
public Object get(Object key) {
return (key instanceof String) ? System.getProperty(getMappedSyspropKey(key)) : null;
}
@Override
public boolean isEmpty() {
return GenericUtils.isEmpty(keySet());
}
@Override
public Set<String> keySet() {
Properties props = System.getProperties();
Set<String> keys = new TreeSet<>();
// filter out any non-SSHD properties
for (String key : props.stringPropertyNames()) {
if (isMappedSyspropKey(key)) {
keys.add(getUnmappedSyspropKey(key));
}
}
return keys;
}
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException("sysprops#put(" + key + ")[" + value + "] N/A");
}
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
throw new UnsupportedOperationException("sysprops#putAll(" + m + ") N/A");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("sysprops#remove(" + key + ") N/A");
}
@Override
public int size() {
return GenericUtils.size(keySet());
}
@Override
public Collection<Object> values() {
Properties props = System.getProperties();
// return a copy in order to avoid concurrent modifications
List<Object> values = new ArrayList<>(props.size());
for (String key : props.stringPropertyNames()) {
if (!isMappedSyspropKey(key)) {
continue;
}
Object v = props.getProperty(key);
if (v != null) {
values.add(v);
}
}
return values;
}
@Override
public String toString() {
return Objects.toString(System.getProperties(), null);
}
/**
* @param key Key to be tested
* @return {@code true} if key starts with {@link #SYSPROPS_MAPPED_PREFIX}
* and continues with a dot followed by some characters
*/
public static boolean isMappedSyspropKey(String key) {
return (GenericUtils.length(key) > (SYSPROPS_MAPPED_PREFIX.length() + 1))
&& key.startsWith(SYSPROPS_MAPPED_PREFIX)
&& (key.charAt(SYSPROPS_MAPPED_PREFIX.length()) == '.');
}
/**
* @param key Key to be transformed
* @return The "pure" key name if a mapped one, same as input otherwise
* @see #isMappedSyspropKey(String)
*/
public static String getUnmappedSyspropKey(Object key) {
String s = Objects.toString(key);
return isMappedSyspropKey(s) ? s.substring(SYSPROPS_MAPPED_PREFIX.length() + 1 /* skip dot */) : s;
}
/**
* @param key The original key
* @return A key prefixed by {@link #SYSPROPS_MAPPED_PREFIX}
* @see #isMappedSyspropKey(String)
*/
public static String getMappedSyspropKey(Object key) {
return SYSPROPS_MAPPED_PREFIX + "." + key;
}
}
| Niky4000/UsefulUtils | projects/ssh/apache_mina/apache-sshd-1.2.0/sshd-core/src/main/java/org/apache/sshd/common/SyspropsMapWrapper.java | Java | gpl-3.0 | 6,908 |
package com.baeldung.jhipster5.web.rest;
import com.baeldung.jhipster5.BookstoreApp;
import com.baeldung.jhipster5.config.Constants;
import com.baeldung.jhipster5.domain.Authority;
import com.baeldung.jhipster5.domain.User;
import com.baeldung.jhipster5.repository.AuthorityRepository;
import com.baeldung.jhipster5.repository.UserRepository;
import com.baeldung.jhipster5.security.AuthoritiesConstants;
import com.baeldung.jhipster5.service.MailService;
import com.baeldung.jhipster5.service.UserService;
import com.baeldung.jhipster5.service.dto.PasswordChangeDTO;
import com.baeldung.jhipster5.service.dto.UserDTO;
import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator;
import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM;
import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AccountResource REST controller.
*
* @see AccountResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BookstoreApp.class)
public class AccountResourceIntTest {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private HttpMessageConverter<?>[] httpMessageConverters;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Mock
private UserService mockUserService;
@Mock
private MailService mockMailService;
private MockMvc restMvc;
private MockMvc restUserMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(any());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService);
AccountResource accountUserMockResource =
new AccountResource(userRepository, mockUserService, mockMailService);
this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
.setMessageConverters(httpMessageConverters)
.setControllerAdvice(exceptionTranslator)
.build();
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void testNonAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
public void testAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.with(request -> {
request.setRemoteUser("test");
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("test"));
}
@Test
public void testGetExistingAccount() throws Exception {
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.ADMIN);
authorities.add(authority);
User user = new User();
user.setLogin("test");
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("[email protected]");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user));
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value("test"))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("[email protected]"))
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
public void testGetUnknownAccount() throws Exception {
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty());
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(status().isInternalServerError());
}
@Test
@Transactional
public void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("[email protected]");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse();
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
@Test
@Transactional
public void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log!n");// <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByEmailIgnoreCase("[email protected]");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterInvalidEmail() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("password");
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("invalid");// <-- invalid
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterInvalidPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("123");// password with only 3 digits
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterNullPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword(null);// invalid null password
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterDuplicateLogin() throws Exception {
// First registration
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("alice");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Something");
firstUser.setEmail("[email protected]");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin(firstUser.getLogin());
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail("[email protected]");
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setCreatedBy(firstUser.getCreatedBy());
secondUser.setCreatedDate(firstUser.getCreatedDate());
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// First user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
// Second (non activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("[email protected]");
assertThat(testUser.isPresent()).isTrue();
testUser.get().setActivated(true);
userRepository.save(testUser.get());
// Second (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
public void testRegisterDuplicateEmail() throws Exception {
// First user
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("test-register-duplicate-email");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Test");
firstUser.setEmail("[email protected]");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Register first user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser1.isPresent()).isTrue();
// Duplicate email, different login
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin("test-register-duplicate-email-2");
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail(firstUser.getEmail());
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register second (non activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser2.isPresent()).isFalse();
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2");
assertThat(testUser3.isPresent()).isTrue();
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(firstUser.getId());
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
userWithUpperCaseEmail.setEmail("[email protected]");
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register third (not activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3");
assertThat(testUser4.isPresent()).isTrue();
assertThat(testUser4.get().getEmail()).isEqualTo("[email protected]");
testUser4.get().setActivated(true);
userService.updateUser((new UserDTO(testUser4.get())));
// Register 4th (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
public void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("[email protected]");
validUser.setActivated(true);
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
Optional<User> userDup = userRepository.findOneByLogin("badguy");
assertThat(userDup.isPresent()).isTrue();
assertThat(userDup.get().getAuthorities()).hasSize(1)
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get());
}
@Test
@Transactional
public void testActivateAccount() throws Exception {
final String activationKey = "some activation key";
User user = new User();
user.setLogin("activate-account");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(false);
user.setActivationKey(activationKey);
userRepository.saveAndFlush(user);
restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.getActivated()).isTrue();
}
@Test
@Transactional
public void testActivateAccountWithWrongKey() throws Exception {
restMvc.perform(get("/api/activate?key=wrongActivationKey"))
.andExpect(status().isInternalServerError());
}
@Test
@Transactional
@WithMockUser("save-account")
public void testSaveAccount() throws Exception {
User user = new User();
user.setLogin("save-account");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
assertThat(updatedUser.getActivated()).isEqualTo(true);
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test
@Transactional
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
User user = new User();
user.setLogin("save-invalid-email");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@Test
@Transactional
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("[email protected]");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
userRepository.saveAndFlush(anotherUser);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
@Test
@Transactional
@WithMockUser("save-existing-email-and-login")
public void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
user.setLogin("save-existing-email-and-login");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
@Test
@Transactional
@WithMockUser("change-password-wrong-existing-password")
public void testChangePasswordWrongExistingPassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-wrong-existing-password");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-small");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-empty");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
public void testRequestPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("[email protected]"))
.andExpect(status().isOk());
}
@Test
@Transactional
public void testRequestPasswordResetUpperCaseEmail() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("[email protected]"))
.andExpect(status().isOk());
}
@Test
public void testRequestPasswordResetWrongEmail() throws Exception {
restMvc.perform(
post("/api/account/reset-password/init")
.content("[email protected]"))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
public void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test
@Transactional
public void testFinishPasswordResetWrongKey() throws Exception {
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey("wrong reset key");
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java | Java | gpl-3.0 | 34,406 |
/*
* 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 xmv.solutions.IT2JZ.Jira;
/**
*
* @author David Koller XMV Solutions GmbH
*/
public class JiraTestcaseStep {
/**
* Name of Step (e.g. "Step 1")
*/
private String stepName;
/**
* Action to give in actual step (e.g. "Press red button")
*/
private String testData;
/**
* Expected result of action for current step (e.g. "Popup is shown saying 'Done!'")
*/
private String expectedResult;
public String getStepName() {
return stepName;
}
public void setStepName(String stepName) {
this.stepName = stepName;
}
public String getTestData() {
return testData;
}
public void setTestData(String testData) {
this.testData = testData;
}
public String getExpectedResult() {
return expectedResult;
}
public void setExpectedResult(String expectedResult) {
this.expectedResult = expectedResult;
}
} | XMV-Solutions/ImportTestcases2JiraZephyr | src/main/java/xmv/solutions/IT2JZ/Jira/JiraTestcaseStep.java | Java | gpl-3.0 | 1,034 |
/*
package de.elxala.langutil
(c) Copyright 2006 Alejandro Xalabarder Aulet
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, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
//(o) WelcomeGastona_source_javaj_layout EVALAYOUT
========================================================================================
================ documentation for WelcomeGastona.gast =================================
========================================================================================
#gastonaDoc#
<docType> javaj_layout
<name> EVALAYOUT
<groupInfo>
<javaClass> de.elxala.Eva.layout.EvaLayout
<importance> 10
<desc> //A fexible grid layout
<help>
//
// Eva layout is the most powerful layout used by Javaj. The components are laid out in a grid
// and it is possible to define very accurately which cells of the grid occupy each one, which
// size has to have and if they are expandable or not.
//
// Syntax:
//
// <layout of NAME>
// EVALAYOUT, marginX, marginY, gapX, gapY
//
// --grid-- , header col1, ... , header colN
// header row1, cell 1 1 , ... , cell 1 N
// ... , ... , ... , ...
// header rowM, cell M 1 , ... , cell M N
//
// The first row starts with "EVALAYOUT" or simply "EVA", then optionally the following values
// in pixels for the whole grid
//
// marginX : horizontal margins for both left and right sides
// marginY : vertical margins for both top and bottom areas
// gapX : horizontal space between columns
// gapY : vertical space between rows
//
// The rest of rows defines a grid with arbitrary N columns and M rows, the minimum for both M
// and N is 1. To define a grid M x N we will need M+1 rows and a maximum of N+1 columns, this
// is because the header types given in rows and columns. These header values may be one of:
//
// header
// value meaning
// ------- --------
// A Adapt (default). The row or column will adapt its size to the bigest default
// size of all components that start in this row or column.
// X Expand. The row or column is expandable, when the the frame is resized all
// expandable row or columns will share the remaining space equally.
// a number A fix size in pixels for the row or column
//
// Note that the very first header ("--grid--") acctually does not correspond with a row or a
// column of the grid and therefore it is ignored by EvaLayout.
//
// Finally the cells are used to place and expand the components. If we want the component to
// ocupy just one cell then we place it in that cell. If we want the component to ocupy more
// cells then we place the component on the left-top cell of the rectangle of cells to be
// ocupped, we fill the rest of top cells with "-" to the right and the rest of left cells with
// the symbol "+" to the bottom, the rest of cells (neither top or left cells) might be left in
// blank.
//
// Example:
//
// let's say we want to lay-out the following form
//
// ----------------------------------------------
// | label1 | field -------> | button1 |
// ----------------------------------------------
// | label2 | text -------> | button2 |
// ------------| | |----------
// | | | button3 |
// | V |----------
// | |
// ------------------------
//
// representing this as grid of cells can be done at least in these two ways
//
//
// Adapt Adapt Expand Adapt Adapt Expand Adapt
// ------------------------------------- -----------------------------
// Adapt | label1 | field | - | button1 | Adapt | label1 | field | button1 |
// |---------|-------|-------|---------| |---------|-------|---------|
// Adapt | label2 | text | - | button2 | Adapt | label2 | text | button2 |
// |---------|------ |-------|---------| |---------|------ |---------|
// Adapt | | + | | button3 | Adapt | | + | button3 |
// |---------|------ |-------|---------| |---------|------ |---------|
// Expand | | + | | | Expand | | + | |
// ------------------------------------- -----------------------------
//
// the implementation of the second one as Evalayout would be
//
// <layout of myFirstLayout>
//
// EVALAYOUT
//
// grid, A , X , A
// A, label1 , field , button1
// A, label2 , text , button2
// A, , + , button3
// X, , + ,
//
// NOTE: While columns and rows of type expandable or fixed size might be empty of components,
// this does not make sense for columns and rows of type adaptable (A), since in this
// case there is nothing to adapt. These columns or rows has to be avoided because
// might produce undefined results.
//
<...>
// NOTE: EvaLayout is also available for C++ development with Windows Api and MFC,
// see as reference the article http://www.codeproject.com/KB/dialog/EvaLayout.aspx
//
<examples>
gastSample
eva layout example1
eva layout example2
eva layout example3
eva layout complet
eva layout centering
eva layout percenting
<eva layout example1>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example layout EVALAYOUT"
//
// <layout of F>
//
// EVALAYOUT, 10, 10, 5, 5
//
// grid, , X ,
// , lLabel1 , eField1 , bButton1
// , lLabel2 , xText1 , bButton2
// , , + , bButton3
// X , , + ,
<eva layout example2>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example 2 layout EVALAYOUT"
//
// <layout of F>
//
// EVA, 10, 10, 5, 5
//
// --- , 75 , X , A ,
// , bButton , xMemo , - ,
// , bBoton , + , ,
// , bKnopf , + , ,
// X , , + , ,
// , eCamp , - , bBotó maco ,
<eva layout example3>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example 2 bis layout EVALAYOUT"
//
// <layout of F>
// EVALAYOUT, 15, 15, 5, 5
//
// , , X ,
// 50, bBoton1 , - , -
// , bBoton4 , eField , bBoton2
// X , + , xText , +
// 50, bBoton3 , - , +
<eva layout complet>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example complex layout"
//
// <layout of F>
// EVALAYOUT, 15, 15, 5, 5
//
// ---, 80 , X , 110
// , lLabel1 , eEdit1 , -
// , lLabel2 , cCombo , lLabel3
// , lLabel4 , xMemo , iLista
// , bBoton1 , + , +
// , bBoton2 , + , +
// X , , + , +
// , layOwner , - , +
// , , , bBoton4
//
// <layout of layOwner>
// PANEL, Y, Owner Info
//
// LayFields
//
// <layout of LayFields>
// EVALAYOUT, 5, 5, 5, 5
//
// ---, , X
// , lName , eName
// , lPhone , ePhone
//
<eva layout centering>
//#gastona#
//
// <PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// Fmain, Centering with EvaLayout demo
//
// <layout of Fmain>
// EVA
//
// , X, A , X
// X ,
// A , , bCentered
// X ,
<eva layout percenting>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// Fmain, Percenting with EvaLayout demo, 300, 300
//
// <layout of Fmain>
// EVA, 10, 10, 7, 7
//
// , X , X , X , X
// X , b11 , b13 , - , -
// X , b22 , - , b23 , -
// X , + , , + ,
// X , b12 , - , + ,
//
//#data#
//
// <b11> 25% x 25%
// <b13> 75% horizontally 25% vertically
// <b22> fifty-fifty
// <b12> 50% x 25% y
// <b23> half and 3/4
#**FIN_EVA#
*/
package de.elxala.Eva.layout;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration; // to traverse the HashTable ...
import java.awt.*;
import de.elxala.Eva.*;
import de.elxala.langutil.*;
import de.elxala.zServices.*;
/**
@author Alejandro Xalabarder
@date 11.04.2006 22:32
Example:
<pre>
import java.awt.*;
import javax.swing.*;
import de.elxala.Eva.*;
import de.elxala.Eva.layout.*;
public class sampleEvaLayout
{
public static void main (String [] aa)
{
JFrame frame = new JFrame ("sampleEvaLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane ();
Eva lay = new Eva();
// set margins
lay.addLine (new EvaLine ("EvaLayout, 15, 15, 5, 5"));
// set grid
lay.addLine (new EvaLine ("RxC, , 100 , X ,"));
lay.addLine (new EvaLine (" , lname , eName , ,"));
lay.addLine (new EvaLine (" , lobserv, xObs , - ,"));
lay.addLine (new EvaLine (" X, , + , ,"));
pane.setLayout (new EvaLayout(lay));
pane.add ("lname", new JLabel("Name"));
pane.add ("lobserv", new JLabel("Notes"));
pane.add ("eName", new JTextField());
pane.add ("xObs", new JTextPane());
frame.pack();
frame.setSize (new Dimension (300, 200));
frame.show();
}
}
</pre>
*/
public class EvaLayout implements LayoutManager2
{
private static logger log = new logger (null, "de.elxala.Eva.EvaLayout", null);
//19.10.2010 20:31
// Note : Limits introduced in change (bildID) 11088 on 2010-09-20 01:47:25
// named "FIX problema en layout (LOW LEVEL BUG 2!)"
// But today the problem (without limits) cannot be reproduced! (?)
// Limits set as aproximation, these can be reviewed and changed
//
private static int MAX_SIZE_DX = 10000;
private static int MAX_SIZE_DY = 10000;
protected static final int HEADER_EXPAND = 10;
protected static final int HEADER_ORIGINAL = 11;
protected static final int HEADER_NUMERIC = 12;
protected static final String EXPAND_HORIZONTAL = "-";
protected static final String EXPAND_VERTICAL = "+";
// variables for pre-calculated layout
//
private boolean isPrecalculated = false;
protected int Hmargin;
protected int Vmargin;
protected int Hgap;
protected int Vgap;
private int mnCols = -1; // note : this is a cached value and might be call before precalculation!
private int mnRows = -1; // note : this is a cached value and might be call before precalculation!
private int fijoH = 0;
private int fijoV = 0;
public int [] HdimMin = new int [0];
public int [] HdimPref = new int [0]; // for preferred instead of minimum
public int [] Hpos = new int [0];
public int [] VdimMin = new int [0];
public int [] VdimPref = new int [0]; // for preferred instead of minimum
public int [] Vpos = new int [0];
private Eva lay = null;
private Hashtable componentHTable = new Hashtable();
protected class widgetInfo
{
public widgetInfo (String nam, Component com)
{
name = nam;
comp = com;
}
public String name; // name of the component in the layout array
public Component comp; // component info
public boolean isLaidOut; // if the component has been found in the layout array
// and therefore if indxPos is a valid calculated field
// place in the layout array mesured in array indices
public int posCol0; // first column that the widget occupies
public int posRow0; // first row
public int posCol1; // last column
public int posRow1; // last row
}
Vector columnsReparto = new Vector ();
Vector rowsReparto = new Vector ();
public EvaLayout()
{
this(new Eva());
}
public EvaLayout(Eva layarray)
{
log.dbg (2, "EvaLayout", "create EvaLayout " + layarray.getName ());
lay = layarray;
}
/**
Switches to another layout : note that the components used in this new layout
has to exists (added to the layout using add method)
*/
public void switchLayout(Eva layarray)
{
log.dbg (2, "switchLayout", "switch new layout info " + layarray.getName ());
lay = layarray;
invalidatePreCalc ();
}
private int headType (String str)
{
if (str.length () == 0 ||
str.equalsIgnoreCase ("a")) return HEADER_ORIGINAL;
if (str.equalsIgnoreCase ("x")) return HEADER_EXPAND;
return HEADER_NUMERIC; // it should
}
private void precalculateAll ()
{
if (isPrecalculated) return;
log.dbg (2, "precalculateAll", "layout " + lay.getName () + " perform precalculation.");
Hmargin = Math.max (0, stdlib.atoi (lay.getValue (0,1)));
Vmargin = Math.max (0, stdlib.atoi (lay.getValue (0,2)));
Hgap = Math.max (0, stdlib.atoi (lay.getValue (0,3)));
Vgap = Math.max (0, stdlib.atoi (lay.getValue (0,4)));
log.dbg (4, "precalculateAll", nColumns() + " columns x " + nRows() + " rows");
log.dbg (4, "precalculateAll", "margins xm=" + Hmargin + ", ym=" + Vmargin + ", yg=" + Hgap + ", yg=" + Vgap);
mnCols = -1; // reset cached number of cols
mnRows = -1; // reset cached number of rows
HdimMin = new int [nColumns()];
HdimPref = new int [nColumns()];
Hpos = new int [nColumns()];
VdimMin = new int [nRows()];
VdimPref = new int [nRows()];
Vpos = new int [nRows()];
columnsReparto = new Vector ();
rowsReparto = new Vector ();
// for all components ...
Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
((widgetInfo) componentHTable.get(key)).isLaidOut = false;
}
// compute Vdim (Note: it might be precalculated if needed)
fijoV = Vmargin;
for (int rr = 0; rr < nRows(); rr ++)
{
String heaRow = rowHeader(rr);
int typ = headType(heaRow);
int gap = (rr == 0) ? 0: Vgap;
if (typ == HEADER_ORIGINAL)
{
// maximum-minimum of the row
VdimPref[rr] = minHeightOfRow(rr, true);
VdimMin[rr] = minHeightOfRow(rr, false);
log.dbg (2, "precalculateAll", "Adaption... VdimPref[rr] = " + VdimPref[rr]);
}
else if (typ == HEADER_EXPAND)
{
rowsReparto.add (new int [] { rr }); // compute later
log.dbg (2, "precalculateAll", "Expand... VdimPref[rr] = " + VdimPref[rr]);
}
else
{
// indicated size
VdimPref[rr] = VdimMin[rr] = stdlib.atoi(heaRow);
log.dbg (2, "precalculateAll", "Explicit... VdimPref[rr] = " + VdimPref[rr]);
}
Vpos[rr] = fijoV + gap;
fijoV += VdimPref[rr];
fijoV += gap;
}
fijoV += Vmargin;
log.dbg (2, "precalculateAll", "fijoV = " + fijoV + " Vmargin = " + Vmargin + " Vgap = " + Vgap);
//DEBUG ....
if (log.isDebugging (2))
{
String vertical = "Vertical array (posY/prefHeight/minHeight)";
for (int rr = 0; rr < Vpos.length; rr++)
vertical += " " + rr + ") " + Vpos[rr] + "/" + VdimPref[rr] + "/" + VdimMin[rr];
log.dbg (2, "precalculateAll", vertical);
}
// compute Hdim (Note: it might be precalculated if needed)
fijoH = Hmargin;
for (int cc = 0; cc < nColumns(); cc ++)
{
String heaCol = columnHeader(cc);
int typ = headType(heaCol);
int gap = (cc == 0) ? 0: Hgap;
if (typ == HEADER_ORIGINAL)
{
// maximum-minimum of the column
HdimPref[cc] = minWidthOfColumn(cc, true);
HdimMin[cc] = minWidthOfColumn(cc, false);
}
else if (typ == HEADER_EXPAND)
columnsReparto.add (new int [] { cc }); // compute later
else
HdimPref[cc] = HdimMin[cc] = stdlib.atoi(heaCol); // indicated size
Hpos[cc] = fijoH + gap;
fijoH += HdimPref[cc];
fijoH += gap;
}
fijoH += Hmargin;
log.dbg (2, "precalculateAll", "fijoH = " + fijoH);
//DEBUG ....
if (log.isDebugging (2))
{
String horizontal = "Horizontal array (posX/prefWidth/minWidth)";
for (int cc = 0; cc < Hpos.length; cc++)
horizontal += " " + cc + ") " + Hpos[cc] + "/" + HdimPref[cc] + "/" + HdimMin[cc];
log.dbg (2, "precalculateAll", horizontal);
}
// finding all components in the layout array
for (int cc = 0; cc < nColumns(); cc ++)
{
for (int rr = 0; rr < nRows(); rr ++)
{
String name = widgetAt(rr, cc);
widgetInfo wid = theComponent (name);
if (wid == null) continue;
// set position x,y
wid.posCol0 = cc;
wid.posRow0 = rr;
// set position x2,y2
int ava = cc;
while (ava+1 < nColumns() && widgetAt(rr, ava+1).equals (EXPAND_HORIZONTAL)) ava ++;
wid.posCol1 = ava;
ava = rr;
while (ava+1 < nRows() && widgetAt(ava+1, cc).equals (EXPAND_VERTICAL)) ava ++;
wid.posRow1 = ava;
wid.isLaidOut = true;
//DEBUG ....
if (log.isDebugging (2))
{
log.dbg (2, "precalculateAll", wid.name + " leftTop (" + wid.posCol0 + ", " + wid.posRow0 + ") rightBottom (" + wid.posCol1 + ", " + wid.posRow1 + ")");
}
}
}
isPrecalculated = true;
}
protected int nColumns ()
{
// OLD
// return Math.max(0, lay.cols(1) - 1);
if (mnCols != -1) return mnCols;
// has to be calculated,
// the maximum n of cols of header or rows
//
for (int ii = 1; ii < lay.rows (); ii ++)
if (mnCols < Math.max(0, lay.cols(ii) - 1))
mnCols = Math.max(0, lay.cols(ii) - 1);
mnCols = Math.max(0, mnCols);
return mnCols;
}
protected int nRows ()
{
// OLD
// return Math.max(0, lay.rows() - 2);
if (mnRows != -1) return mnRows;
mnRows = Math.max(0, lay.rows() - 2);
return mnRows;
}
public Eva getEva ()
{
return lay;
}
public String [] getWidgets ()
{
java.util.Vector vecWidg = new java.util.Vector ();
for (int rr = 0; rr < nRows(); rr ++)
for (int cc = 0; cc < nColumns(); cc ++)
{
String name = widgetAt (rr, cc);
if (name.length() > 0 && !name.equals(EXPAND_HORIZONTAL) && !name.equals(EXPAND_VERTICAL))
vecWidg.add (name);
}
// pasarlo a array
String [] arrWidg = new String [vecWidg.size ()];
for (int ii = 0; ii < arrWidg.length; ii ++)
arrWidg[ii] = (String) vecWidg.get (ii);
return arrWidg;
}
/**
* Adds the specified component with the specified name
*/
public void addLayoutComponent(String name, Component comp)
{
log.dbg (2, "addLayoutComponent", name + " compName (" + comp.getName () + ")");
componentHTable.put(name, new widgetInfo (name, comp));
isPrecalculated = false;
}
/**
* Removes the specified component from the layout.
* @param comp the component to be removed
*/
public void removeLayoutComponent(Component comp)
{
// componentHTable.remove(comp);
}
/**
* Calculates the preferred size dimensions for the specified
* panel given the components in the specified parent container.
* @param parent the component to be laid out
*/
public Dimension preferredLayoutSize(Container parent)
{
///*EXPERIMENT!!!*/invalidatePreCalc ();
Dimension di = getLayoutSize(parent, true);
log.dbg (2, "preferredLayoutSize", lay.getName() + " preferredLayoutSize (" + di.width + ", " + di.height + ")");
//(o) TODO_javaj_layingOut Problem: preferredLayoutSize
//19.04.2009 19:50 Problem: preferredLayoutSize is called when pack and after that no more
// layouts data dependent like slider (don't know if horizontal or vertical) have problems
// Note: this is not just a problem of EvaLayout but of all layout managers
//log.severe ("SEVERINIO!");
return di;
}
/**
* Calculates the minimum size dimensions for the specified
* panel given the components in the specified parent container.
* @param parent the component to be laid out
*/
public Dimension minimumLayoutSize(Container parent)
{
Dimension di = getLayoutSize(parent, false);
log.dbg (2, "minimumLayoutSize", lay.getName() + " minimumLayoutSize (" + di.width + ", " + di.height + ")");
return di;
}
/**
*calculating layout size (minimum or preferred).
*/
protected Dimension getLayoutSize(Container parent, boolean isPreferred)
{
log.dbg (2, "getLayoutSize", lay.getName());
precalculateAll ();
// In precalculateAll the methods minWidthOfColumn and minHeightOfRow
// does not evaluate expandable components since these might use other columns.
// But in order to calculate the minimum or preferred total size we need this information.
// In these cases we have to calculate following : if the sum of the sizes of the
// columns that the component occupies is less that the minimum/preferred size of
// the component then we add the difference to the total width
// We evaluate this ONLY for those components that could be expanded!
// for example
//
// NO COMPONENT HAS TO COMPONENTS comp1 and comp3
// BE RECALCULED HAS TO BE RECALCULED
// --------------------- ------------------------
// grid, 160 , A grid, 160 , X
// A , comp1 , - A , comp1 , -
// A , comp2 , comp3 X , comp2 , comp3
//
int [] extraCol = new int [nColumns ()];
int [] extraRow = new int [nRows ()];
int [] Hdim = isPreferred ? HdimPref: HdimMin;
int [] Vdim = isPreferred ? VdimPref: VdimMin;
//System.err.println ("PARLANT DE " + lay.getName () + " !!!");
// for all components ...
Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
boolean someExpan = false;
String key = (String) enu.nextElement();
widgetInfo wi = (widgetInfo) componentHTable.get(key);
if (! wi.isLaidOut) continue;
Dimension csiz = (isPreferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
log.dbg (2, "getLayoutSize", wi.name + " dim (" + csiz.width + ", " + csiz.height + ")");
// some column expandable ?
//
someExpan = false;
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
if (headType(columnHeader(cc)) == HEADER_EXPAND)
{
someExpan = true;
break;
}
if (someExpan)
{
// sum of all columns that this component occupy
int sum = 0;
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
sum += (Hdim[cc] + extraCol[cc]);
// distribute it in all columns to be salomonic
int resto = csiz.width - sum;
if (resto > 0)
{
if (wi.posCol0 == wi.posCol1)
{
// System.err.println ("Resto X " + resto + " de " + wi.name + " en la " + wi.posCol0 + " veniendo de csiz.width " + csiz.width + " y sum " + sum + " que repahartimos en " + (1 + wi.posCol1 - wi.posCol0) + " parates tenahamos una estra de " + extraCol[wi.posCol0]);
}
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
extraCol[cc] = resto / (1 + wi.posCol1 - wi.posCol0);
}
}
// some row expandable ?
//
someExpan = false;
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
if (headType(rowHeader(rr)) == HEADER_EXPAND)
{
someExpan = true;
break;
}
if (someExpan)
{
// sum of all height (rows) that this component occupy
int sum = 0;
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
sum += (Vdim[rr] + extraRow[rr]);
// distribute it in all columns to be salomonic
int resto = csiz.height - sum;
if (resto > 0)
{
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
extraRow[rr] = resto / (1 + wi.posRow1 - wi.posRow0);
}
}
}
int tot_width = 0;
for (int cc = 0; cc < nColumns(); cc ++)
{
tot_width += (Hdim[cc] + extraCol[cc]);
}
int tot_height = 0;
for (int rr = 0; rr < nRows(); rr ++)
{
tot_height += Vdim[rr] + extraRow[rr];
}
Insets insets = (parent != null) ? parent.getInsets(): new Insets(0,0,0,0);
tot_width += Hgap * (nColumns() - 1) + insets.left + insets.right + 2 * Hmargin;
tot_height += Vgap * (nRows() - 1) + insets.top + insets.bottom + 2 * Vmargin;
log.dbg (2, "getLayoutSize", "returning tot_width " + tot_width + ", tot_height " + tot_height);
// System.out.println ("getLayoutSize pref=" + isPreferred + " nos sale (" + tot_width + ", " + tot_height + ")");
return new Dimension (tot_width, tot_height);
}
private String columnHeader(int ncol)
{
return lay.getValue(1, ncol + 1).toUpperCase ();
}
private String rowHeader(int nrow)
{
return lay.getValue(2 + nrow, 0).toUpperCase ();
}
private String widgetAt(int nrow, int ncol)
{
return lay.getValue (nrow + 2, ncol + 1);
}
private widgetInfo theComponent(String cellName)
{
if (cellName.length() == 0 || cellName.equals(EXPAND_HORIZONTAL) || cellName.equals(EXPAND_VERTICAL)) return null;
widgetInfo wi = (widgetInfo) componentHTable.get(cellName);
if (wi == null)
log.severe ("theComponent", "Component " + cellName + " not found in the container laying out " + lay.getName () + "!");
return wi;
}
private int minWidthOfColumn (int ncol, boolean preferred)
{
// el componente ma's ancho de la columna
int maxwidth = 0;
for (int rr = 0; rr < nRows(); rr ++)
{
String name = widgetAt (rr, ncol);
widgetInfo wi = theComponent (name);
if (wi != null)
{
if (widgetAt (rr, ncol+1).equals(EXPAND_HORIZONTAL)) continue; // widget occupies more columns so do not compute it
Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
maxwidth = Math.max (maxwidth, csiz.width);
}
}
//19.09.2010 Workaround
//in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail!
return maxwidth > MAX_SIZE_DX ? MAX_SIZE_DX : maxwidth;
}
private int minHeightOfRow (int nrow, boolean preferred)
{
// el componente ma's alto de la columna
int maxheight = 0;
for (int cc = 0; cc < nColumns(); cc ++)
{
String name = widgetAt (nrow, cc);
widgetInfo wi = theComponent (name);
if (wi != null)
{
if (widgetAt (nrow+1, cc).equals(EXPAND_VERTICAL)) continue; // widget occupies more rows so do not compute it
Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
maxheight = Math.max (maxheight, csiz.height);
}
}
//19.09.2010 Workaround
//in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail!
return maxheight > MAX_SIZE_DY ? MAX_SIZE_DY : maxheight;
}
/**
* Lays out the container in the specified container.
* @param parent the component which needs to be laid out
*/
public void layoutContainer(Container parent)
{
//isPrecalculated = false;
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", lay.getName ());
precalculateAll ();
synchronized (parent.getTreeLock())
{
Insets insets = parent.getInsets();
//if (log.isDebugging(4))
// log.dbg (4, "layoutContainer", "insets left right =" + insets.left + ", " + insets.right + " top bottom " + insets.top + ", " + insets.bottom);
// Total parent dimensions
Dimension size = parent.getSize();
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "parent size =" + size.width + ", " + size.height);
int repartH = size.width - (insets.left + insets.right) - fijoH;
int repartV = size.height - (insets.top + insets.bottom) - fijoV;
int [] HextraPos = new int [HdimPref.length];
int [] VextraPos = new int [VdimPref.length];
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "repartH=" + repartH + " repartV=" + repartV);
// repartir H
if (columnsReparto.size() > 0)
{
repartH /= columnsReparto.size();
for (int ii = 0; ii < columnsReparto.size(); ii ++)
{
int indx = ((int []) columnsReparto.get (ii))[0];
HdimPref[indx] = repartH;
for (int res = indx+1; res < nColumns(); res ++)
HextraPos[res] += repartH;
}
}
// repartir V
if (rowsReparto.size() > 0)
{
repartV /= rowsReparto.size();
for (int ii = 0; ii < rowsReparto.size(); ii ++)
{
int indx = ((int []) rowsReparto.get (ii))[0];
VdimPref[indx] = repartV;
for (int res = indx+1; res < nRows(); res ++)
VextraPos[res] += repartV;
}
}
//
// for all components ... for (int ii = 0; ii < componentArray.size(); ii ++)
//
java.util.Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
widgetInfo wi = (widgetInfo) componentHTable.get(key);
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "element [" + key + "]");
// System.out.println ("componente " + wi.name);
if (! wi.isLaidOut) continue;
// System.out.println (" indices " + wi.posCol0 + " (" + Hpos[wi.posCol0] + " extras " + HextraPos[wi.posCol0] + ")");
int x = Hpos[wi.posCol0] + HextraPos[wi.posCol0];
int y = Vpos[wi.posRow0] + VextraPos[wi.posRow0];
int dx = 0;
int dy = 0;
//if (log.isDebugging(4))
// log.dbg (4, "SIGUEY", "1) y = " + y + " Vpos[wi.posRow0] = " + Vpos[wi.posRow0] + " VextraPos[wi.posRow0] = " + VextraPos[wi.posRow0]);
for (int mm = wi.posCol0; mm <= wi.posCol1; mm ++)
{
if (mm != wi.posCol0) dx += Hgap;
dx += HdimPref[mm];
}
for (int mm = wi.posRow0; mm <= wi.posRow1; mm ++)
{
if (mm != wi.posRow0) dy += Vgap;
dy += VdimPref[mm];
}
if (x < 0 || y < 0 || dx < 0 || dy < 0)
{
//Disable this warning because it happens very often when minimizing the window etc
//log.warn ("layoutContainer", "component not laid out! [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")");
continue;
}
wi.comp.setBounds(x, y, dx, dy);
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "vi.name [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")");
}
} // end synchronized
}
// LayoutManager2 /////////////////////////////////////////////////////////
/**
* This method make no sense in this layout, the constraints are not per component
* but per column and rows. Since this method is called when adding components through
* the method add(String, Component) we implement it as if constraints were the name
*/
public void addLayoutComponent(Component comp, Object constraints)
{
addLayoutComponent((String) constraints, comp);
}
/**
* Returns the maximum size of this component.
*/
public Dimension maximumLayoutSize(Container target)
{
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX(Container target)
{
return 0.5f;
}
/**
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY(Container target)
{
return 0.5f;
}
/**
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target)
{
invalidatePreCalc();
}
public void invalidatePreCalc()
{
isPrecalculated = false;
}
}
| wakeupthecat/gastona | pc/src/de/elxala/Eva/layout/EvaLayout.java | Java | gpl-3.0 | 36,814 |
package yio.tro.antiyoy.menu.customizable_list;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import yio.tro.antiyoy.gameplay.diplomacy.DiplomaticEntity;
import yio.tro.antiyoy.menu.render.AbstractRenderCustomListItem;
import yio.tro.antiyoy.menu.render.MenuRender;
import yio.tro.antiyoy.menu.scenes.Scenes;
import yio.tro.antiyoy.menu.scenes.gameplay.choose_entity.IDipEntityReceiver;
import yio.tro.antiyoy.stuff.Fonts;
import yio.tro.antiyoy.stuff.GraphicsYio;
public class SimpleDipEntityItem extends AbstractSingleLineItem{
public DiplomaticEntity diplomaticEntity;
public int backgroundColor;
@Override
protected BitmapFont getTitleFont() {
return Fonts.smallerMenuFont;
}
@Override
protected double getHeight() {
return 0.07f * GraphicsYio.height;
}
@Override
protected void onClicked() {
Scenes.sceneChooseDiplomaticEntity.onDiplomaticEntityChosen(diplomaticEntity);
}
public void setDiplomaticEntity(DiplomaticEntity diplomaticEntity) {
this.diplomaticEntity = diplomaticEntity;
backgroundColor = getGameController().colorsManager.getColorByFraction(diplomaticEntity.fraction);
setTitle("" + diplomaticEntity.capitalName);
}
@Override
public AbstractRenderCustomListItem getRender() {
return MenuRender.renderSimpleDipEntityItem;
}
}
| yiotro/Antiyoy | core/src/yio/tro/antiyoy/menu/customizable_list/SimpleDipEntityItem.java | Java | gpl-3.0 | 1,380 |
package standalone_tools;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import framework.DataQuery;
import framework.DiffComplexDetector;
import framework.DiffComplexDetector.SPEnrichment;
import framework.DiffSeedCombDetector;
import framework.QuantDACOResultSet;
import framework.Utilities;
/**
* CompleXChange cmd-tool
* @author Thorsten Will
*/
public class CompleXChange {
static String version_string = "CompleXChange 1.01";
private static String path_group1 = "[GROUP1-FOLDER]";
private static String path_group2 = "[GROUP2-FOLDER]";
private static Map<String, QuantDACOResultSet> group1;
private static Map<String, QuantDACOResultSet> group2;
private static String path_seed = "no seed file defined";
private static Set<String> seed = null;
private static String output_folder;
private static double FDR = 0.05;
private static boolean parametric = false;
private static boolean paired = false;
private static boolean incorporate_supersets = false;
private static double min_variant_fraction = 0.75;
private static boolean human_readable = false;
private static boolean also_seedcomb_calcs = false;
private static boolean also_seed_enrich = false;
private static boolean filter_allosome = false;
private static int no_threads = Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); // assuming HT/SMT systems
/**
* Reads all matching output pairs of JDACO results/major transcripts from a certain folder:
* [folder]/[sample-string]_complexes.txt(.gz) and [folder]/[sample-string]_major-transcripts.txt(.gz)
* @param folder
* @return
*/
public static Map<String, QuantDACOResultSet> readQuantDACOComplexes(String folder) {
Map<String, QuantDACOResultSet> data = new HashMap<>();
for (File f:Utilities.getAllSuffixMatchingFilesInSubfolders(folder, "_major-transcripts.txt")) {
String gz = "";
if (f.getName().endsWith(".gz"))
gz = ".gz";
String pre = f.getAbsolutePath().split("_major-transcripts")[0];
String sample = f.getName().split("_major-transcripts")[0];
QuantDACOResultSet qdr = new QuantDACOResultSet(pre + "_complexes.txt" + gz, seed, pre + "_major-transcripts.txt" + gz);
data.put(sample, qdr);
}
return data;
}
/**
* Prints the help message
*/
public static void printHelp() {
System.out.println("usage: java -jar CompleXChange.jar ([OPTIONS]) [GROUP1-FOLDER] [GROUP2-FOLDER] [OUTPUT-FOLDER]");
System.out.println();
System.out.println("[OPTIONS] (optional) :");
System.out.println(" -fdr=[FDR] : false discovery rate (default: 0.05)");
System.out.println(" -mf=[MIN_VAR_FRACTION] : fraction of either group a complex must be part of to be considered in the analysis (default: 0.75)");
System.out.println(" -s=[SEED-FILE] : file listing proteins around which the complexes are centered, e.g. seed file used for JDACO complex predictions (default: none)");
System.out.println(" -t=[#threads] : number of threads to be used (default: #cores/2)");
System.out.println(" -nd : assume normal distribution when testing (default: no assumption, non-parametric tests applied)");
System.out.println(" -p : assume paired/dependent data (default: unpaired/independent tests applied)");
System.out.println(" -ss : also associate supersets in the analyses (default: no supersets)");
System.out.println(" -enr : determine seed proteins enriched in up/down-regulated complexes (as in GSEA)");
System.out.println(" -sc : additional analysis based on seed combinations rather than sole complexes (as in GSEA)");
System.out.println(" -hr : additionally output human readable files with gene names and rounded numbers (default: no output)");
System.out.println(" -f : filter complexes with allosome proteins (default: no filtering)");
System.out.println();
System.out.println("[GROUPx-FOLDER] :");
System.out.println(" Standard PPIXpress/JDACO-output is read from those folders. JDACO results and major transcripts are needed.");
System.out.println();
System.out.println("[OUTPUT-FOLDER]");
System.out.println(" The outcome is written to this folder. If it does not exist, it is created.");
System.out.println();
System.exit(0);
}
/**
* Prints the version of the program
*/
public static void printVersion() {
System.out.println(version_string);
System.exit(0);
}
/**
* Parse arguments
* @param args
*/
public static void parseInput(String[] args) {
for (String arg:args) {
// help needed?
if (arg.equals("-h") || arg.equals("-help"))
printHelp();
// output version
else if (arg.equals("-version"))
printVersion();
// parse FDR
else if (arg.startsWith("-fdr="))
FDR = Double.parseDouble(arg.split("=")[1]);
// parse min_variant_fraction
else if (arg.startsWith("-mf="))
min_variant_fraction = Double.parseDouble(arg.split("=")[1]);
// add seed file
else if (arg.startsWith("-s=")) {
path_seed = arg.split("=")[1];
seed = Utilities.readEntryFile(path_seed);
if (seed == null)
System.exit(1); // error will be thrown by the utility-function
if (seed.isEmpty()) {
System.err.println("Seed file " + path_seed + " is empty.");
System.exit(1);
}
}
// parse #threads
else if (arg.startsWith("-t="))
no_threads = Math.max(Integer.parseInt(arg.split("=")[1]), 1);
// parametric?
else if (arg.equals("-nd"))
parametric = true;
// paired?
else if (arg.equals("-p"))
paired = true;
// supersets?
else if (arg.equals("-ss"))
incorporate_supersets = true;
// seed combinations?
else if (arg.equals("-sc"))
also_seedcomb_calcs = true;
// seed enrichment?
else if (arg.equals("-enr"))
also_seed_enrich = true;
// output human readable files?
else if (arg.equals("-hr"))
human_readable = true;
// filter allosome proteins?
else if (arg.equals("-f"))
filter_allosome = true;
// read groupwise input
else if (group1 == null) {
path_group1 = arg;
if (!path_group1.endsWith("/"))
path_group1 += "/";
group1 = readQuantDACOComplexes(path_group1);
}
else if (group2 == null) {
path_group2 = arg;
if (!path_group2.endsWith("/"))
path_group2 += "/";
group2 = readQuantDACOComplexes(path_group2);
}
// set output-folder
else if (output_folder == null) {
output_folder = arg;
if (!output_folder.endsWith("/"))
output_folder += "/";
}
}
// some final checks
if (group1 == null || group1.isEmpty() || group2 == null || group2.isEmpty()) {
if (group1 == null || group1.isEmpty())
System.err.println(path_group1 + " does not exist or contains no useable data.");
if (group2 == null || group2.isEmpty())
System.err.println(path_group2 + " does not exist or contains no useable data.");
System.exit(1);
}
if (group1.size() < 2 || group2.size() < 2) {
if (group1.size() < 2)
System.err.println(path_group1 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation.");
if (group2.size() < 2)
System.err.println(path_group2 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation.");
System.exit(1);
}
if (output_folder == null) {
System.err.println("Please add an output folder.");
System.exit(1);
}
// check for invalid usage of seedcomb mode
if (also_seedcomb_calcs && seed == null) {
also_seedcomb_calcs = false;
System.out.println("Analysis of seed combination variants in complexes requires a seed file, this additional analysis is skipped.");
}
if (also_seed_enrich && seed == null) {
also_seed_enrich = false;
System.out.println("Analysis of seed protein enrichment in complexes requires a seed file, this additional analysis is skipped.");
}
}
public static void main(String[] args) {
if (args.length == 1 && args[0].equals("-version"))
printVersion();
if (args.length < 3) {
printHelp();
}
// parse cmd-line and set all parameters
try {
parseInput(args);
} catch (Exception e) {
System.out.println("Something went wrong while reading the command-line, please check your input!");
System.out.println();
printHelp();
}
// preface
if (group1.size() < 5 || group2.size() < 5) {
System.out.println("Computations will run as intended, but be aware that at least five samples per group are recommended to gather meaningful results.");
}
System.out.println("Seed: " + path_seed);
System.out.println("FDR: " + FDR);
String test = "Wilcoxon rank sum test (unpaired, non-parametric)";
if (paired && parametric)
test = "paired t-test (paired, parametric)";
else if (paired)
test = "Wilcoxon signed-rank test (paired, non-parametric)";
else if (parametric)
test = "Welch's unequal variances t-test (unpaired, parametric)";
System.out.println("Statistical test: " + test);
System.out.println("Min. fraction: " + min_variant_fraction);
System.out.println("Incorporate supersets: " + (incorporate_supersets ? "yes" : "no"));
if (filter_allosome) {
System.out.print("Filtering of complexes with allosome proteins enabled. Downloading data ... ");
String db = DataQuery.getEnsemblOrganismDatabaseFromProteins(group1.values().iterator().next().getAbundantSeedProteins());
DataQuery.getAllosomeProteins(db);
System.out.println("done.");
}
System.out.println();
// computations
boolean output_to_write = false;
System.out.println("Processing " + path_group1 + " (" + group1.keySet().size() + ") vs " + path_group2 + " (" + group2.keySet().size() + ") ...");
System.out.flush();
DiffComplexDetector dcd = new DiffComplexDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome);
if (seed != null)
System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() +" (" + dcd.getSignSortedVariants(false, false).size() + " seed combination variants) significant.");
else
System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() + " significant.");
System.out.flush();
output_to_write = !dcd.getSignificanceSortedComplexes().isEmpty();
DiffSeedCombDetector dscd = null;
if (also_seedcomb_calcs) {
dscd = new DiffSeedCombDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome);
System.out.println(dscd.getVariantsRawPValues().size() + " seed combinations tested, " + dscd.getSignificanceSortedVariants().size() + " significant.");
if (!dscd.getSignificanceSortedVariants().isEmpty())
output_to_write = true;
System.out.flush();
}
SPEnrichment spe = null;
if (seed == null && also_seed_enrich) {
System.out.println("Please specify a seed protein file if seed protein enrichment should be determined.");
System.out.flush();
}
else if (seed != null && also_seed_enrich) {
System.out.println("Calculating seed protein enrichment with 10000 permutations to approximate null distribution and only considering seed proteins participating in at least 10 complexes.");
System.out.flush();
spe = dcd.calculateSPEnrichment(FDR, 10000, 10);
if (!spe.getSignificanceSortedSeedProteins().isEmpty())
output_to_write = true;
}
/*
* write file-output
*/
if (!output_to_write) {
System.out.println("Since there is nothing to report, no output is written.");
System.exit(0);
}
// check if output-folder exists, otherwise create it
File f = new File(output_folder);
if (!f.exists())
f.mkdir();
// write output files
System.out.println("Writing results ...");
dcd.writeSignSortedComplexes(output_folder + "diff_complexes.txt", false);
if (seed != null) {
dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes.txt", false);
if (also_seedcomb_calcs)
dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations.txt", false);
if (also_seed_enrich)
spe.writeSignificantSeedProteins(output_folder + "enriched_seed_proteins.txt");
}
if (human_readable) {
System.out.println("Retrieving data on gene names ...");
System.out.flush();
System.out.println("Output human readable results ...");
dcd.writeSignSortedComplexes(output_folder + "diff_complexes_hr.txt", true);
if (seed != null) {
dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes_hr.txt", true);
if (also_seedcomb_calcs)
dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations_hr.txt", true);
}
}
}
} | edeltoaster/jdaco_dev | jdaco_dev/src/standalone_tools/CompleXChange.java | Java | gpl-3.0 | 12,876 |
/*
* Geopaparazzi - Digital field mapping on Android based devices
* Copyright (C) 2016 HydroloGIS (www.hydrologis.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 eu.geopaparazzi.library.profiles.objects;
import android.os.Parcel;
import android.os.Parcelable;
import eu.geopaparazzi.library.network.download.IDownloadable;
/**
* Created by hydrologis on 19/03/18.
*/
public class ProfileOtherfiles extends ARelativePathResource implements Parcelable, IDownloadable {
public String url = "";
public String modifiedDate = "";
public long size = -1;
private String destinationPath = "";
public ProfileOtherfiles() {
}
protected ProfileOtherfiles(Parcel in) {
url = in.readString();
modifiedDate = in.readString();
size = in.readLong();
destinationPath = in.readString();
}
public static final Creator<ProfileOtherfiles> CREATOR = new Creator<ProfileOtherfiles>() {
@Override
public ProfileOtherfiles createFromParcel(Parcel in) {
return new ProfileOtherfiles(in);
}
@Override
public ProfileOtherfiles[] newArray(int size) {
return new ProfileOtherfiles[size];
}
};
@Override
public long getSize() {
return size;
}
@Override
public String getUrl() {
return url;
}
@Override
public String getDestinationPath() {
return destinationPath;
}
@Override
public void setDestinationPath(String path) {
destinationPath = path;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(url);
dest.writeString(modifiedDate);
dest.writeLong(size);
dest.writeString(destinationPath);
}
}
| geopaparazzi/geopaparazzi | geopaparazzi_library/src/main/java/eu/geopaparazzi/library/profiles/objects/ProfileOtherfiles.java | Java | gpl-3.0 | 2,473 |
package de.turnierverwaltung.control.settingsdialog;
import java.awt.Dialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.SQLException;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import de.turnierverwaltung.control.ExceptionHandler;
import de.turnierverwaltung.control.MainControl;
import de.turnierverwaltung.control.Messages;
import de.turnierverwaltung.control.PropertiesControl;
import de.turnierverwaltung.control.ratingdialog.DWZListToSQLITEControl;
import de.turnierverwaltung.control.ratingdialog.ELOListToSQLITEControl;
import de.turnierverwaltung.control.sqlite.SaveTournamentControl;
import de.turnierverwaltung.model.TournamentConstants;
import de.turnierverwaltung.view.settingsdialog.SettingsView;
import say.swing.JFontChooser;
public class ActionListenerSettingsControl {
private final MainControl mainControl;
private final SettingsControl esControl;
private JDialog dialog;
public ActionListenerSettingsControl(final MainControl mainControl, final SettingsControl esControl) {
super();
this.mainControl = mainControl;
this.esControl = esControl;
addPropertiesActionListener();
}
public void addActionListeners() {
esControl.getEigenschaftenView().getFontChooserButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JFontChooser fontChooser = esControl.getEigenschaftenView().getFontChooser();
fontChooser.setSelectedFont(mainControl.getPropertiesControl().getFont());
final int result = fontChooser.showDialog(esControl.getEigenschaftenView());
if (result == JFontChooser.OK_OPTION) {
final Font selectedFont = fontChooser.getSelectedFont();
MainControl.setUIFont(selectedFont);
mainControl.getPropertiesControl().setFont(selectedFont);
mainControl.getPropertiesControl().writeProperties();
}
}
});
esControl.getEigenschaftenView().getOkButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
mainControl.getPropertiesControl().writeSettingsDialogProperties(dialog.getBounds().x,
dialog.getBounds().y, dialog.getBounds().width, dialog.getBounds().height);
dialog.dispose();
final PropertiesControl ppC = mainControl.getPropertiesControl();
final SettingsView settingsView = esControl.getEigenschaftenView();
ppC.setTableComumnBlack(settingsView.getBlackTextField().getText());
ppC.setTableComumnWhite(settingsView.getWhiteTextField().getText());
ppC.setTableComumnMeeting(settingsView.getMeetingTextField().getText());
ppC.setTableComumnNewDWZ(settingsView.getNewDWZTextField().getText());
ppC.setTableComumnOldDWZ(settingsView.getOldDWZTextField().getText());
ppC.setTableComumnNewELO(settingsView.getNewELOTextField().getText());
ppC.setTableComumnOldELO(settingsView.getOldELOTextField().getText());
ppC.setTableComumnPlayer(settingsView.getPlayerTextField().getText());
ppC.setTableComumnPoints(settingsView.getPointsTextField().getText());
ppC.setTableComumnRanking(settingsView.getRankingTextField().getText());
ppC.setTableComumnResult(settingsView.getResultTextField().getText());
ppC.setTableComumnSonnebornBerger(settingsView.getSbbTextField().getText());
ppC.setTableComumnRound(settingsView.getRoundTextField().getText());
ppC.setSpielfrei(settingsView.getSpielfreiTextField().getText());
if (mainControl.getPlayerListControl() != null) {
mainControl.getPlayerListControl().testPlayerListForDoubles();
}
ppC.setCutForename(settingsView.getForenameLengthBox().getValue());
ppC.setCutSurname(settingsView.getSurnameLengthBox().getValue());
ppC.setWebserverPath(settingsView.getWebserverPathTextField().getText());
ppC.checkCrossTableColumnForDoubles();
ppC.checkMeetingTableColumnForDoubles();
ppC.setCSSTable(settingsView.getTableCSSTextField().getText());
ppC.writeProperties();
esControl.setTableColumns();
}
});
esControl.getEigenschaftenView().getOpenVereineCSVButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// vereine.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("CSV file", "csv", "CSV");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToVereineCVS(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS());
}
}
});
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final DWZListToSQLITEControl dwzL = new DWZListToSQLITEControl(mainControl);
dwzL.convertDWZListToSQLITE();
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
}
});
esControl.getEigenschaftenView().getOpenPlayersCSVButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// spieler.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("CSV or SQLite file", "csv", "CSV", "sqlite",
"SQLite");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToPlayersCSV(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
final String filename = file.getName();
final int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true);
}
}
}
}
});
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final ELOListToSQLITEControl eloL = new ELOListToSQLITEControl(mainControl);
eloL.convertELOListToSQLITE();
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
}
});
esControl.getEigenschaftenView().getOpenPlayersELOButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
// spieler.csv
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
final FileFilter filter = new FileNameExtensionFilter("TXT or SQLite file", "txt", "TXT", "sqlite",
"SQLite");
fc.setFileFilter(filter);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setPathToPlayersELO(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
final String filename = file.getName();
final int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true);
}
}
}
}
});
esControl.getEigenschaftenView().getOpenDefaultPathButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final File path = new File(mainControl.getPropertiesControl().getDefaultPath());
final JFileChooser fc = new JFileChooser(path);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File file = fc.getSelectedFile();
// This is where a real application would open the
// file.
mainControl.getPropertiesControl().setDefaultPath(file.getAbsolutePath());
mainControl.getPropertiesControl().writeProperties();
esControl.getEigenschaftenView()
.setOpenDefaultPathLabel(mainControl.getPropertiesControl().getDefaultPath());
}
}
});
esControl.getEigenschaftenView()
.setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS());
esControl.getEigenschaftenView()
.setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV());
esControl.getEigenschaftenView()
.setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO());
esControl.getEigenschaftenView().getGermanLanguageCheckBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
mainControl.getLanguagePropertiesControl().setLanguageToGerman();
mainControl.getPropertiesControl().writeProperties();
}
});
esControl.getEigenschaftenView().getEnglishLanguageCheckBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
mainControl.getLanguagePropertiesControl().setLanguageToEnglish();
mainControl.getPropertiesControl().writeProperties();
}
});
esControl.getEigenschaftenView().getSpielerListeAuswahlBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final int anzahlProTab = esControl.getEigenschaftenView().getSpielerListeAuswahlBox()
.getSelectedIndex();
mainControl.getPropertiesControl().setSpielerProTab(anzahlProTab);
mainControl.getPropertiesControl().writeProperties();
}
});
esControl.getEigenschaftenView().getTurnierListeAuswahlBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
final int anzahlProTab = esControl.getEigenschaftenView().getTurnierListeAuswahlBox()
.getSelectedIndex();
mainControl.getPropertiesControl().setTurniereProTab(anzahlProTab);
mainControl.getPropertiesControl().writeProperties();
}
});
String filename = mainControl.getPropertiesControl().getPathToPlayersELO();
int positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true);
}
} else {
esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false);
}
filename = mainControl.getPropertiesControl().getPathToPlayersCSV();
positionEXT = filename.lastIndexOf('.');
if (positionEXT > 0) {
final String newFile = filename.substring(positionEXT);
if (newFile.equals(".sqlite")) {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true);
}
} else {
esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false);
}
esControl.getEigenschaftenView().getResetPropertiesButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final int abfrage = beendenHinweis();
if (abfrage > 0) {
if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) {
if (mainControl.getChangedGames().isEmpty() == false) {
final SaveTournamentControl saveTournament = new SaveTournamentControl(mainControl);
try {
saveTournament.saveChangedPartien();
} catch (final SQLException e1) {
final ExceptionHandler eh = new ExceptionHandler(mainControl);
eh.fileSQLError(e1.getMessage());
}
}
}
}
mainControl.getPropertiesControl().resetProperties();
mainControl.getPropertiesControl().writeProperties();
JOptionPane.showMessageDialog(null, Messages.getString("EigenschaftenControl.29"),
Messages.getString("EigenschaftenControl.28"), JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
});
}
private void addPropertiesActionListener() {
mainControl.getNaviView().getPropertiesButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent arg0) {
mainControl.getSettingsControl().setEigenschaftenView(new SettingsView());
final SettingsView eigenschaftenView = mainControl.getSettingsControl().getEigenschaftenView();
mainControl.getSettingsControl().setItemListenerControl(
new ItemListenerSettingsControl(mainControl, mainControl.getSettingsControl()));
mainControl.getSettingsControl().getItemListenerControl().addItemListeners();
if (dialog == null) {
dialog = new JDialog();
} else {
dialog.dispose();
dialog = new JDialog();
}
// dialog.setAlwaysOnTop(true);
dialog.getContentPane().add(eigenschaftenView);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setBounds(mainControl.getPropertiesControl().getSettingsDialogX(),
mainControl.getPropertiesControl().getSettingsDialogY(),
mainControl.getPropertiesControl().getSettingsDialogWidth(),
mainControl.getPropertiesControl().getSettingsDialogHeight());
dialog.setEnabled(true);
if (mainControl.getPropertiesControl() == null) {
mainControl.setPropertiesControl(new PropertiesControl(mainControl));
}
final PropertiesControl ppC = mainControl.getPropertiesControl();
ppC.readProperties();
eigenschaftenView.getCheckBoxHeaderFooter().setSelected(ppC.getOnlyTables());
eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ());
eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(ppC.getNoFolgeDWZ());
eigenschaftenView.getCheckBoxohneELO().setSelected(ppC.getNoELO());
eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(ppC.getNoFolgeELO());
eigenschaftenView.getSpielerListeAuswahlBox().setSelectedIndex(ppC.getSpielerProTab());
eigenschaftenView.getTurnierListeAuswahlBox().setSelectedIndex(ppC.getTurniereProTab());
eigenschaftenView.getForenameLengthBox().setValue(ppC.getCutForename());
eigenschaftenView.getSurnameLengthBox().setValue(ppC.getCutSurname());
eigenschaftenView.getWebserverPathTextField().setText(ppC.getWebserverPath());
// eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ());
eigenschaftenView.getCheckBoxhtmlToClipboard().setSelected(ppC.gethtmlToClipboard());
if (eigenschaftenView.getCheckBoxohneDWZ().isSelected() == true) {
eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(true);
eigenschaftenView.getCheckBoxohneFolgeDWZ().setEnabled(false);
ppC.setNoFolgeDWZ(true);
}
if (eigenschaftenView.getCheckBoxohneELO().isSelected() == true) {
eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(true);
eigenschaftenView.getCheckBoxohneFolgeELO().setEnabled(false);
ppC.setNoFolgeELO(true);
}
eigenschaftenView.getCheckBoxPDFLinks().setSelected(ppC.getPDFLinks());
eigenschaftenView.getWebserverPathTextField().setEnabled(ppC.getPDFLinks());
if (mainControl.getPropertiesControl().getLanguage().equals("german")) { //$NON-NLS-1$
eigenschaftenView.getGermanLanguageCheckBox().setSelected(true);
eigenschaftenView.getEnglishLanguageCheckBox().setSelected(false);
mainControl.getLanguagePropertiesControl().setLanguageToGerman();
} else if (mainControl.getPropertiesControl().getLanguage().equals("english")) { //$NON-NLS-1$
eigenschaftenView.getGermanLanguageCheckBox().setSelected(false);
eigenschaftenView.getEnglishLanguageCheckBox().setSelected(true);
mainControl.getLanguagePropertiesControl().setLanguageToEnglish();
}
eigenschaftenView.setOpenDefaultPathLabel(ppC.getDefaultPath());
eigenschaftenView.getTableCSSTextField().setText(ppC.getCSSTable());
esControl.setTableColumns();
addActionListeners();
esControl.getItemListenerControl().addItemListeners();
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible(true);
}
});
}
private int beendenHinweis() {
int abfrage = 0;
if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) {
if (mainControl.getChangedGames().isEmpty() == false) {
final String hinweisText = Messages.getString("NaviController.21") //$NON-NLS-1$
+ Messages.getString("NaviController.22") //$NON-NLS-1$
+ Messages.getString("NaviController.33"); //$NON-NLS-1$
abfrage = 1;
// Custom button text
final Object[] options = { Messages.getString("NaviController.24"), //$NON-NLS-1$
Messages.getString("NaviController.25") }; //$NON-NLS-1$
abfrage = JOptionPane.showOptionDialog(mainControl, hinweisText,
Messages.getString("NaviController.26"), //$NON-NLS-1$
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
}
}
return abfrage;
}
}
| mars7105/JKLubTV | src/de/turnierverwaltung/control/settingsdialog/ActionListenerSettingsControl.java | Java | gpl-3.0 | 18,976 |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadSavedData
{
public static void StartRead() throws IOException
{
FileReader file = new FileReader("C:/Users/Public/Documents/SavedData.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
{
text += line;
line = reader.readLine();
}
reader.close();
System.out.println(text);
}
} | uSirPatrick/IPCalcGUI | IPCalc2/src/ReadSavedData.java | Java | gpl-3.0 | 556 |
/**
* Copyright 2010 David Froehlich <[email protected]>,
* Samuel Kogler <[email protected]>,
* Stephan Stiboller <[email protected]>
*
* This file is part of Codesearch.
*
* Codesearch 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.
*
* Codesearch 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 Codesearch. If not, see <http://www.gnu.org/licenses/>.
*/
package com.uwyn.jhighlight.pcj.hash;
/**
* This interface represents hash functions from char values
* to int values. The int value result is chosen to achieve
* consistence with the common
* {@link Object#hashCode() hashCode()}
* method. The interface is provided to alter the hash functions used
* by hashing data structures, like
* {@link com.uwyn.rife.pcj.map.CharKeyIntChainedHashMap CharKeyIntChainedHashMap}
* or
* {@link com.uwyn.rife.pcj.set.CharChainedHashSet CharChainedHashSet}.
*
* @see DefaultCharHashFunction
*
* @author Søren Bak
* @version 1.0 2002/29/12
* @since 1.0
*/
public interface CharHashFunction
{
/**
* Returns a hash code for a specified char value.
*
* @param v
* the value for which to return a hash code.
*
* @return a hash code for the specified value.
*/
int hash(char v);
}
| codesearch-github/codesearch | src/custom-libs/Codesearch-JHighlight/src/main/java/com/uwyn/jhighlight/pcj/hash/CharHashFunction.java | Java | gpl-3.0 | 1,832 |
package org.amse.marinaSokol.model.interfaces.object.net;
public interface IActivationFunctor {
/**
* Ôóíêöèÿ àêòèâàöèè
* @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ àêòèâàöèè
* @return âûõîä íåéðîíà
* */
double getFunction(double x);
/**
* ïðîèçâîäíàÿ ôóíêöèè àêòèâàöèè
* @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ
* @return âûõîä
* */
double getDerivation(double x);
/**
* Èìÿ ôóíêöèè àêòèâàöèè
* @return èìÿ ôóíêöèè àêòèâàöèè
* */
String getNameFunction();
}
| sokolm/NeuroNet | src/org/amse/marinaSokol/model/interfaces/object/net/IActivationFunctor.java | Java | gpl-3.0 | 558 |
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*/
package net.sareweb.emg.service;
import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil;
import com.liferay.portal.kernel.util.ReferenceRegistry;
import com.liferay.portal.service.InvokableService;
/**
* Provides the remote service utility for Draw. This utility wraps
* {@link net.sareweb.emg.service.impl.DrawServiceImpl} and is the
* primary access point for service operations in application layer code running
* on a remote server. Methods of this service are expected to have security
* checks based on the propagated JAAS credentials because this service can be
* accessed remotely.
*
* @author A.Galdos
* @see DrawService
* @see net.sareweb.emg.service.base.DrawServiceBaseImpl
* @see net.sareweb.emg.service.impl.DrawServiceImpl
* @generated
*/
public class DrawServiceUtil {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify this class directly. Add custom service methods to {@link net.sareweb.emg.service.impl.DrawServiceImpl} and rerun ServiceBuilder to regenerate this class.
*/
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
public static java.lang.String getBeanIdentifier() {
return getService().getBeanIdentifier();
}
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
public static void setBeanIdentifier(java.lang.String beanIdentifier) {
getService().setBeanIdentifier(beanIdentifier);
}
public static java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
return getService().invokeMethod(name, parameterTypes, arguments);
}
public static java.util.List<net.sareweb.emg.model.Draw> getDrawsNewerThanDate(
long date) throws com.liferay.portal.kernel.exception.SystemException {
return getService().getDrawsNewerThanDate(date);
}
public static void clearService() {
_service = null;
}
public static DrawService getService() {
if (_service == null) {
InvokableService invokableService = (InvokableService)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(),
DrawService.class.getName());
if (invokableService instanceof DrawService) {
_service = (DrawService)invokableService;
}
else {
_service = new DrawServiceClp(invokableService);
}
ReferenceRegistry.registerReference(DrawServiceUtil.class,
"_service");
}
return _service;
}
/**
* @deprecated As of 6.2.0
*/
public void setService(DrawService service) {
}
private static DrawService _service;
} | aritzg/EuroMillionGame-portlet | docroot/WEB-INF/service/net/sareweb/emg/service/DrawServiceUtil.java | Java | gpl-3.0 | 3,192 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.optimizer;
import org.mozilla.javascript.ArrowFunction;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.ConsString;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ES6Generator;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.NativeFunction;
import org.mozilla.javascript.NativeGenerator;
import org.mozilla.javascript.NativeIterator;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
/**
* <p>OptRuntime class.</p>
*
*
*
*/
public final class OptRuntime extends ScriptRuntime
{
/** Constant <code>oneObj</code> */
public static final Double oneObj = Double.valueOf(1.0);
/** Constant <code>minusOneObj</code> */
public static final Double minusOneObj = Double.valueOf(-1.0);
/**
* Implement ....() call shrinking optimizer code.
*
* @param fun a {@link org.mozilla.javascript.Callable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object call0(Callable fun, Scriptable thisObj,
Context cx, Scriptable scope)
{
return fun.call(cx, scope, thisObj, ScriptRuntime.emptyArgs);
}
/**
* Implement ....(arg) call shrinking optimizer code.
*
* @param fun a {@link org.mozilla.javascript.Callable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @param arg0 a {@link java.lang.Object} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object call1(Callable fun, Scriptable thisObj, Object arg0,
Context cx, Scriptable scope)
{
return fun.call(cx, scope, thisObj, new Object[] { arg0 } );
}
/**
* Implement ....(arg0, arg1) call shrinking optimizer code.
*
* @param fun a {@link org.mozilla.javascript.Callable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @param arg0 a {@link java.lang.Object} object.
* @param arg1 a {@link java.lang.Object} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object call2(Callable fun, Scriptable thisObj,
Object arg0, Object arg1,
Context cx, Scriptable scope)
{
return fun.call(cx, scope, thisObj, new Object[] { arg0, arg1 });
}
/**
* Implement ....(arg0, arg1, ...) call shrinking optimizer code.
*
* @param fun a {@link org.mozilla.javascript.Callable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @param args an array of {@link java.lang.Object} objects.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object callN(Callable fun, Scriptable thisObj,
Object[] args,
Context cx, Scriptable scope)
{
return fun.call(cx, scope, thisObj, args);
}
/**
* Implement name(args) call shrinking optimizer code.
*
* @param args an array of {@link java.lang.Object} objects.
* @param name a {@link java.lang.String} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object callName(Object[] args, String name,
Context cx, Scriptable scope)
{
Callable f = getNameFunctionAndThis(name, cx, scope);
Scriptable thisObj = lastStoredScriptable(cx);
return f.call(cx, scope, thisObj, args);
}
/**
* Implement name() call shrinking optimizer code.
*
* @param name a {@link java.lang.String} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object callName0(String name,
Context cx, Scriptable scope)
{
Callable f = getNameFunctionAndThis(name, cx, scope);
Scriptable thisObj = lastStoredScriptable(cx);
return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs);
}
/**
* Implement x.property() call shrinking optimizer code.
*
* @param value a {@link java.lang.Object} object.
* @param property a {@link java.lang.String} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link java.lang.Object} object.
*/
public static Object callProp0(Object value, String property,
Context cx, Scriptable scope)
{
Callable f = getPropFunctionAndThis(value, property, cx, scope);
Scriptable thisObj = lastStoredScriptable(cx);
return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs);
}
/**
* <p>add.</p>
*
* @param val1 a {@link java.lang.Object} object.
* @param val2 a double.
* @return a {@link java.lang.Object} object.
*/
public static Object add(Object val1, double val2)
{
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(null);
if (!(val1 instanceof CharSequence))
return wrapDouble(toNumber(val1) + val2);
return new ConsString((CharSequence)val1, toString(val2));
}
/** {@inheritDoc} */
public static Object add(double val1, Object val2)
{
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(null);
if (!(val2 instanceof CharSequence))
return wrapDouble(toNumber(val2) + val1);
return new ConsString(toString(val1), (CharSequence)val2);
}
/** {@inheritDoc} */
@Deprecated
public static Object elemIncrDecr(Object obj, double index,
Context cx, int incrDecrMask)
{
return elemIncrDecr(obj, index, cx, getTopCallScope(cx), incrDecrMask);
}
/** {@inheritDoc} */
public static Object elemIncrDecr(Object obj, double index,
Context cx, Scriptable scope,
int incrDecrMask)
{
return ScriptRuntime.elemIncrDecr(obj, Double.valueOf(index), cx, scope,
incrDecrMask);
}
/**
* <p>padStart.</p>
*
* @param currentArgs an array of {@link java.lang.Object} objects.
* @param count a int.
* @return an array of {@link java.lang.Object} objects.
*/
public static Object[] padStart(Object[] currentArgs, int count) {
Object[] result = new Object[currentArgs.length + count];
System.arraycopy(currentArgs, 0, result, count, currentArgs.length);
return result;
}
/**
* <p>initFunction.</p>
*
* @param fn a {@link org.mozilla.javascript.NativeFunction} object.
* @param functionType a int.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
*/
public static void initFunction(NativeFunction fn, int functionType,
Scriptable scope, Context cx)
{
ScriptRuntime.initFunction(cx, scope, fn, functionType, false);
}
/**
* <p>bindThis.</p>
*
* @param fn a {@link org.mozilla.javascript.NativeFunction} object.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link org.mozilla.javascript.Function} object.
*/
public static Function bindThis(NativeFunction fn, Context cx, Scriptable scope, Scriptable thisObj)
{
return new ArrowFunction(cx, scope, fn, thisObj);
}
/** {@inheritDoc} */
public static Object callSpecial(Context cx, Callable fun,
Scriptable thisObj, Object[] args,
Scriptable scope,
Scriptable callerThis, int callType,
String fileName, int lineNumber)
{
return ScriptRuntime.callSpecial(cx, fun, thisObj, args, scope,
callerThis, callType,
fileName, lineNumber);
}
/**
* <p>newObjectSpecial.</p>
*
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param fun a {@link java.lang.Object} object.
* @param args an array of {@link java.lang.Object} objects.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @param callerThis a {@link org.mozilla.javascript.Scriptable} object.
* @param callType a int.
* @return a {@link java.lang.Object} object.
*/
public static Object newObjectSpecial(Context cx, Object fun,
Object[] args, Scriptable scope,
Scriptable callerThis, int callType)
{
return ScriptRuntime.newSpecial(cx, fun, args, scope, callType);
}
/**
* <p>wrapDouble.</p>
*
* @param num a double.
* @return a {@link java.lang.Double} object.
*/
public static Double wrapDouble(double num)
{
if (num == 0.0) {
if (1 / num > 0) {
// +0.0
return zeroObj;
}
} else if (num == 1.0) {
return oneObj;
} else if (num == -1.0) {
return minusOneObj;
} else if (Double.isNaN(num)) {
return NaNobj;
}
return Double.valueOf(num);
}
static String encodeIntArray(int[] array)
{
// XXX: this extremely inefficient for small integers
if (array == null) { return null; }
int n = array.length;
char[] buffer = new char[1 + n * 2];
buffer[0] = 1;
for (int i = 0; i != n; ++i) {
int value = array[i];
int shift = 1 + i * 2;
buffer[shift] = (char)(value >>> 16);
buffer[shift + 1] = (char)value;
}
return new String(buffer);
}
private static int[] decodeIntArray(String str, int arraySize)
{
// XXX: this extremely inefficient for small integers
if (arraySize == 0) {
if (str != null) throw new IllegalArgumentException();
return null;
}
if (str.length() != 1 + arraySize * 2 && str.charAt(0) != 1) {
throw new IllegalArgumentException();
}
int[] array = new int[arraySize];
for (int i = 0; i != arraySize; ++i) {
int shift = 1 + i * 2;
array[i] = (str.charAt(shift) << 16) | str.charAt(shift + 1);
}
return array;
}
/**
* <p>newArrayLiteral.</p>
*
* @param objects an array of {@link java.lang.Object} objects.
* @param encodedInts a {@link java.lang.String} object.
* @param skipCount a int.
* @param cx a {@link org.mozilla.javascript.Context} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @return a {@link org.mozilla.javascript.Scriptable} object.
*/
public static Scriptable newArrayLiteral(Object[] objects,
String encodedInts,
int skipCount,
Context cx,
Scriptable scope)
{
int[] skipIndexces = decodeIntArray(encodedInts, skipCount);
return newArrayLiteral(objects, skipIndexces, cx, scope);
}
/**
* <p>main.</p>
*
* @param script a {@link org.mozilla.javascript.Script} object.
* @param args an array of {@link java.lang.String} objects.
*/
public static void main(final Script script, final String[] args)
{
ContextFactory.getGlobal().call(cx -> {
ScriptableObject global = getGlobal(cx);
// get the command line arguments and define "arguments"
// array in the top-level object
Object[] argsCopy = new Object[args.length];
System.arraycopy(args, 0, argsCopy, 0, args.length);
Scriptable argsObj = cx.newArray(global, argsCopy);
global.defineProperty("arguments", argsObj,
ScriptableObject.DONTENUM);
script.exec(cx, global);
return null;
});
}
/**
* <p>throwStopIteration.</p>
*
* @param scope a {@link java.lang.Object} object.
* @param genState a {@link java.lang.Object} object.
*/
public static void throwStopIteration(Object scope, Object genState) {
Object value = getGeneratorReturnValue(genState);
Object si =
(value == Undefined.instance) ?
NativeIterator.getStopIterationObject((Scriptable)scope) :
new NativeIterator.StopIteration(value);
throw new JavaScriptException(si, "", 0);
}
/**
* <p>createNativeGenerator.</p>
*
* @param funObj a {@link org.mozilla.javascript.NativeFunction} object.
* @param scope a {@link org.mozilla.javascript.Scriptable} object.
* @param thisObj a {@link org.mozilla.javascript.Scriptable} object.
* @param maxLocals a int.
* @param maxStack a int.
* @return a {@link org.mozilla.javascript.Scriptable} object.
*/
public static Scriptable createNativeGenerator(NativeFunction funObj,
Scriptable scope,
Scriptable thisObj,
int maxLocals,
int maxStack)
{
GeneratorState gs = new GeneratorState(thisObj, maxLocals, maxStack);
if (Context.getCurrentContext().getLanguageVersion() >= Context.VERSION_ES6) {
return new ES6Generator(scope, funObj, gs);
} else {
return new NativeGenerator(scope, funObj, gs);
}
}
/**
* <p>getGeneratorStackState.</p>
*
* @param obj a {@link java.lang.Object} object.
* @return an array of {@link java.lang.Object} objects.
*/
public static Object[] getGeneratorStackState(Object obj) {
GeneratorState rgs = (GeneratorState) obj;
if (rgs.stackState == null)
rgs.stackState = new Object[rgs.maxStack];
return rgs.stackState;
}
/**
* <p>getGeneratorLocalsState.</p>
*
* @param obj a {@link java.lang.Object} object.
* @return an array of {@link java.lang.Object} objects.
*/
public static Object[] getGeneratorLocalsState(Object obj) {
GeneratorState rgs = (GeneratorState) obj;
if (rgs.localsState == null)
rgs.localsState = new Object[rgs.maxLocals];
return rgs.localsState;
}
/**
* <p>setGeneratorReturnValue.</p>
*
* @param obj a {@link java.lang.Object} object.
* @param val a {@link java.lang.Object} object.
*/
public static void setGeneratorReturnValue(Object obj, Object val) {
GeneratorState rgs = (GeneratorState) obj;
rgs.returnValue = val;
}
/**
* <p>getGeneratorReturnValue.</p>
*
* @param obj a {@link java.lang.Object} object.
* @return a {@link java.lang.Object} object.
*/
public static Object getGeneratorReturnValue(Object obj) {
GeneratorState rgs = (GeneratorState) obj;
return (rgs.returnValue == null ? Undefined.instance : rgs.returnValue);
}
public static class GeneratorState {
static final String CLASS_NAME =
"org/mozilla/javascript/optimizer/OptRuntime$GeneratorState";
@SuppressWarnings("unused")
public int resumptionPoint;
static final String resumptionPoint_NAME = "resumptionPoint";
static final String resumptionPoint_TYPE = "I";
@SuppressWarnings("unused")
public Scriptable thisObj;
static final String thisObj_NAME = "thisObj";
static final String thisObj_TYPE =
"Lorg/mozilla/javascript/Scriptable;";
Object[] stackState;
Object[] localsState;
int maxLocals;
int maxStack;
Object returnValue;
GeneratorState(Scriptable thisObj, int maxLocals, int maxStack) {
this.thisObj = thisObj;
this.maxLocals = maxLocals;
this.maxStack = maxStack;
}
}
}
| oswetto/LoboEvolution | LoboParser/src/main/java/org/mozilla/javascript/optimizer/OptRuntime.java | Java | gpl-3.0 | 18,041 |
/*******************************************************************************
* Copyright 2010 Olaf Sebelin
*
* This file is part of Verdandi.
*
* Verdandi 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.
*
* Verdandi 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 Verdandi. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package verdandi;
/**
*
* @
*/
public class InvalidIntervalException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public InvalidIntervalException() {
super();
}
/**
* @param message
*/
public InvalidIntervalException(String message) {
super(message);
}
}
| osebelin/verdandi | src/main/java/verdandi/InvalidIntervalException.java | Java | gpl-3.0 | 1,220 |
/*
* SPDX-License-Identifier: GPL-3.0
*
*
* (J)ava (M)iscellaneous (U)tilities (L)ibrary
*
* JMUL is a central repository for utilities which are used in my
* other public and private repositories.
*
* Copyright (C) 2016 Kristian Kutin
*
* 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/>.
*
* e-mail: [email protected]
*/
/*
* This section contains meta informations.
*
* $Id$
*/
package jmul.web.page;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import jmul.io.NestedStreams;
import jmul.io.NestedStreamsImpl;
import jmul.misc.exceptions.MultipleCausesException;
import static jmul.string.Constants.FILE_SEPARATOR;
import static jmul.string.Constants.SLASH;
/**
* This class represents an entity which loads web content from the file
* system.
*
* @author Kristian Kutin
*/
public class PageLoader {
/**
* The base directory of the web content.
*/
private final File baseDirectory;
/**
* The file with the page content.
*/
private final File file;
/**
* Creates a new instance of a content loader.
*
* @param aBaseDirectory
* a base directory
* @param aFile
* a file (i.e. file path)
*/
public PageLoader(File aBaseDirectory, File aFile) {
baseDirectory = aBaseDirectory;
file = aFile;
}
/**
* Loads the web content.
*
* @return web content
*/
public PublishedPage loadContent() {
String path = getPath();
NestedStreams nestedStreams = null;
try {
nestedStreams = openStreams(file);
} catch (FileNotFoundException e) {
String message = "Unable to load the web content (\"" + file + "\")!";
throw new PageLoaderException(message, e);
}
byte[] content = null;
try {
content = loadContent(nestedStreams);
} catch (IOException e) {
Throwable followupError = null;
try {
nestedStreams.close();
} catch (IOException f) {
followupError = f;
}
String message = "Error while reading from file (\"" + file + "\")!";
if (followupError != null) {
throw new PageLoaderException(message, new MultipleCausesException(e, followupError));
} else {
throw new PageLoaderException(message, followupError);
}
}
return new PublishedPage(path, content);
}
/**
* Determines the web path for this file relative to the base directory.
*
* @param aBaseDirectory
* @param aFile
*
* @return a path
*
* @throws IOException
* is thrown if the specified directory or file cannot be resolved to
* absolute paths
*/
private static String determinePath(File aBaseDirectory, File aFile) throws IOException {
String directory = aBaseDirectory.getCanonicalPath();
String fileName = aFile.getCanonicalPath();
String path = fileName.replace(directory, "");
path = path.replace(FILE_SEPARATOR, SLASH);
return path;
}
/**
* Opens a stream to read from the specified file.
*
* @param aFile
*
* @return an input stream
*
* @throws FileNotFoundException
* is thrown if the specified file doesn't exist
*/
private static NestedStreams openStreams(File aFile) throws FileNotFoundException {
InputStream reader = new FileInputStream(aFile);
return new NestedStreamsImpl(reader);
}
/**
* Tries to load the web content from the specified file.
*
* @param someNestedStreams
*
* @return some web content
*
* @throws IOException
* is thrown if an error occurred while reading from the file
*/
private static byte[] loadContent(NestedStreams someNestedStreams) throws IOException {
InputStream reader = (InputStream) someNestedStreams.getOuterStream();
List<Byte> buffer = new ArrayList<>();
while (true) {
int next = reader.read();
if (next == -1) {
break;
}
buffer.add((byte) next);
}
int size = buffer.size();
byte[] bytes = new byte[size];
for (int a = 0; a < size; a++) {
Byte b = buffer.get(a);
bytes[a] = b;
}
return bytes;
}
/**
* Returns the path of the web page.
*
* @return a path
*/
public String getPath() {
String path = null;
try {
path = determinePath(baseDirectory, file);
} catch (IOException e) {
String message = "Unable to resolve paths (\"" + baseDirectory + "\" & \"" + file + "\")!";
throw new PageLoaderException(message, e);
}
return path;
}
}
| gammalgris/jmul | Utilities/Web/src/jmul/web/page/PageLoader.java | Java | gpl-3.0 | 5,731 |
/*******************************************************************************
* Australian National University Data Commons
* Copyright (C) 2013 The Australian National University
*
* This file is part of Australian National University Data Commons.
*
* Australian National University Data Commons 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 au.edu.anu.datacommons.doi;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.StringWriter;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.datacite.schema.kernel_4.Resource;
import org.datacite.schema.kernel_4.Resource.Creators;
import org.datacite.schema.kernel_4.Resource.Creators.Creator;
import org.datacite.schema.kernel_4.Resource.Creators.Creator.CreatorName;
import org.datacite.schema.kernel_4.Resource.Identifier;
import org.datacite.schema.kernel_4.Resource.Titles;
import org.datacite.schema.kernel_4.Resource.Titles.Title;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.test.framework.JerseyTest;
public class DoiClientTest extends JerseyTest
{
private static final Logger LOGGER = LoggerFactory.getLogger(DoiClientTest.class);
private DoiClient doiClient;
private String sampleDoi = "10.5072/13/50639BFE25F18";
private static JAXBContext context;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
public DoiClientTest()
{
super("au.edu.anu.datacommons.doi");
// LOGGER.trace("In Constructor");
// WebResource webResource = resource();
// DoiConfig doiConfig = new DoiConfigImpl(webResource.getURI().toString(), appId);
// doiClient = new DoiClient(doiConfig);
doiClient = new DoiClient();
}
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
context = JAXBContext.newInstance(Resource.class);
}
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
@Before
public void setUp() throws Exception
{
super.setUp();
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://datacite.org/schema/kernel-2.2 http://schema.datacite.org/meta/kernel-2.2/metadata.xsd");
}
@After
public void tearDown() throws Exception
{
super.tearDown();
}
@Ignore
public void testMint()
{
try
{
doiClient.mint("https://datacommons.anu.edu.au:8443/DataCommons/item/anudc:3320", generateSampleResource());
String respStr = doiClient.getDoiResponseAsString();
LOGGER.trace(respStr);
}
catch (Exception e)
{
failOnException(e);
}
}
@Ignore
public void testUpdate()
{
try
{
Resource res = new Resource();
Creators creators = new Creators();
Creator creator = new Creator();
CreatorName creatorName = new CreatorName();
creatorName.setValue("Creator 1");
creator.setCreatorName(creatorName);
creators.getCreator().add(creator);
res.setCreators(creators);
Titles titles = new Titles();
Title title = new Title();
title.setValue("Title 1");
titles.getTitle().add(title);
res.setTitles(titles);
res.setPublisher("Publisher 1");
res.setPublicationYear("1987");
Identifier id = new Identifier();
id.setValue(sampleDoi);
id.setIdentifierType("DOI");
res.setIdentifier(id);
doiClient.update(sampleDoi, null, res);
Resource newRes = doiClient.getMetadata(sampleDoi);
String resAsStr = getResourceAsString(newRes);
LOGGER.trace(resAsStr);
}
catch (Exception e)
{
failOnException(e);
}
}
@Ignore
public void testDeactivate()
{
try
{
doiClient.deactivate(sampleDoi);
assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "deactivate.xml/") != -1);
// assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:app_id=TEST" + appId) != -1);
assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1);
}
catch (Exception e)
{
failOnException(e);
}
}
@Ignore
public void testActivate()
{
try
{
doiClient.activate(sampleDoi);
assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "activate.xml/") != -1);
// assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:app_id=TEST" + appId) != -1);
assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1);
}
catch (Exception e)
{
failOnException(e);
}
}
@Test
public void testGetDoiMetaData()
{
try
{
Resource res = doiClient.getMetadata(sampleDoi);
StringWriter strW = new StringWriter();
marshaller.marshal(res, strW);
// assertTrue(doiClient.getDoiResponseAsString().indexOf("AbsolutePath:" + resource().getURI().toString() + "xml.xml/") != -1);
// assertTrue(doiClient.getDoiResponseAsString().indexOf("QueryParam:doi=" + sampleDoi) != -1);
}
catch (Exception e)
{
failOnException(e);
}
}
private Resource generateSampleResource()
{
Resource metadata = new Resource();
Titles titles = new Titles();
Title title1 = new Title();
title1.setValue("Some title without a type");
titles.getTitle().add(title1);
metadata.setTitles(titles);
Creators creators = new Creators();
metadata.setCreators(creators);
Creator creator = new Creator();
CreatorName creatorName = new CreatorName();
creatorName.setValue("Smith, John");
creator.setCreatorName(creatorName);
metadata.getCreators().getCreator().add(creator);
metadata.setPublisher("Some random publisher");
metadata.setPublicationYear("2010");
return metadata;
}
private String getResourceAsString(Resource res) throws JAXBException
{
StringWriter strW = new StringWriter();
marshaller.marshal(res, strW);
return strW.toString();
}
private void failOnException(Throwable e)
{
LOGGER.error(e.getMessage(), e);
fail(e.getMessage());
}
}
| anu-doi/anudc | DataCommons/src/test/java/au/edu/anu/datacommons/doi/DoiClientTest.java | Java | gpl-3.0 | 6,942 |
package co.edu.udea.ingenieriaweb.admitravel.bl;
import java.util.List;
import co.edu.udea.ingenieriaweb.admitravel.dto.PaqueteDeViaje;
import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWBLException;
import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWDaoException;
/**
* Clase DestinoBL define la funcionalidad a implementar en el DestinoBLImp
*
* @author Yeferson Marín
*
*/
public interface PaqueteDeViajeBL {
/**
* Método que permite almacenar un paquete de viaje en el sistema
* @param idPaquete tipo de identificación del paquete de viaje
* @param destinos nombre del destinos (Este parametro no debería ir)
* @param transporte transporte en el que se hace el viaje
* @param alimentacion alimentación que lleva el viaje
* @param duracionViaje duración del viaje tomado
* @throws IWDaoException ocurre cuando hay un error en la base de datos
* @throws IWBLException ocurre cuando hay un error de lógica del negocio en los datos a guardar
*/
public void guardar(String idPaquete, String destinos, String transporte, String alimentacion,
String duracionViaje) throws IWDaoException, IWBLException;
public void actualizar(PaqueteDeViaje paqueteDeViaje, String idPaquete, String destinos,
String transporte, String alimentacion, String duracionViaje)throws IWDaoException, IWBLException;
PaqueteDeViaje obtener(String idPaquete) throws IWDaoException, IWBLException;
}
| yefry/AdmiTravelSpring | AdmiTravelSpring/src/co/edu/udea/ingenieriaweb/admitravel/bl/PaqueteDeViajeBL.java | Java | gpl-3.0 | 1,439 |
package com.github.wglanzer.redmine;
import java.util.function.Consumer;
/**
* Interface that is able to create background-tasks
*
* @author w.glanzer, 11.12.2016.
*/
public interface IRTaskCreator
{
/**
* Executes a given task in background
*
* @param pTask Task that should be done in background
* @return the given task
*/
<T extends ITask> T executeInBackground(T pTask);
/**
* Progress, that can be executed
*/
interface ITask extends Consumer<IProgressIndicator>
{
/**
* @return the name of the current progress
*/
String getName();
}
/**
* Indicator-Interface to call back to UI
*/
interface IProgressIndicator
{
/**
* Adds the given number to percentage
*
* @param pPercentage 0-100
*/
void addPercentage(double pPercentage);
}
}
| wglanzer/redmine-intellij-plugin | core/src/main/java/com/github/wglanzer/redmine/IRTaskCreator.java | Java | gpl-3.0 | 841 |
/**
*
*/
package qa.AnswerFormation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import qa.IQuestion;
import qa.Utility;
/**
* @author Deepak
*
*/
public class AnswerGenerator implements IAnswerGenerator {
/**
*
* @param processedQuestionsQueue
*/
public AnswerGenerator(Queue<IQuestion> processedQuestionsQueue, List<IQuestion> processedQuestions) {
this.processedQuestionsQueue = processedQuestionsQueue;
this.processedQuestions = processedQuestions;
}
/**
*
*/
@Override
public void run() {
while(!processedQuestionsQueue.isEmpty() || !Utility.IsPassageRetrivalDone) {
IQuestion question = processedQuestionsQueue.poll();
if(question == null) continue;
HashSet<String> answers = new HashSet<String>();
for(String passage : question.getRelevantPassages()) {
List<String> output = new ArrayList<String>();
String passageWithoutKeywords = null;
String nerTaggedPassage = Utility.getNERTagging(passage);
String posTaggedPassage = Utility.getPOSTagging(passage);
output.addAll(getDataFromOutput(nerTaggedPassage, question.getAnswerTypes()));
output.addAll(getDataFromOutput(posTaggedPassage, question.getAnswerTypes()));
for(String answer : output) {
if(!question.getQuestion().toLowerCase().contains(answer.toLowerCase()) && !answers.contains(answer)) {
answers.add(answer);
passageWithoutKeywords = Utility.removeKeywords(answer, question.getKeywords());
question.addAnswer(passageWithoutKeywords);
}
}
}
for(String passage : question.getRelevantPassages()) {
List<String> output = new ArrayList<String>();
String passageWithoutKeywords = null;
if(answers.size() >= 10) break;
try{
output.addAll(Utility.getNounPhrases(passage, false));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
for(String answer : output) {
if(!question.getQuestion().toLowerCase().contains(answer.toLowerCase()) && !answers.contains(answer)) {
answers.add(answer);
passageWithoutKeywords = Utility.removeKeywords(answer, question.getKeywords());
question.addAnswer(passageWithoutKeywords);
}
}
}
// for(String answer : answers) {
// boolean flag = true;
// for(String answer1 : answers) {
// if(!answer.equals(answer1)) {
// if(answer1.toLowerCase().contains(answer.toLowerCase())) {
// flag = false;
// break;
// }
// }
// }
// if(flag) {
// question.addAnswer(answer);
// }
// }
this.processedQuestions.add(question);
}
AnswerWriter writer = new AnswerWriter("answer.txt");
writer.writeAnswers(processedQuestions);
}
/**
*
* @param output
* @param tagName
* @return
*/
private List<String> getDataFromOutput(String output, String tagName) {
List<String> answers = new ArrayList<String>();
StringBuilder temp = new StringBuilder();
String[] outputArray = output.split("[/_\\s]");
String[] tags = tagName.split("\\|");
for(String tag : tags) {
if(tag == null || tag.equals("")) continue;
String[] tagsArray = tag.split(":");
for(int arrayIndex = 1; arrayIndex < outputArray.length; arrayIndex+=2) {
if(outputArray[arrayIndex].trim().equals(tagsArray[1].trim())) {
temp.append(outputArray[arrayIndex - 1] + " ");
} else {
if(!temp.toString().equals("")) {
answers.add(temp.toString().trim());
}
temp = new StringBuilder();
}
}
if(!temp.toString().equals("") ) {
answers.add(temp.toString().trim());
}
}
return answers;
}
/**
*
*/
private Queue<IQuestion> processedQuestionsQueue;
private List<IQuestion> processedQuestions;
}
| ddeeps2610/NLP_PA2_QA | src/qa/AnswerFormation/AnswerGenerator.java | Java | gpl-3.0 | 3,904 |
package com.wisecityllc.cookedapp.fragments;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.parse.ParseQueryAdapter;
import com.segment.analytics.Analytics;
import com.wisecityllc.cookedapp.R;
import com.wisecityllc.cookedapp.adapters.AlertWallAdapter;
import com.wisecityllc.cookedapp.parseClasses.Message;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AlertsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link AlertsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AlertsFragment extends Fragment {
public static final String ALERTS_SCREEN = "AlertsScreen";
private boolean mHasMadeInitialLoad = false;
private AlertWallAdapter mAlertsAdapter;
private ListView mAlertsListView;
private TextView mNoAlertsTextView;
private ProgressBar mLoadingIndicator;
public static AlertsFragment newInstance() {
AlertsFragment fragment = new AlertsFragment();
return fragment;
}
public AlertsFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_alerts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLoadingIndicator = (ProgressBar) view.findViewById(R.id.alerts_fragment_loading_indicator);
mAlertsAdapter = new AlertWallAdapter(this.getActivity());
mAlertsAdapter.addOnQueryLoadListener(new ParseQueryAdapter.OnQueryLoadListener<Message>() {
@Override
public void onLoading() {
mAlertsListView.setVisibility(View.GONE);
mLoadingIndicator.setVisibility(View.VISIBLE);
mNoAlertsTextView.setVisibility(View.GONE);
}
@Override
public void onLoaded(List<Message> list, Exception e) {
mLoadingIndicator.setVisibility(View.GONE);
mNoAlertsTextView.setVisibility(e != null || list == null || list.isEmpty() ? View.VISIBLE : View.GONE);
mAlertsListView.setVisibility(View.VISIBLE);
}
});
if(mAlertsListView == null){
mAlertsListView = (ListView)view.findViewById(R.id.alerts_list_view);
}
mNoAlertsTextView = (TextView) view.findViewById(R.id.alerts_fragment_no_messages_text_view);
// mAlertsListView.setOnItemClickListener(this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
// Has become visible
Analytics.with(getActivity()).screen(null, ALERTS_SCREEN);
// Delay our loading until we become visible
if(mHasMadeInitialLoad == false && mAlertsAdapter != null) {
mAlertsListView.setAdapter(mAlertsAdapter);
mHasMadeInitialLoad = true;
}
}
}
}
| dexterlohnes/cooked-android | app/src/main/java/com/wisecityllc/cookedapp/fragments/AlertsFragment.java | Java | gpl-3.0 | 4,689 |
package org.aslab.om.metacontrol.action;
import java.util.HashSet;
import java.util.Set;
import org.aslab.om.ecl.action.Action;
import org.aslab.om.ecl.action.ActionFeedback;
import org.aslab.om.ecl.action.ActionResult;
import org.aslab.om.metacontrol.value.CompGoalAtomTracker;
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @author chcorbato
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public class FunctionalAction extends Action {
/**
* <!-- begin-UML-doc -->
* number of ever issued action_list (this way a new number is assigned to everyone upon creation)
* <!-- end-UML-doc -->
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
private static short num_of_actions = 0;
@Override
protected short addAction(){
return num_of_actions++;
}
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public Set<CompGoalAtomTracker> atoms = new HashSet<CompGoalAtomTracker>();
/**
* <!-- begin-UML-doc -->
* <!-- end-UML-doc -->
* @param a
* @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)"
*/
public FunctionalAction(Set<CompGoalAtomTracker> a) {
// begin-user-code
atoms = a;
// end-user-code
}
@Override
public ActionResult processResult(ActionFeedback feedback) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean timeOut() {
// TODO Auto-generated method stub
return false;
}
}
| aslab/rct | higgs/branches/ros-fuerte/OM/versions/NamePerception_OM/OMJava/src/org/aslab/om/metacontrol/action/FunctionalAction.java | Java | gpl-3.0 | 1,624 |
package net.ballmerlabs.scatterbrain.network.wifidirect;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import net.ballmerlabs.scatterbrain.network.GlobalNet;
/**
* Created by user on 5/29/16.
*/
@SuppressWarnings({"FieldCanBeLocal", "DefaultFileTemplate"})
class WifiDirectLooper extends Thread {
private Handler handler;
@SuppressWarnings("unused")
private final GlobalNet globnet;
public WifiDirectLooper(GlobalNet globnet) {
super();
this.globnet = globnet;
handler = new Handler();
}
public Handler getHandler() {
return this.handler;
}
@Override
public void run() {
Looper.prepare();
handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return true;
}
});
Looper.loop();
}
}
| gnu3ra/Scatterbrain | app/src/main/java/net/ballmerlabs/scatterbrain/network/wifidirect/WifiDirectLooper.java | Java | gpl-3.0 | 938 |
package org.jlinda.nest.gpf;
import com.bc.ceres.core.ProgressMonitor;
import org.apache.commons.math3.util.FastMath;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.MetadataElement;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.framework.gpf.Operator;
import org.esa.beam.framework.gpf.OperatorException;
import org.esa.beam.framework.gpf.OperatorSpi;
import org.esa.beam.framework.gpf.Tile;
import org.esa.beam.framework.gpf.annotations.OperatorMetadata;
import org.esa.beam.framework.gpf.annotations.Parameter;
import org.esa.beam.framework.gpf.annotations.SourceProduct;
import org.esa.beam.framework.gpf.annotations.TargetProduct;
import org.esa.beam.util.ProductUtils;
import org.esa.snap.datamodel.AbstractMetadata;
import org.esa.snap.datamodel.Unit;
import org.esa.snap.gpf.OperatorUtils;
import org.esa.snap.gpf.ReaderUtils;
import org.jblas.ComplexDoubleMatrix;
import org.jblas.DoubleMatrix;
import org.jblas.MatrixFunctions;
import org.jblas.Solve;
import org.jlinda.core.Orbit;
import org.jlinda.core.SLCImage;
import org.jlinda.core.Window;
import org.jlinda.core.utils.MathUtils;
import org.jlinda.core.utils.PolyUtils;
import org.jlinda.core.utils.SarUtils;
import org.jlinda.nest.utils.BandUtilsDoris;
import org.jlinda.nest.utils.CplxContainer;
import org.jlinda.nest.utils.ProductContainer;
import org.jlinda.nest.utils.TileUtilsDoris;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
@OperatorMetadata(alias = "Interferogram",
category = "SAR Processing/Interferometric/Products",
authors = "Petar Marinkovic",
copyright = "Copyright (C) 2013 by PPO.labs",
description = "Compute interferograms from stack of coregistered images : JBLAS implementation")
public class InterferogramOp extends Operator {
@SourceProduct
private Product sourceProduct;
@TargetProduct
private Product targetProduct;
@Parameter(valueSet = {"1", "2", "3", "4", "5", "6", "7", "8"},
description = "Order of 'Flat earth phase' polynomial",
defaultValue = "5",
label = "Degree of \"Flat Earth\" polynomial")
private int srpPolynomialDegree = 5;
@Parameter(valueSet = {"301", "401", "501", "601", "701", "801", "901", "1001"},
description = "Number of points for the 'flat earth phase' polynomial estimation",
defaultValue = "501",
label = "Number of 'Flat earth' estimation points")
private int srpNumberPoints = 501;
@Parameter(valueSet = {"1", "2", "3", "4", "5"},
description = "Degree of orbit (polynomial) interpolator",
defaultValue = "3",
label = "Orbit interpolation degree")
private int orbitDegree = 3;
@Parameter(defaultValue="false", label="Do NOT subtract flat-earth phase from interferogram.")
private boolean doNotSubtract = false;
// flat_earth_polynomial container
private HashMap<String, DoubleMatrix> flatEarthPolyMap = new HashMap<String, DoubleMatrix>();
// source
private HashMap<Integer, CplxContainer> masterMap = new HashMap<Integer, CplxContainer>();
private HashMap<Integer, CplxContainer> slaveMap = new HashMap<Integer, CplxContainer>();
// target
private HashMap<String, ProductContainer> targetMap = new HashMap<String, ProductContainer>();
// operator tags
private static final boolean CREATE_VIRTUAL_BAND = true;
private String productName;
public String productTag;
private int sourceImageWidth;
private int sourceImageHeight;
/**
* Initializes this operator and sets the one and only target product.
* <p>The target product can be either defined by a field of type {@link org.esa.beam.framework.datamodel.Product} annotated with the
* {@link org.esa.beam.framework.gpf.annotations.TargetProduct TargetProduct} annotation or
* by calling {@link #setTargetProduct} method.</p>
* <p>The framework calls this method after it has created this operator.
* Any client code that must be performed before computation of tile data
* should be placed here.</p>
*
* @throws org.esa.beam.framework.gpf.OperatorException
* If an error occurs during operator initialisation.
* @see #getTargetProduct()
*/
@Override
public void initialize() throws OperatorException {
try {
// rename product if no subtraction of the flat-earth phase
if (doNotSubtract) {
productName = "ifgs";
productTag = "ifg";
} else {
productName = "srp_ifgs";
productTag = "ifg_srp";
}
checkUserInput();
constructSourceMetadata();
constructTargetMetadata();
createTargetProduct();
// final String[] masterBandNames = sourceProduct.getBandNames();
// for (int i = 0; i < masterBandNames.length; i++) {
// if (masterBandNames[i].contains("mst")) {
// masterBand1 = sourceProduct.getBand(masterBandNames[i]);
// if (masterBand1.getUnit() != null && masterBand1.getUnit().equals(Unit.REAL)) {
// masterBand2 = sourceProduct.getBand(masterBandNames[i + 1]);
// }
// break;
// }
// }
//
// getMetadata();
getSourceImageDimension();
if (!doNotSubtract) {
constructFlatEarthPolynomials();
}
} catch (Exception e) {
throw new OperatorException(e);
}
}
private void getSourceImageDimension() {
sourceImageWidth = sourceProduct.getSceneRasterWidth();
sourceImageHeight = sourceProduct.getSceneRasterHeight();
}
private void constructFlatEarthPolynomials() throws Exception {
for (Integer keyMaster : masterMap.keySet()) {
CplxContainer master = masterMap.get(keyMaster);
for (Integer keySlave : slaveMap.keySet()) {
CplxContainer slave = slaveMap.get(keySlave);
flatEarthPolyMap.put(slave.name, estimateFlatEarthPolynomial(master.metaData, master.orbit, slave.metaData, slave.orbit));
}
}
}
private void constructTargetMetadata() {
for (Integer keyMaster : masterMap.keySet()) {
CplxContainer master = masterMap.get(keyMaster);
for (Integer keySlave : slaveMap.keySet()) {
// generate name for product bands
final String productName = keyMaster.toString() + "_" + keySlave.toString();
final CplxContainer slave = slaveMap.get(keySlave);
final ProductContainer product = new ProductContainer(productName, master, slave, true);
product.targetBandName_I = "i_" + productTag + "_" + master.date + "_" + slave.date;
product.targetBandName_Q = "q_" + productTag + "_" + master.date + "_" + slave.date;
// put ifg-product bands into map
targetMap.put(productName, product);
}
}
}
private void constructSourceMetadata() throws Exception {
// define sourceMaster/sourceSlave name tags
final String masterTag = "mst";
final String slaveTag = "slv";
// get sourceMaster & sourceSlave MetadataElement
final MetadataElement masterMeta = AbstractMetadata.getAbstractedMetadata(sourceProduct);
final String slaveMetadataRoot = AbstractMetadata.SLAVE_METADATA_ROOT;
/* organize metadata */
// put sourceMaster metadata into the masterMap
metaMapPut(masterTag, masterMeta, sourceProduct, masterMap);
// plug sourceSlave metadata into slaveMap
MetadataElement slaveElem = sourceProduct.getMetadataRoot().getElement(slaveMetadataRoot);
if(slaveElem == null) {
slaveElem = sourceProduct.getMetadataRoot().getElement("Slave Metadata");
}
MetadataElement[] slaveRoot = slaveElem.getElements();
for (MetadataElement meta : slaveRoot) {
metaMapPut(slaveTag, meta, sourceProduct, slaveMap);
}
}
private void metaMapPut(final String tag,
final MetadataElement root,
final Product product,
final HashMap<Integer, CplxContainer> map) throws Exception {
// TODO: include polarization flags/checks!
// pull out band names for this product
final String[] bandNames = product.getBandNames();
final int numOfBands = bandNames.length;
// map key: ORBIT NUMBER
int mapKey = root.getAttributeInt(AbstractMetadata.ABS_ORBIT);
// metadata: construct classes and define bands
final String date = OperatorUtils.getAcquisitionDate(root);
final SLCImage meta = new SLCImage(root);
final Orbit orbit = new Orbit(root, orbitDegree);
// TODO: resolve multilook factors
meta.setMlAz(1);
meta.setMlRg(1);
Band bandReal = null;
Band bandImag = null;
for (int i = 0; i < numOfBands; i++) {
String bandName = bandNames[i];
if (bandName.contains(tag) && bandName.contains(date)) {
final Band band = product.getBandAt(i);
if (BandUtilsDoris.isBandReal(band)) {
bandReal = band;
} else if (BandUtilsDoris.isBandImag(band)) {
bandImag = band;
}
}
}
try {
map.put(mapKey, new CplxContainer(date, meta, orbit, bandReal, bandImag));
} catch (Exception e) {
e.printStackTrace();
}
}
private void createTargetProduct() {
// construct target product
targetProduct = new Product(productName,
sourceProduct.getProductType(),
sourceProduct.getSceneRasterWidth(),
sourceProduct.getSceneRasterHeight());
ProductUtils.copyProductNodes(sourceProduct, targetProduct);
for (final Band band : targetProduct.getBands()) {
targetProduct.removeBand(band);
}
for (String key : targetMap.keySet()) {
String targetBandName_I = targetMap.get(key).targetBandName_I;
targetProduct.addBand(targetBandName_I, ProductData.TYPE_FLOAT32);
targetProduct.getBand(targetBandName_I).setUnit(Unit.REAL);
String targetBandName_Q = targetMap.get(key).targetBandName_Q;
targetProduct.addBand(targetBandName_Q, ProductData.TYPE_FLOAT32);
targetProduct.getBand(targetBandName_Q).setUnit(Unit.IMAGINARY);
final String tag0 = targetMap.get(key).sourceMaster.date;
final String tag1 = targetMap.get(key).sourceSlave.date;
if (CREATE_VIRTUAL_BAND) {
String countStr = "_" + productTag + "_" + tag0 + "_" + tag1;
ReaderUtils.createVirtualIntensityBand(targetProduct, targetProduct.getBand(targetBandName_I), targetProduct.getBand(targetBandName_Q), countStr);
ReaderUtils.createVirtualPhaseBand(targetProduct, targetProduct.getBand(targetBandName_I), targetProduct.getBand(targetBandName_Q), countStr);
}
}
// For testing: the optimal results with 1024x1024 pixels tiles, not clear whether it's platform dependent?
// targetProduct.setPreferredTileSize(512, 512);
}
private void checkUserInput() throws OperatorException {
// check for the logic in input paramaters
final MetadataElement masterMeta = AbstractMetadata.getAbstractedMetadata(sourceProduct);
final int isCoregStack = masterMeta.getAttributeInt(AbstractMetadata.coregistered_stack);
if (isCoregStack != 1) {
throw new OperatorException("Input should be a coregistered SLC stack");
}
}
private DoubleMatrix estimateFlatEarthPolynomial(SLCImage masterMetadata, Orbit masterOrbit, SLCImage slaveMetadata, Orbit slaveOrbit) throws Exception {
// estimation window : this works only for NEST "crop" logic
// long minLine = masterMetadata.getCurrentWindow().linelo;
// long maxLine = masterMetadata.getCurrentWindow().linehi;
// long minPixel = masterMetadata.getCurrentWindow().pixlo;
// long maxPixel = masterMetadata.getCurrentWindow().pixhi;
long minLine = 0;
long maxLine = sourceImageHeight;
long minPixel = 0;
long maxPixel = sourceImageWidth;
int numberOfCoefficients = PolyUtils.numberOfCoefficients(srpPolynomialDegree);
int[][] position = MathUtils.distributePoints(srpNumberPoints, new Window(minLine,maxLine,minPixel,maxPixel));
// setup observation and design matrix
DoubleMatrix y = new DoubleMatrix(srpNumberPoints);
DoubleMatrix A = new DoubleMatrix(srpNumberPoints, numberOfCoefficients);
double masterMinPi4divLam = (-4 * Math.PI * org.jlinda.core.Constants.SOL) / masterMetadata.getRadarWavelength();
double slaveMinPi4divLam = (-4 * Math.PI * org.jlinda.core.Constants.SOL) / slaveMetadata.getRadarWavelength();
// Loop through vector or distributedPoints()
for (int i = 0; i < srpNumberPoints; ++i) {
double line = position[i][0];
double pixel = position[i][1];
// compute azimuth/range time for this pixel
final double masterTimeRange = masterMetadata.pix2tr(pixel + 1);
// compute xyz of this point : sourceMaster
org.jlinda.core.Point xyzMaster = masterOrbit.lp2xyz(line + 1, pixel + 1, masterMetadata);
org.jlinda.core.Point slaveTimeVector = slaveOrbit.xyz2t(xyzMaster, slaveMetadata);
final double slaveTimeRange = slaveTimeVector.x;
// observation vector
y.put(i, (masterMinPi4divLam * masterTimeRange) - (slaveMinPi4divLam * slaveTimeRange));
// set up a system of equations
// ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______
double posL = PolyUtils.normalize2(line, minLine, maxLine);
double posP = PolyUtils.normalize2(pixel, minPixel, maxPixel);
int index = 0;
for (int j = 0; j <= srpPolynomialDegree; j++) {
for (int k = 0; k <= j; k++) {
A.put(i, index, (FastMath.pow(posL, (double) (j - k)) * FastMath.pow(posP, (double) k)));
index++;
}
}
}
// Fit polynomial through computed vector of phases
DoubleMatrix Atranspose = A.transpose();
DoubleMatrix N = Atranspose.mmul(A);
DoubleMatrix rhs = Atranspose.mmul(y);
// this should be the coefficient of the reference phase
// flatEarthPolyCoefs = Solve.solve(N, rhs);
return Solve.solve(N, rhs);
}
/**
* Called by the framework in order to compute a tile for the given target band.
* <p>The default implementation throws a runtime exception with the message "not implemented".</p>
*
* @param targetTileMap The target tiles associated with all target bands to be computed.
* @param targetRectangle The rectangle of target tile.
* @param pm A progress monitor which should be used to determine computation cancelation requests.
* @throws org.esa.beam.framework.gpf.OperatorException
* If an error occurs during computation of the target raster.
*/
@Override
public void computeTileStack(Map<Band, Tile> targetTileMap, Rectangle targetRectangle, ProgressMonitor pm)
throws OperatorException {
try {
int y0 = targetRectangle.y;
int yN = y0 + targetRectangle.height - 1;
int x0 = targetRectangle.x;
int xN = targetRectangle.x + targetRectangle.width - 1;
final Window tileWindow = new Window(y0, yN, x0, xN);
// Band flatPhaseBand;
Band targetBand_I;
Band targetBand_Q;
for (String ifgKey : targetMap.keySet()) {
ProductContainer product = targetMap.get(ifgKey);
/// check out results from source ///
Tile tileReal = getSourceTile(product.sourceMaster.realBand, targetRectangle);
Tile tileImag = getSourceTile(product.sourceMaster.imagBand, targetRectangle);
ComplexDoubleMatrix complexMaster = TileUtilsDoris.pullComplexDoubleMatrix(tileReal, tileImag);
/// check out results from source ///
tileReal = getSourceTile(product.sourceSlave.realBand, targetRectangle);
tileImag = getSourceTile(product.sourceSlave.imagBand, targetRectangle);
ComplexDoubleMatrix complexSlave = TileUtilsDoris.pullComplexDoubleMatrix(tileReal, tileImag);
// if (srpPolynomialDegree > 0) {
if (!doNotSubtract) {
// normalize range and azimuth axis
DoubleMatrix rangeAxisNormalized = DoubleMatrix.linspace(x0, xN, complexMaster.columns);
rangeAxisNormalized = normalizeDoubleMatrix(rangeAxisNormalized, sourceImageWidth);
DoubleMatrix azimuthAxisNormalized = DoubleMatrix.linspace(y0, yN, complexMaster.rows);
azimuthAxisNormalized = normalizeDoubleMatrix(azimuthAxisNormalized, sourceImageHeight);
// pull polynomial from the map
DoubleMatrix polyCoeffs = flatEarthPolyMap.get(product.sourceSlave.name);
// estimate the phase on the grid
DoubleMatrix realReferencePhase =
PolyUtils.polyval(azimuthAxisNormalized, rangeAxisNormalized,
polyCoeffs, PolyUtils.degreeFromCoefficients(polyCoeffs.length));
// compute the reference phase
ComplexDoubleMatrix complexReferencePhase =
new ComplexDoubleMatrix(MatrixFunctions.cos(realReferencePhase),
MatrixFunctions.sin(realReferencePhase));
complexSlave.muli(complexReferencePhase); // no conjugate here!
}
SarUtils.computeIfg_inplace(complexMaster, complexSlave.conji());
/// commit to target ///
targetBand_I = targetProduct.getBand(product.targetBandName_I);
Tile tileOutReal = targetTileMap.get(targetBand_I);
TileUtilsDoris.pushDoubleMatrix(complexMaster.real(), tileOutReal, targetRectangle);
targetBand_Q = targetProduct.getBand(product.targetBandName_Q);
Tile tileOutImag = targetTileMap.get(targetBand_Q);
TileUtilsDoris.pushDoubleMatrix(complexMaster.imag(), tileOutImag, targetRectangle);
}
} catch (Throwable e) {
OperatorUtils.catchOperatorException(getId(), e);
}
}
private DoubleMatrix normalizeDoubleMatrix(DoubleMatrix matrix, int factor) {
matrix.subi(0.5 * (factor - 1));
matrix.divi(0.25 * (factor - 1));
return matrix;
}
/**
* The SPI is used to register this operator in the graph processing framework
* via the SPI configuration file
* {@code META-INF/services/org.esa.beam.framework.gpf.OperatorSpi}.
* This class may also serve as a factory for new operator instances.
*
* @see org.esa.beam.framework.gpf.OperatorSpi#createOperator()
* @see org.esa.beam.framework.gpf.OperatorSpi#createOperator(java.util.Map, java.util.Map)
*/
public static class Spi extends OperatorSpi {
public Spi() {
super(InterferogramOp.class);
}
}
}
| kristotammeoja/ks | jlinda/jlinda-nest/src/main/java/org/jlinda/nest/gpf/InterferogramOp.java | Java | gpl-3.0 | 20,085 |
package com.xxl.job.database.meta;
import com.xxl.job.database.dboperate.DBManager;
/**
* 基于mysql的一些特殊处理定义
*
*/
public class MySQLDatabaseMeta extends DatabaseMeta {
public MySQLDatabaseMeta() {
this.dbType = DBManager.MYSQL_DB;
}
}
| lijie2713977/xxl-job | xxl-job-database/src/main/java/com/xxl/job/database/meta/MySQLDatabaseMeta.java | Java | gpl-3.0 | 277 |
import net.sf.javabdd.*;
/**
* @author John Whaley
*/
public class NQueens {
static BDDFactory B;
static boolean TRACE;
static int N; /* Size of the chess board */
static BDD[][] X; /* BDD variable array */
static BDD queen; /* N-queen problem expressed as a BDD */
static BDD solution; /* One solution */
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("USAGE: java NQueens N");
return;
}
N = Integer.parseInt(args[0]);
if (N <= 0) {
System.err.println("USAGE: java NQueens N");
return;
}
TRACE = true;
long time = System.currentTimeMillis();
runTest();
freeAll();
time = System.currentTimeMillis() - time;
System.out.println("Time: "+time/1000.+" seconds");
BDDFactory.CacheStats cachestats = B.getCacheStats();
if (cachestats != null && cachestats.uniqueAccess > 0) {
System.out.println(cachestats);
}
B.done();
B = null;
}
public static double runTest() {
if (B == null) {
/* Initialize with reasonable nodes and cache size and NxN variables */
String numOfNodes = System.getProperty("bddnodes");
int numberOfNodes;
if (numOfNodes == null)
numberOfNodes = (int) (Math.pow(4.42, N-6))*1000;
else
numberOfNodes = Integer.parseInt(numOfNodes);
String cache = System.getProperty("bddcache");
int cacheSize;
if (cache == null)
cacheSize = 1000;
else
cacheSize = Integer.parseInt(cache);
numberOfNodes = Math.max(1000, numberOfNodes);
B = BDDFactory.init(numberOfNodes, cacheSize);
}
if (B.varNum() < N * N) B.setVarNum(N * N);
queen = B.universe();
int i, j;
/* Build variable array */
X = new BDD[N][N];
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
X[i][j] = B.ithVar(i * N + j);
/* Place a queen in each row */
for (i = 0; i < N; i++) {
BDD e = B.zero();
for (j = 0; j < N; j++) {
e.orWith(X[i][j].id());
}
queen.andWith(e);
}
/* Build requirements for each variable(field) */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) {
if (TRACE) System.out.print("Adding position " + i + "," + j+" \r");
build(i, j);
}
solution = queen.satOne();
double result = queen.satCount();
/* Print the results */
if (TRACE) {
System.out.println("There are " + (long) result + " solutions.");
double result2 = solution.satCount();
System.out.println("Here is "+(long) result2 + " solution:");
solution.printSet();
System.out.println();
}
return result;
}
public static void freeAll() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
X[i][j].free();
queen.free();
solution.free();
}
static void build(int i, int j) {
BDD a = B.universe(), b = B.universe(), c = B.universe(), d = B.universe();
int k, l;
/* No one in the same column */
for (l = 0; l < N; l++) {
if (l != j) {
BDD u = X[i][l].apply(X[i][j], BDDFactory.nand);
a.andWith(u);
}
}
/* No one in the same row */
for (k = 0; k < N; k++) {
if (k != i) {
BDD u = X[i][j].apply(X[k][j], BDDFactory.nand);
b.andWith(u);
}
}
/* No one in the same up-right diagonal */
for (k = 0; k < N; k++) {
int ll = k - i + j;
if (ll >= 0 && ll < N) {
if (k != i) {
BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand);
c.andWith(u);
}
}
}
/* No one in the same down-right diagonal */
for (k = 0; k < N; k++) {
int ll = i + j - k;
if (ll >= 0 && ll < N) {
if (k != i) {
BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand);
d.andWith(u);
}
}
}
c.andWith(d);
b.andWith(c);
a.andWith(b);
queen.andWith(a);
}
}
| aindilis/sandbox-gamer | JavaBDD/NQueens.java | Java | gpl-3.0 | 4,650 |
package it.unimi.di.big.mg4j.query;
/*
* MG4J: Managing Gigabytes for Java (big)
*
* Copyright (C) 2005-2015 Sebastiano Vigna
*
* 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/>.
*
*/
import it.unimi.di.big.mg4j.document.Document;
import it.unimi.di.big.mg4j.document.DocumentCollection;
import it.unimi.di.big.mg4j.document.DocumentFactory;
import it.unimi.di.big.mg4j.document.DocumentFactory.FieldType;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.servlet.VelocityViewServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** An generic item, displaying all document fields.
*
* <P>This kind of {@link it.unimi.di.big.mg4j.query.QueryServlet} item will display each field
* of a document inside a <samp>FIELDSET</samp> element. It is mainly useful for debugging purposes.
*/
public class GenericItem extends VelocityViewServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger( GenericItem.class );
@Override
protected ExtendedProperties loadConfiguration( final ServletConfig config ) throws FileNotFoundException, IOException {
return HttpQueryServer.setLiberalResourceLoading( super.loadConfiguration( config ) );
}
public Template handleRequest( final HttpServletRequest request, final HttpServletResponse response, final Context context ) throws Exception {
if ( request.getParameter( "doc" ) != null ) {
DocumentCollection collection = (DocumentCollection)getServletContext().getAttribute( "collection" );
response.setContentType( request.getParameter( "m" ) );
response.setCharacterEncoding( "UTF-8" );
final Document document = collection.document( Long.parseLong( request.getParameter( "doc" ) ) );
final DocumentFactory factory = collection.factory();
final ObjectArrayList<String> fields = new ObjectArrayList<String>();
final int numberOfFields = factory.numberOfFields();
LOGGER.debug( "ParsingFactory declares " + numberOfFields + " fields" );
for( int field = 0; field < numberOfFields; field++ ) {
if ( factory.fieldType( field ) != FieldType.TEXT ) fields.add( StringEscapeUtils.escapeHtml( document.content( field ).toString() ) );
else fields.add( StringEscapeUtils.escapeHtml( IOUtils.toString( (Reader)document.content( field ) ) ).replaceAll( "\n", "<br>\n" ) );
}
context.put( "title", document.title() );
context.put( "fields", fields );
context.put( "factory", factory );
return getTemplate( "it/unimi/dsi/mg4j/query/generic.velocity" );
}
return null;
}
}
| JC-R/mg4j | src/it/unimi/di/big/mg4j/query/GenericItem.java | Java | gpl-3.0 | 3,657 |
package net.adanicx.cyancraft.client.model;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.adanicx.cyancraft.client.OpenGLHelper;
import net.adanicx.cyancraft.entities.EntityArmorStand;
@SideOnly(Side.CLIENT)
public class ModelArmorStand extends ModelArmorStandArmor {
public ModelRenderer standRightSide;
public ModelRenderer standLeftSide;
public ModelRenderer standWaist;
public ModelRenderer standBase;
public ModelArmorStand() {
this(0.0F);
}
public ModelArmorStand(float size) {
super(size, 64, 64);
bipedHead = new ModelRenderer(this, 0, 0);
bipedHead.addBox(-1.0F, -7.0F, -1.0F, 2, 7, 2, size);
bipedHead.setRotationPoint(0.0F, 0.0F, 0.0F);
bipedBody = new ModelRenderer(this, 0, 26);
bipedBody.addBox(-6.0F, 0.0F, -1.5F, 12, 3, 3, size);
bipedBody.setRotationPoint(0.0F, 0.0F, 0.0F);
bipedRightArm = new ModelRenderer(this, 24, 0);
bipedRightArm.addBox(-2.0F, -2.0F, -1.0F, 2, 12, 2, size);
bipedRightArm.setRotationPoint(-5.0F, 2.0F, 0.0F);
bipedLeftArm = new ModelRenderer(this, 32, 16);
bipedLeftArm.mirror = true;
bipedLeftArm.addBox(0.0F, -2.0F, -1.0F, 2, 12, 2, size);
bipedLeftArm.setRotationPoint(5.0F, 2.0F, 0.0F);
bipedRightLeg = new ModelRenderer(this, 8, 0);
bipedRightLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size);
bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F);
bipedLeftLeg = new ModelRenderer(this, 40, 16);
bipedLeftLeg.mirror = true;
bipedLeftLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size);
bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F);
standRightSide = new ModelRenderer(this, 16, 0);
standRightSide.addBox(-3.0F, 3.0F, -1.0F, 2, 7, 2, size);
standRightSide.setRotationPoint(0.0F, 0.0F, 0.0F);
standRightSide.showModel = true;
standLeftSide = new ModelRenderer(this, 48, 16);
standLeftSide.addBox(1.0F, 3.0F, -1.0F, 2, 7, 2, size);
standLeftSide.setRotationPoint(0.0F, 0.0F, 0.0F);
standWaist = new ModelRenderer(this, 0, 48);
standWaist.addBox(-4.0F, 10.0F, -1.0F, 8, 2, 2, size);
standWaist.setRotationPoint(0.0F, 0.0F, 0.0F);
standBase = new ModelRenderer(this, 0, 32);
standBase.addBox(-6.0F, 11.0F, -6.0F, 12, 1, 12, size);
standBase.setRotationPoint(0.0F, 12.0F, 0.0F);
}
@Override
public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entity) {
super.setRotationAngles(p_78087_1_, p_78087_2_, p_78087_3_, p_78087_4_, p_78087_5_, p_78087_6_, entity);
if (entity instanceof EntityArmorStand) {
EntityArmorStand stand = (EntityArmorStand) entity;
bipedLeftArm.showModel = stand.getShowArms();
bipedRightArm.showModel = stand.getShowArms();
standBase.showModel = !stand.hasNoBasePlate();
bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F);
bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F);
standRightSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standRightSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standRightSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standLeftSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standLeftSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standLeftSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standWaist.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standWaist.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standWaist.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standBase.rotateAngleX = 0.0F;
standBase.rotateAngleY = 0.017453292F * -entity.rotationYaw;
standBase.rotateAngleZ = 0.0F;
}
}
@Override
public void render(Entity p_78088_1_, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_) {
super.render(p_78088_1_, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_);
OpenGLHelper.pushMatrix();
if (isChild) {
float f6 = 2.0F;
OpenGLHelper.scale(1.0F / f6, 1.0F / f6, 1.0F / f6);
OpenGLHelper.translate(0.0F, 24.0F * p_78088_7_, 0.0F);
standRightSide.render(p_78088_7_);
standLeftSide.render(p_78088_7_);
standWaist.render(p_78088_7_);
standBase.render(p_78088_7_);
} else {
if (p_78088_1_.isSneaking())
OpenGLHelper.translate(0.0F, 0.2F, 0.0F);
standRightSide.render(p_78088_7_);
standLeftSide.render(p_78088_7_);
standWaist.render(p_78088_7_);
standBase.render(p_78088_7_);
}
OpenGLHelper.popMatrix();
}
}
| Cyancraft/Cyancraft | src/main/java/net/adanicx/cyancraft/client/model/ModelArmorStand.java | Java | gpl-3.0 | 4,767 |
/*
* BufferAllocator.java February 2001
*
* Copyright (C) 2001, Niall Gallagher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.util.buffer;
import java.io.IOException;
import java.io.InputStream;
/**
* The <code>BufferAllocator</code> object is used to provide a means to
* allocate buffers using a single underlying buffer. This uses a buffer from a
* existing allocator to create the region of memory to use to allocate all
* other buffers. As a result this allows a single buffer to acquire the bytes
* in a number of associated buffers. This has the advantage of allowing bytes
* to be read in sequence without joining data from other buffers or allocating
* multiple regions.
*
* @author Niall Gallagher
*/
public class BufferAllocator extends FilterAllocator implements Buffer {
/**
* This is the underlying buffer all other buffers are within.
*/
private Buffer buffer;
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a default buffer size of half a kilobyte.
* This ensures that it can be used for general purpose byte storage and for
* minor I/O tasks.
*
* @param source
* this is where the underlying buffer is allocated
*/
public BufferAllocator(Allocator source) {
super(source);
}
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a specified buffer size. This is typically
* used when a very specific buffer capacity is required, for example a
* request body with a known length.
*
* @param source
* this is where the underlying buffer is allocated
* @param capacity
* the initial capacity of the allocated buffers
*/
public BufferAllocator(Allocator source, long capacity) {
super(source, capacity);
}
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a specified buffer size. This is typically
* used when a very specific buffer capacity is required, for example a
* request body with a known length.
*
* @param source
* this is where the underlying buffer is allocated
* @param capacity
* the initial capacity of the allocated buffers
* @param limit
* this is the maximum buffer size created by this
*/
public BufferAllocator(Allocator source, long capacity, long limit) {
super(source, capacity, limit);
}
/**
* This method is used so that a buffer can be represented as a stream of
* bytes. This provides a quick means to access the data that has been
* written to the buffer. It wraps the buffer within an input stream so that
* it can be read directly.
*
* @return a stream that can be used to read the buffered bytes
*/
@Override
public InputStream getInputStream() throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.getInputStream();
}
/**
* This method is used to acquire the buffered bytes as a string. This is
* useful if the contents need to be manipulated as a string or transferred
* into another encoding. If the UTF-8 content encoding is not supported the
* platform default is used, however this is unlikely as UTF-8 should be
* supported.
*
* @return this returns a UTF-8 encoding of the buffer contents
*/
@Override
public String encode() throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.encode();
}
/**
* This method is used to acquire the buffered bytes as a string. This is
* useful if the contents need to be manipulated as a string or transferred
* into another encoding. This will convert the bytes using the specified
* character encoding format.
*
* @return this returns the encoding of the buffer contents
*/
@Override
public String encode(String charset) throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.encode(charset);
}
/**
* This method is used to append bytes to the end of the buffer. This will
* expand the capacity of the buffer if there is not enough space to
* accommodate the extra bytes.
*
* @param array
* this is the byte array to append to this buffer
*
* @return this returns this buffer for another operation
*/
@Override
public Buffer append(byte[] array) throws IOException {
return this.append(array, 0, array.length);
}
/**
* This method is used to append bytes to the end of the buffer. This will
* expand the capacity of the buffer if there is not enough space to
* accommodate the extra bytes.
*
* @param array
* this is the byte array to append to this buffer
* @param size
* the number of bytes to be read from the array
* @param off
* this is the offset to begin reading the bytes from
*
* @return this returns this buffer for another operation
*/
@Override
public Buffer append(byte[] array, int off, int size) throws IOException {
if (this.buffer == null) {
this.allocate(size);
}
return this.buffer.append(array, off, size);
}
/**
* This will clear all data from the buffer. This simply sets the count to
* be zero, it will not clear the memory occupied by the instance as the
* internal buffer will remain. This allows the memory occupied to be reused
* as many times as is required.
*/
@Override
public void clear() throws IOException {
if (this.buffer != null) {
this.buffer.clear();
}
}
/**
* This method is used to ensure the buffer can be closed. Once the buffer
* is closed it is an immutable collection of bytes and can not longer be
* modified. This ensures that it can be passed by value without the risk of
* modification of the bytes.
*/
@Override
public void close() throws IOException {
if (this.buffer == null) {
this.allocate();
}
this.buffer.close();
}
/**
* This method is used to allocate a default buffer. This will allocate a
* buffer of predetermined size, allowing it to grow to an upper limit to
* accommodate extra data. If the buffer requested is larger than the limit
* an exception is thrown.
*
* @return this returns an allocated buffer with a default size
*/
@Override
public Buffer allocate() throws IOException {
return this.allocate(this.capacity);
}
/**
* This method is used to allocate a default buffer. This will allocate a
* buffer of predetermined size, allowing it to grow to an upper limit to
* accommodate extra data. If the buffer requested is larger than the limit
* an exception is thrown.
*
* @param size
* the initial capacity of the allocated buffer
*
* @return this returns an allocated buffer with a default size
*/
@Override
public Buffer allocate(long size) throws IOException {
if (size > this.limit)
throw new BufferException("Specified size %s beyond limit", size);
if (this.capacity > size) { // lazily create backing buffer
size = this.capacity;
}
if (this.buffer == null) {
this.buffer = this.source.allocate(size);
}
return this.buffer.allocate();
}
}
| TehSomeLuigi/someluigis-peripherals | slp_common/org/simpleframework/util/buffer/BufferAllocator.java | Java | gpl-3.0 | 8,448 |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.openkm.util.FormatUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.api.OKMDocument;
import com.openkm.api.OKMRepository;
import com.openkm.bean.Document;
import com.openkm.core.Config;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.util.PathUtils;
import com.openkm.util.WebUtils;
/**
* Download Servlet
*/
public class DownloadServlet extends BasicSecuredServlet {
private static Logger log = LoggerFactory.getLogger(DownloadServlet.class);
private static final long serialVersionUID = 1L;
/**
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
String userId = request.getRemoteUser();
String path = WebUtils.getString(request, "path");
String uuid = WebUtils.getString(request, "uuid");
boolean inline = WebUtils.getBoolean(request, "inline");
InputStream is = null;
try {
// Now an document can be located by UUID
if (uuid != null && !uuid.isEmpty()) {
uuid = FormatUtil.sanitizeInput(uuid);
path = OKMRepository.getInstance().getNodePath(null, uuid);
} else if (path != null && !path.isEmpty()) {
path = FormatUtil.sanitizeInput(path);
}
if (path != null) {
Document doc = OKMDocument.getInstance().getProperties(null, path);
String fileName = PathUtils.getName(doc.getPath());
// Optinal append version to download ( not when doing checkout )
if (Config.VERSION_APPEND_DOWNLOAD) {
String versionToAppend = " rev " + OKMDocument.getInstance().getProperties(null,uuid).getActualVersion().getName();
String[] nameParts = fileName.split("\\.(?=[^\\.]+$)");
fileName = nameParts[0] + versionToAppend + "." + nameParts[1];
}
log.info("Download {} by {} ({})", new Object[] { path, userId, (inline ? "inline" : "attachment") });
is = OKMDocument.getInstance().getContent(null, path, false);
WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
} else {
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Missing document reference");
out.close();
}
} catch (PathNotFoundException e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "PathNotFoundException: " + e.getMessage());
} catch (RepositoryException e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RepositoryException: " + e.getMessage());
} catch (Exception e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
}
| papamas/DMS-KANGREG-XI-MANADO | src/main/java/com/openkm/servlet/DownloadServlet.java | Java | gpl-3.0 | 4,131 |
package com.example.heregpsloc;
import java.security.SecureRandom;
import java.math.BigInteger;
// http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
public final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
} | popokatapepel/project_uebersaxen | app/src/main/java/com/example/heregpsloc/SessionIdentifierGenerator.java | Java | gpl-3.0 | 392 |
package com.hackatoncivico.rankingpolitico;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.util.LogWriter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hackatoncivico.rankingpolitico.models.Candidato;
import com.hackatoncivico.rankingpolitico.models.Criterio;
import com.hackatoncivico.rankingpolitico.models.CriterioCandidato;
import com.hackatoncivico.rankingpolitico.models.RegistroCandidato;
import com.hackatoncivico.rankingpolitico.models.RegistroCandidatos;
import com.hackatoncivico.rankingpolitico.utils.ApiAccess;
import com.hackatoncivico.rankingpolitico.utils.Utils;
import com.squareup.picasso.Picasso;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Created by franz on 7/11/2015.
*/
public class ProfileActivity extends AppCompatActivity {
private static final String TAG = "ProfileActivity";
public static final String ID_CANDIDATO = "ID_CANDIDATO";
private String idCandidato;
private Candidato candidato;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Add Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setTitle(getString(R.string.title_profile_activity));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
idCandidato = sharedPref.getString(Utils.SELECTED_CANDIDATE, "");
GetCandidato data = new GetCandidato();
data.execute();
}
@Override
public void onResume() {
super.onResume();
if (candidato != null) {
handleCandidato(candidato);
}
}
private void handleCandidato(final Candidato candidato){
this.candidato = candidato;
Button btn_logros = (Button) findViewById(R.id.btn_logros);
btn_logros.setOnClickListener(Utils.setNextScreenListener(this, LogrosActivity.class, LogrosActivity.ID_CANDIDATO, String.valueOf(candidato.id)));
Button btn_criterios = (Button) findViewById(R.id.btn_criterios);
btn_criterios.setOnClickListener(Utils.setNextScreenListener(this, CriteriosActivity.class, CriteriosActivity.ID_CANDIDATO, String.valueOf(candidato.id)));
runOnUiThread(new Runnable() {
@Override
public void run() {
//progressBar.setVisibility(View.GONE);
ImageView avatar = (ImageView) findViewById(R.id.profile_avatar);
Picasso.with(getBaseContext())
.load(ApiAccess.DOMINIO_URL + candidato.foto)
.placeholder(R.drawable.avatar)
.into(avatar);
TextView full_name = (TextView) findViewById(R.id.profile_full_name);
full_name.setText(candidato.nombres + " " + candidato.apellidos);
TextView logros = (TextView) findViewById(R.id.profile_logros_count);
logros.setText(String.valueOf(candidato.logros.size()));
int criterios_count = 0;
for (int i = 0; i < candidato.criterios.size(); i++) {
CriterioCandidato criterioCandidato = candidato.criterios.get(i);
Criterio criterio = criterioCandidato.criterio;
try{
criterios_count = criterios_count + Integer.parseInt(criterio.puntuacion);
} catch (NumberFormatException nfe){
nfe.printStackTrace();
}
}
TextView criterios = (TextView) findViewById(R.id.profile_criterios_count);
criterios.setText(String.valueOf(criterios_count));
}
});
}
private class GetCandidato extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(ApiAccess.CANDIDATOS_URL + '/' + idCandidato);
//Perform the request and check the status code
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
//gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
//List<Candidato> posts = new ArrayList<Candidato>();
//posts = Arrays.asList(gson.fromJson(reader, Candidato[].class));
RegistroCandidato registroCandidato = gson.fromJson(reader, RegistroCandidato.class);
content.close();
handleCandidato(registroCandidato.registros);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
//failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
//failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
//failedLoadingPosts();
}
return null;
}
}
}
| franzueto/rankingpoliticogt-android | app/src/main/java/com/hackatoncivico/rankingpolitico/ProfileActivity.java | Java | gpl-3.0 | 6,690 |
package com.octagon.airships.block;
import com.octagon.airships.reference.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
public abstract class AirshipsBlock extends Block {
public AirshipsBlock(Material material) {
super(material);
}
public AirshipsBlock() {
this(Material.rock);
}
@Override
public String getUnlocalizedName()
{
return String.format("tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister)
{
blockIcon = iconRegister.registerIcon(String.format("%s", getUnwrappedUnlocalizedName(this.getUnlocalizedName())));
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
}
| Todkommt/Mass-Effect-Ships-Mod | src/main/java/com/octagon/airships/block/AirshipsBlock.java | Java | gpl-3.0 | 1,152 |
package itaf.WsUserTakeDeliveryAddressService;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the itaf.WsUserTakeDeliveryAddressService package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private static final QName _DeleteByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteByIdResponse");
private static final QName _GetById_QNAME = new QName("itaf.framework.ws.server.consumer", "getById");
private static final QName _SaveOrUpdateResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdateResponse");
private static final QName _FindListByUserIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserIdResponse");
private static final QName _GetByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "getByIdResponse");
private static final QName _FindListByUserId_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserId");
private static final QName _DeleteById_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteById");
private static final QName _SaveOrUpdate_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdate");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: itaf.WsUserTakeDeliveryAddressService
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link FindListByUserId }
*
*/
public FindListByUserId createFindListByUserId() {
return new FindListByUserId();
}
/**
* Create an instance of {@link DeleteById }
*
*/
public DeleteById createDeleteById() {
return new DeleteById();
}
/**
* Create an instance of {@link SaveOrUpdate }
*
*/
public SaveOrUpdate createSaveOrUpdate() {
return new SaveOrUpdate();
}
/**
* Create an instance of {@link SaveOrUpdateResponse }
*
*/
public SaveOrUpdateResponse createSaveOrUpdateResponse() {
return new SaveOrUpdateResponse();
}
/**
* Create an instance of {@link GetById }
*
*/
public GetById createGetById() {
return new GetById();
}
/**
* Create an instance of {@link DeleteByIdResponse }
*
*/
public DeleteByIdResponse createDeleteByIdResponse() {
return new DeleteByIdResponse();
}
/**
* Create an instance of {@link GetByIdResponse }
*
*/
public GetByIdResponse createGetByIdResponse() {
return new GetByIdResponse();
}
/**
* Create an instance of {@link FindListByUserIdResponse }
*
*/
public FindListByUserIdResponse createFindListByUserIdResponse() {
return new FindListByUserIdResponse();
}
/**
* Create an instance of {@link BzInvoiceItemDto }
*
*/
public BzInvoiceItemDto createBzInvoiceItemDto() {
return new BzInvoiceItemDto();
}
/**
* Create an instance of {@link BzServiceProviderTypeDto }
*
*/
public BzServiceProviderTypeDto createBzServiceProviderTypeDto() {
return new BzServiceProviderTypeDto();
}
/**
* Create an instance of {@link SysRoleDto }
*
*/
public SysRoleDto createSysRoleDto() {
return new SysRoleDto();
}
/**
* Create an instance of {@link BzStockOrderDto }
*
*/
public BzStockOrderDto createBzStockOrderDto() {
return new BzStockOrderDto();
}
/**
* Create an instance of {@link BzOrderPaymentDto }
*
*/
public BzOrderPaymentDto createBzOrderPaymentDto() {
return new BzOrderPaymentDto();
}
/**
* Create an instance of {@link WsPageResult }
*
*/
public WsPageResult createWsPageResult() {
return new WsPageResult();
}
/**
* Create an instance of {@link BzUserDeliveryAddressDto }
*
*/
public BzUserDeliveryAddressDto createBzUserDeliveryAddressDto() {
return new BzUserDeliveryAddressDto();
}
/**
* Create an instance of {@link BzProductCategoryDto }
*
*/
public BzProductCategoryDto createBzProductCategoryDto() {
return new BzProductCategoryDto();
}
/**
* Create an instance of {@link BzProductEvaluationDto }
*
*/
public BzProductEvaluationDto createBzProductEvaluationDto() {
return new BzProductEvaluationDto();
}
/**
* Create an instance of {@link BzMerchantCreditEvalDto }
*
*/
public BzMerchantCreditEvalDto createBzMerchantCreditEvalDto() {
return new BzMerchantCreditEvalDto();
}
/**
* Create an instance of {@link BzProductDto }
*
*/
public BzProductDto createBzProductDto() {
return new BzProductDto();
}
/**
* Create an instance of {@link BzMerchantCreditDto }
*
*/
public BzMerchantCreditDto createBzMerchantCreditDto() {
return new BzMerchantCreditDto();
}
/**
* Create an instance of {@link BzOrderDto }
*
*/
public BzOrderDto createBzOrderDto() {
return new BzOrderDto();
}
/**
* Create an instance of {@link BzPaymentTypeDto }
*
*/
public BzPaymentTypeDto createBzPaymentTypeDto() {
return new BzPaymentTypeDto();
}
/**
* Create an instance of {@link BzConsumerCreditEvalDto }
*
*/
public BzConsumerCreditEvalDto createBzConsumerCreditEvalDto() {
return new BzConsumerCreditEvalDto();
}
/**
* Create an instance of {@link BzInvoiceDto }
*
*/
public BzInvoiceDto createBzInvoiceDto() {
return new BzInvoiceDto();
}
/**
* Create an instance of {@link SysUserDto }
*
*/
public SysUserDto createSysUserDto() {
return new SysUserDto();
}
/**
* Create an instance of {@link BzProductFavoriteDto }
*
*/
public BzProductFavoriteDto createBzProductFavoriteDto() {
return new BzProductFavoriteDto();
}
/**
* Create an instance of {@link BzPositionDto }
*
*/
public BzPositionDto createBzPositionDto() {
return new BzPositionDto();
}
/**
* Create an instance of {@link BzStockDto }
*
*/
public BzStockDto createBzStockDto() {
return new BzStockDto();
}
/**
* Create an instance of {@link BzDistComCreditDto }
*
*/
public BzDistComCreditDto createBzDistComCreditDto() {
return new BzDistComCreditDto();
}
/**
* Create an instance of {@link BzCollectionOrderDto }
*
*/
public BzCollectionOrderDto createBzCollectionOrderDto() {
return new BzCollectionOrderDto();
}
/**
* Create an instance of {@link BzStockOrderItemDto }
*
*/
public BzStockOrderItemDto createBzStockOrderItemDto() {
return new BzStockOrderItemDto();
}
/**
* Create an instance of {@link BzDistributionModelDto }
*
*/
public BzDistributionModelDto createBzDistributionModelDto() {
return new BzDistributionModelDto();
}
/**
* Create an instance of {@link BzMerchantDto }
*
*/
public BzMerchantDto createBzMerchantDto() {
return new BzMerchantDto();
}
/**
* Create an instance of {@link TrProductStockIdDto }
*
*/
public TrProductStockIdDto createTrProductStockIdDto() {
return new TrProductStockIdDto();
}
/**
* Create an instance of {@link BzOrderItemDto }
*
*/
public BzOrderItemDto createBzOrderItemDto() {
return new BzOrderItemDto();
}
/**
* Create an instance of {@link BzShelfDto }
*
*/
public BzShelfDto createBzShelfDto() {
return new BzShelfDto();
}
/**
* Create an instance of {@link BzCartItemDto }
*
*/
public BzCartItemDto createBzCartItemDto() {
return new BzCartItemDto();
}
/**
* Create an instance of {@link SysResourceDto }
*
*/
public SysResourceDto createSysResourceDto() {
return new SysResourceDto();
}
/**
* Create an instance of {@link BzDistributionOrderDto }
*
*/
public BzDistributionOrderDto createBzDistributionOrderDto() {
return new BzDistributionOrderDto();
}
/**
* Create an instance of {@link BzOrderHistoryDto }
*
*/
public BzOrderHistoryDto createBzOrderHistoryDto() {
return new BzOrderHistoryDto();
}
/**
* Create an instance of {@link BzProductBrandDto }
*
*/
public BzProductBrandDto createBzProductBrandDto() {
return new BzProductBrandDto();
}
/**
* Create an instance of {@link BzProductAttachmentDto }
*
*/
public BzProductAttachmentDto createBzProductAttachmentDto() {
return new BzProductAttachmentDto();
}
/**
* Create an instance of {@link BzDistributionCompanyDto }
*
*/
public BzDistributionCompanyDto createBzDistributionCompanyDto() {
return new BzDistributionCompanyDto();
}
/**
* Create an instance of {@link BzConsumerCreditDto }
*
*/
public BzConsumerCreditDto createBzConsumerCreditDto() {
return new BzConsumerCreditDto();
}
/**
* Create an instance of {@link BzUserPositionDto }
*
*/
public BzUserPositionDto createBzUserPositionDto() {
return new BzUserPositionDto();
}
/**
* Create an instance of {@link BzUserTakeDeliveryAddressDto }
*
*/
public BzUserTakeDeliveryAddressDto createBzUserTakeDeliveryAddressDto() {
return new BzUserTakeDeliveryAddressDto();
}
/**
* Create an instance of {@link TrProductStockDto }
*
*/
public TrProductStockDto createTrProductStockDto() {
return new TrProductStockDto();
}
/**
* Create an instance of {@link BzDistComCreditEvalDto }
*
*/
public BzDistComCreditEvalDto createBzDistComCreditEvalDto() {
return new BzDistComCreditEvalDto();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteByIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteByIdResponse")
public JAXBElement<DeleteByIdResponse> createDeleteByIdResponse(DeleteByIdResponse value) {
return new JAXBElement<DeleteByIdResponse>(_DeleteByIdResponse_QNAME, DeleteByIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetById }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getById")
public JAXBElement<GetById> createGetById(GetById value) {
return new JAXBElement<GetById>(_GetById_QNAME, GetById.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdateResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdateResponse")
public JAXBElement<SaveOrUpdateResponse> createSaveOrUpdateResponse(SaveOrUpdateResponse value) {
return new JAXBElement<SaveOrUpdateResponse>(_SaveOrUpdateResponse_QNAME, SaveOrUpdateResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserIdResponse")
public JAXBElement<FindListByUserIdResponse> createFindListByUserIdResponse(FindListByUserIdResponse value) {
return new JAXBElement<FindListByUserIdResponse>(_FindListByUserIdResponse_QNAME, FindListByUserIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetByIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getByIdResponse")
public JAXBElement<GetByIdResponse> createGetByIdResponse(GetByIdResponse value) {
return new JAXBElement<GetByIdResponse>(_GetByIdResponse_QNAME, GetByIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserId }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserId")
public JAXBElement<FindListByUserId> createFindListByUserId(FindListByUserId value) {
return new JAXBElement<FindListByUserId>(_FindListByUserId_QNAME, FindListByUserId.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteById }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteById")
public JAXBElement<DeleteById> createDeleteById(DeleteById value) {
return new JAXBElement<DeleteById>(_DeleteById_QNAME, DeleteById.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdate }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdate")
public JAXBElement<SaveOrUpdate> createSaveOrUpdate(SaveOrUpdate value) {
return new JAXBElement<SaveOrUpdate>(_SaveOrUpdate_QNAME, SaveOrUpdate.class, null, value);
}
}
| zpxocivuby/freetong_mobile_server | itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsUserTakeDeliveryAddressService/ObjectFactory.java | Java | gpl-3.0 | 14,213 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* 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.lh64.randomdungeon.actors.buffs;
import com.lh64.randomdungeon.ui.BuffIndicator;
import com.lh64.utils.Bundle;
public class SnipersMark extends FlavourBuff {
public int object = 0;
private static final String OBJECT = "object";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( OBJECT, object );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
object = bundle.getInt( OBJECT );
}
@Override
public int icon() {
return BuffIndicator.MARK;
}
@Override
public String toString() {
return "Zeroed in";
}
}
| lighthouse64/Random-Dungeon | src/com/lh64/randomdungeon/actors/buffs/SnipersMark.java | Java | gpl-3.0 | 1,360 |
package com.dotmarketing.servlets;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dotcms.repackage.commons_lang_2_4.org.apache.commons.lang.time.FastDateFormat;
import com.dotmarketing.util.Constants;
import com.dotmarketing.util.Logger;
import com.liferay.util.FileUtil;
public class IconServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
FastDateFormat df = FastDateFormat.getInstance(Constants.RFC2822_FORMAT, TimeZone.getTimeZone("GMT"), Locale.US);
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String i = request.getParameter("i");
if(i !=null && i.length() > 0 && i.indexOf('.') < 0){
i="." + i;
}
String icon = com.dotmarketing.util.UtilMethods.getFileExtension(i);
java.text.SimpleDateFormat httpDate = new java.text.SimpleDateFormat(Constants.RFC2822_FORMAT, Locale.US);
httpDate.setTimeZone(TimeZone.getDefault());
// -------- HTTP HEADER/ MODIFIED SINCE CODE -----------//
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(new Date(0));
Date _lastModified = c.getTime();
String _eTag = "dot:icon-" + icon + "-" + _lastModified.getTime() ;
String ifModifiedSince = request.getHeader("If-Modified-Since");
String ifNoneMatch = request.getHeader("If-None-Match");
/*
* If the etag matches then the file is the same
*
*/
if(ifNoneMatch != null){
if(_eTag.equals(ifNoneMatch) || ifNoneMatch.equals("*")){
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED );
return;
}
}
/* Using the If-Modified-Since Header */
if(ifModifiedSince != null){
try{
Date ifModifiedSinceDate = httpDate.parse(ifModifiedSince);
if(_lastModified.getTime() <= ifModifiedSinceDate.getTime()){
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED );
return;
}
}
catch(Exception e){}
}
response.setHeader("Last-Modified", df.format(_lastModified));
response.setHeader("ETag", "\"" + _eTag +"\"");
ServletOutputStream out = response.getOutputStream();
response.setContentType("image/png");
java.util.GregorianCalendar expiration = new java.util.GregorianCalendar();
expiration.add(java.util.Calendar.YEAR, 1);
response.setHeader("Expires", httpDate.format(expiration.getTime()));
response.setHeader("Cache-Control", "max-age=" +(60*60*24*30*12));
File f = new File(FileUtil.getRealPath("/html/images/icons/" + icon + ".png"));
if(!f.exists()){
f = new File(FileUtil.getRealPath("/html/images/icons/ukn.png"));
}
response.setHeader("Content-Length", String.valueOf(f.length()));
BufferedInputStream fis = null;
try {
fis =
new BufferedInputStream(new FileInputStream(f));
int n;
while ((n = fis.available()) > 0) {
byte[] b = new byte[n];
int result = fis.read(b);
if (result == -1)
break;
out.write(b);
} // end while
}
catch (Exception e) {
Logger.error(this.getClass(), "cannot read:" + f.toString());
}
finally {
if (fis != null)
fis.close();
f=null;
}
out.close();
}
}
| austindlawless/dotCMS | src/com/dotmarketing/servlets/IconServlet.java | Java | gpl-3.0 | 3,815 |
/**
* Copyright (c) 2017 HES-SO Valais - Smart Infrastructure Laboratory (http://silab.hes.ch)
*
* This file is part of StructuredSimulationFramework.
*
* The StructuredSimulationFramework 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.
*
* The StructuredSimulationFramework 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 StructuredSimulationFramework.
* If not, see <http://www.gnu.org/licenses/>.
* */
package ch.hevs.silab.structuredsim.interfaces;
import java.util.List;
/**
* Name : IManageModifier
* <p>
* Description : Class to manage the modifier
* <p>
* Date : 25 July 2017
* @version 1.0
* @author Audrey Dupont
*/
public interface IManageModifier {
/**
* Method to initiate the modifier class inside a List
*/
public List<AModifier> initiateModifierList();
}
| SiLab-group/structSim | structSimV1/src/main/java/ch/hevs/silab/structuredsim/interfaces/IManageModifier.java | Java | gpl-3.0 | 1,281 |
/**
* Hub Miner: a hubness-aware machine learning experimentation library.
* Copyright (C) 2014 Nenad Tomasev. Email: nenad.tomasev at gmail.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 draw.basic;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import javax.imageio.*;
import javax.swing.*;
/**
* This is a convenience class to create and optionally save to a file a
* BufferedImage of an area shown on the screen. It covers several different
* scenarios, so the image can be created of:
*
* a) an entire component b) a region of the component c) the entire desktop d)
* a region of the desktop
*
* This class can also be used to create images of components not displayed on a
* GUI. The only foolproof way to get an image in such cases is to make sure the
* component has been added to a realized window with code something like the
* following:
*
* JFrame frame = new JFrame(); frame.setContentPane( someComponent );
* frame.pack(); ScreenImage.createImage( someComponent );
*
* @author This code has been taken from the following web sources:
* https://www.wuestkamp.com/2012/02/java-save-component-to-image-make-screen-shot-of-component/
* http://tips4java.wordpress.com/2008/10/13/screen-image/
*/
public class ScreenImage {
private static List<String> imageTypes = Arrays.asList(
ImageIO.getWriterFileSuffixes());
/**
* Create a BufferedImage for Swing components. The entire component will be
* captured to an image.
*
* @param component Swing component to create the image from.
* @return image The image for the given region.
*/
public static BufferedImage createImage(JComponent component) {
Dimension dim = component.getSize();
if (dim.width == 0 || dim.height == 0) {
dim = component.getPreferredSize();
component.setSize(dim);
}
Rectangle region = new Rectangle(0, 0, dim.width, dim.height);
return ScreenImage.createImage(component, region);
}
/**
* Create a BufferedImage for Swing components. All or part of the component
* can be captured to an image.
*
* @param component Swing component to create the image from.
* @param region The region of the component to be captured to an image.
* @return image The image for the given region.
*/
public static BufferedImage createImage(JComponent component,
Rectangle region) {
if (!component.isDisplayable()) {
Dimension dim = component.getSize();
if (dim.width == 0 || dim.height == 0) {
dim = component.getPreferredSize();
component.setSize(dim);
}
layoutComponent(component);
}
BufferedImage image = new BufferedImage(region.width, region.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
// Paint a background for non-opaque components.
if (!component.isOpaque()) {
g2d.setColor(component.getBackground());
g2d.fillRect(region.x, region.y, region.width, region.height);
}
g2d.translate(-region.x, -region.y);
component.paint(g2d);
g2d.dispose();
return image;
}
/**
* Convenience method to create a BufferedImage of the desktop.
*
* @param fileName Name of file to be created or null.
* @return image The image for the given region.
* @exception AWTException
* @exception IOException
*/
public static BufferedImage createDesktopImage() throws AWTException,
IOException {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle region = new Rectangle(0, 0, dim.width, dim.height);
return ScreenImage.createImage(region);
}
/**
* Create a BufferedImage for AWT components.
*
* @param component AWT component to create image from
* @return image the image for the given region
* @exception AWTException see Robot class constructors
*/
public static BufferedImage createImage(Component component)
throws AWTException {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, component);
Rectangle region = component.getBounds();
region.x = p.x;
region.y = p.y;
return ScreenImage.createImage(region);
}
/**
* Create a BufferedImage from a rectangular region on the screen. This will
* include Swing components JFrame, JDialog and JWindow which all extend
* from Component, not JComponent.
*
* @param Region region on the screen to create image from
* @return Image the image for the given region
* @exception AWTException see Robot class constructors
*/
public static BufferedImage createImage(Rectangle region)
throws AWTException {
BufferedImage image = new Robot().createScreenCapture(region);
return image;
}
/**
* Write a BufferedImage to a File.
*
* @param Image image to be written.
* @param FileName name of file to be created.
* @exception IOException if an error occurs during writing.
*/
public static void writeImage(BufferedImage image, String fileName)
throws IOException {
if (fileName == null) {
return;
}
int offset = fileName.lastIndexOf(".");
if (offset == -1) {
String message = "file type was not specified";
throw new IOException(message);
}
String fileType = fileName.substring(offset + 1);
if (imageTypes.contains(fileType)) {
ImageIO.write(image, fileType, new File(fileName));
} else {
String message = "unknown writer file type (" + fileType + ")";
throw new IOException(message);
}
}
/**
* A recursive layout call on the component.
*
* @param component Component object.
*/
static void layoutComponent(Component component) {
synchronized (component.getTreeLock()) {
component.doLayout();
if (component instanceof Container) {
for (Component child :
((Container) component).getComponents()) {
layoutComponent(child);
}
}
}
}
}
| datapoet/hubminer | src/main/java/draw/basic/ScreenImage.java | Java | gpl-3.0 | 7,076 |
/*
* dmfs - http://dmfs.org/
*
* Copyright (C) 2012 Marten Gajda <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package org.dmfs.xmlserializer;
import java.io.IOException;
import java.io.Writer;
/**
* An abstract XML node.
*
* @author Marten Gajda <[email protected]>
*/
public abstract class XmlAbstractNode
{
/**
* State for new nodes.
*/
final static int STATE_NEW = 0;
/**
* State indicating the node has been opened and the start tag has been opened.
*/
final static int STATE_START_TAG_OPEN = 1;
/**
* State indication the node has been opened and the start tag has been closed, but the end tag is not written yet.
*/
final static int STATE_START_TAG_CLOSED = 2;
/**
* State indication the node has been closed (i.e. the end tag has been written).
*/
final static int STATE_CLOSED = 3;
/**
* The state of a node, initialized with {@link STATE_NEW}.
*/
int state = STATE_NEW;
/**
* The depth at which this node is located in the XML tree. Until this node has been added to a tree it is considered to be the root element.
*/
private int mDepth = 0;
/**
* Set the depth of this node (i.e. at which level it is located in the XML node tree).
*
* @param depth
* The depth.
*/
void setDepth(int depth)
{
mDepth = depth;
}
/**
* Get the depth of this node (i.e. at which level it is located in the XML node tree).
*
* @return The depth.
*/
final int getDepth()
{
return mDepth;
}
/**
* Assign the {@link XmlNamespaceRegistry} that belongs to this XML tree.
*
* @param namespaceRegistry
* The {@link XmlNamespaceRegistry} of this XMl tree.
* @throws InvalidValueException
*/
abstract void setNamespaceRegistry(XmlNamespaceRegistry namespaceRegistry) throws InvalidValueException;
/**
* Open this node for writing to a {@link Writer}
*
* @param out
* The {@link Writer} to write to.
* @throws IOException
* @throws InvalidStateException
* @throws InvalidValueException
*/
abstract void open(Writer out) throws IOException, InvalidStateException, InvalidValueException;
/**
* Close this node, flushing out all unwritten content.
*
* @throws IOException
* @throws InvalidStateException
* @throws InvalidValueException
*/
abstract void close() throws IOException, InvalidStateException, InvalidValueException;
}
| dmfs/xml-serializer | src/org/dmfs/xmlserializer/XmlAbstractNode.java | Java | gpl-3.0 | 3,072 |
package beseenium.controller.ActionFactory;
/** Copyright(C) 2015 Jan P.C. Hanson & BeSeen Marketing Ltd
*
* 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/>.
*/
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import beseenium.controller.ActionDataFactory.ActionDataFactory;
import beseenium.controller.ActionFactory.elementActions.MakeClear;
import beseenium.controller.ActionFactory.elementActions.MakeClick;
import beseenium.controller.ActionFactory.elementActions.MakeGetAttribute;
import beseenium.controller.ActionFactory.elementActions.MakeGetCssValue;
import beseenium.controller.ActionFactory.elementActions.MakeGetLocation;
import beseenium.controller.ActionFactory.elementActions.MakeGetSize;
import beseenium.controller.ActionFactory.elementActions.MakeGetTagName;
import beseenium.controller.ActionFactory.elementActions.MakeGetText;
import beseenium.controller.ActionFactory.elementActions.MakeIsDisplayed;
import beseenium.controller.ActionFactory.elementActions.MakeIsEnabled;
import beseenium.controller.ActionFactory.elementActions.MakeIsSelected;
import beseenium.controller.ActionFactory.elementActions.MakeSendKeys;
import beseenium.controller.ActionFactory.elementActions.MakeSubmit;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByClass;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByCss;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsById;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByLinkTxt;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByName;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByPartialLinkTxt;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByTagName;
import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByXpath;
import beseenium.controller.ActionFactory.navigateActions.MakeNavigateBack;
import beseenium.controller.ActionFactory.navigateActions.MakeNavigateForward;
import beseenium.controller.ActionFactory.navigateActions.MakeRefreshPage;
import beseenium.controller.ActionFactory.pageActions.MakeBrowserQuit;
import beseenium.controller.ActionFactory.pageActions.MakeGetPageSrc;
import beseenium.controller.ActionFactory.pageActions.MakeGetTitle;
import beseenium.controller.ActionFactory.pageActions.MakeGetURL;
import beseenium.controller.ActionFactory.pageActions.MakePageClose;
import beseenium.controller.ActionFactory.pageActions.MakePageGet;
import beseenium.exceptions.actionDataExceptions.ActionDataFactoryException;
import beseenium.exceptions.actionExceptions.ActionFactoryException;
import beseenium.model.action.AbstractAction;
/**
* this class is a factory for creating actions, it uses a factory method
* style pattern and a map implementation.
* @author JPC Hanson
*
*/
public class ActionFactory
{
/** the map to store the actions in **/
private Map<String, MakeAction> actionMap;
/** internal ActionDataFactory reference **/
private ActionDataFactory actionDataFactory;
/**
* default constructor creates and populates internal map
* @param actionDataFactory
* @throws ActionDataFactoryException
* @throws MalformedURLException
*
*/
public ActionFactory(ActionDataFactory actionDataFactory)
throws ActionDataFactoryException, MalformedURLException
{
super();
this.actionDataFactory = actionDataFactory;
this.actionMap = new HashMap<String, MakeAction>();
this.populateActionMap();
}
/**
* creates an Action
* @return AbstractAction
* @throws ActionFactoryException
* @throws ActionDataFactoryException
*/
public AbstractAction makeAction(String actionKey) throws ActionFactoryException
{
if(this.actionMap.containsKey(actionKey))
{return this.actionMap.get(actionKey).makeAction();}
else
{throw new ActionFactoryException("you cannot instanciate this type of Action '"
+actionKey+ "' Check your spelling, or refer to documentation");}
}
/**
* creates all possible actions and populates the map with them.
* @throws ActionDataFactoryException
*
*/
private void populateActionMap() throws ActionDataFactoryException
{
// //Page Actions
this.actionMap.put( "PageGet", new MakePageGet(actionDataFactory));
this.actionMap.put( "GetPageSrc", new MakeGetPageSrc(actionDataFactory));
this.actionMap.put( "BrowserQuit", new MakeBrowserQuit(actionDataFactory));
this.actionMap.put( "GetTitle", new MakeGetTitle(actionDataFactory));
this.actionMap.put( "GetURL", new MakeGetURL(actionDataFactory));
this.actionMap.put( "PageClose", new MakePageClose(actionDataFactory));
// //Navigation Actions
this.actionMap.put( "NavigateBack", new MakeNavigateBack(actionDataFactory));
this.actionMap.put( "NavigateForward", new MakeNavigateForward(actionDataFactory));
this.actionMap.put( "RefreshPage", new MakeRefreshPage(actionDataFactory));
// //Find Element Actions
this.actionMap.put( "FindElementsByClass", new MakeFindElementsByClass(actionDataFactory));
this.actionMap.put( "FindElementsByCss", new MakeFindElementsByCss(actionDataFactory));
this.actionMap.put( "FindElementsById", new MakeFindElementsById(actionDataFactory));
this.actionMap.put( "FindElementsByLinkTxt", new MakeFindElementsByLinkTxt(actionDataFactory));
this.actionMap.put( "FindElementsByName", new MakeFindElementsByName(actionDataFactory));
this.actionMap.put( "FindElementsByPartialLinkTxt", new MakeFindElementsByPartialLinkTxt(actionDataFactory));
this.actionMap.put( "FindElementsByTagName", new MakeFindElementsByTagName(actionDataFactory));
this.actionMap.put( "FindElementsByXpath", new MakeFindElementsByXpath(actionDataFactory));
// //Element Actions
this.actionMap.put( "Clear", new MakeClear(actionDataFactory));
this.actionMap.put( "Click", new MakeClick(actionDataFactory));
this.actionMap.put( "GetAttribute", new MakeGetAttribute(actionDataFactory));
this.actionMap.put( "GetCssValue", new MakeGetCssValue(actionDataFactory));
this.actionMap.put( "GetLocation", new MakeGetLocation(actionDataFactory));
this.actionMap.put( "GetSize", new MakeGetSize(actionDataFactory));
this.actionMap.put( "GetTagName", new MakeGetTagName(actionDataFactory));
this.actionMap.put( "GetText", new MakeGetText(actionDataFactory));
this.actionMap.put( "IsDisplayed", new MakeIsDisplayed(actionDataFactory));
this.actionMap.put( "IsEnabled", new MakeIsEnabled(actionDataFactory));
this.actionMap.put( "IsSelected", new MakeIsSelected(actionDataFactory));
this.actionMap.put( "SendKeys", new MakeSendKeys(actionDataFactory));
this.actionMap.put( "Submit", new MakeSubmit(actionDataFactory));
}
}
| jpchanson/BeSeenium | src/beseenium/controller/ActionFactory/ActionFactory.java | Java | gpl-3.0 | 7,333 |
/*
* 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 proyectomio.controlador.operaciones;
import proyectomio.accesoDatos.Controlador_BD;
import proyectomio.modelo.Consulta;
/**
*
* @author root
*/
public class Controlador_Conductor {
private final Controlador_BD CONTROLADOR_BD = new Controlador_BD();
public Consulta consultar_buses_asignados(int id_conductor) {
if (id_conductor != 0) {
Consulta consulta = new Consulta();
consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa inner join ruta on ruta.id_ruta = bus.id_ruta where bus_empleado.id_empleado = " + id_conductor);
return consulta;
}
else{
Consulta consulta = new Consulta();
consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM (bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa) inner join ruta on ruta.id_ruta = bus.id_ruta;");
return consulta;
}
}
}
| luchoman08/Proyecto-MIO | src/java/proyectomio/controlador/operaciones/Controlador_Conductor.java | Java | gpl-3.0 | 1,169 |
package io.github.notsyncing.cowherd.files;
import io.github.notsyncing.cowherd.Cowherd;
import io.github.notsyncing.cowherd.commons.CowherdConfiguration;
import io.github.notsyncing.cowherd.commons.RouteType;
import io.github.notsyncing.cowherd.models.ActionMethodInfo;
import io.github.notsyncing.cowherd.models.RouteInfo;
import io.github.notsyncing.cowherd.models.UploadFileInfo;
import io.github.notsyncing.cowherd.routing.RouteManager;
import io.github.notsyncing.cowherd.server.CowherdLogger;
import io.github.notsyncing.cowherd.utils.StringUtils;
import io.vertx.core.Vertx;
import io.vertx.core.file.FileSystem;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
/**
* 文件存储对象
* 用于方便分类存储各类文件
*/
public class FileStorage
{
private Map<Enum, Path> storagePaths = new ConcurrentHashMap<>();
private FileSystem fs;
private CowherdLogger log = CowherdLogger.getInstance(this);
public FileStorage(Vertx vertx)
{
init(vertx);
}
public FileStorage() throws IllegalAccessException, InvocationTargetException, InstantiationException {
this(Cowherd.dependencyInjector.getComponent(Vertx.class));
}
protected void init(Vertx vertx) {
try {
fs = vertx.fileSystem();
} catch (Exception e) {
log.e("Failed to create file storage", e);
}
}
/**
* 注册一个文件存储目录
* @param tag 标识该存储类型的枚举
* @param path 要注册的目录
* @throws IOException
*/
public void registerStoragePath(Enum tag, String path) throws IOException
{
registerStoragePath(tag, Paths.get(path));
}
/**
* 注册一个文件存储目录
* @param tag 标识该存储类型的枚举
* @param path 要注册的目录
* @throws IOException
*/
public void registerStoragePath(Enum tag, Path path) throws IOException
{
if (storagePaths.containsKey(tag)) {
log.w("Tag " + tag + " already registered to path " + storagePaths.get(tag) +
", will be overwritten to " + path);
}
storagePaths.put(tag, path);
if (!Files.exists(path)) {
Path p = Files.createDirectories(path);
log.i("Created storage path " + p + " for tag " + tag);
} else {
log.i("Registered storage path " + path + " to tag " + tag);
}
}
/**
* 获取存储类别标识所对应的存放目录
* @param tag 存储类别标识枚举
* @return 该类别标识所对应的存放目录
*/
public Path getStoragePath(Enum tag)
{
return storagePaths.get(tag);
}
/**
* 异步将文件存放至指定的存储类别中
* @param file 要存放的文件
* @param tag 存储类别标识枚举
* @param newFileName 新文件名,若为 null,则按原文件名存储
* @param noRemoveOld 为 true 则不删除源文件
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFile(Path file, Enum tag, String newFileName, boolean noRemoveOld) {
CompletableFuture<Path> f = new CompletableFuture<>();
String fileName = newFileName == null ? file.getFileName().toString() : newFileName;
Path store = storagePaths.get(tag);
Path to;
if (store == null) {
f.completeExceptionally(new Exception("Storage tag " + tag + " not registered!"));
return f;
}
if (CowherdConfiguration.isStoreFilesByDate()) {
LocalDate date = LocalDate.now();
to = store.resolve(String.valueOf(date.getYear())).resolve(String.valueOf(date.getMonthValue()))
.resolve(String.valueOf(date.getDayOfMonth()));
try {
Files.createDirectories(to);
} catch (Exception e) {
f.completeExceptionally(e);
return f;
}
to = to.resolve(fileName);
} else {
to = store.resolve(fileName);
}
final Path finalTo = to;
fs.copy(file.toString(), to.toString(), r -> {
if (r.succeeded()) {
if (noRemoveOld) {
f.complete(store.relativize(finalTo));
} else {
fs.delete(file.toString(), r2 -> {
if (r2.succeeded()) {
f.complete(finalTo);
} else {
f.completeExceptionally(r2.cause());
}
});
}
} else {
f.completeExceptionally(r.cause());
}
});
return f;
}
/**
* 异步将文件存放至指定的存储类别中
* @param file 要存放的文件
* @param tag 存储类别标识枚举
* @param newFileName 新文件名,若为 null,则按原文件名存储
* @param noRemoveOld 为 true 则不删除源文件
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFile(File file, Enum tag, String newFileName, boolean noRemoveOld)
{
return storeFile(file.toPath(), tag, newFileName, noRemoveOld);
}
/**
* 异步将文件存放至指定的存储类别中
* @param file 要存放的文件
* @param tag 存储类别标识枚举
* @param newFileName 新文件名,若为 null,则按原文件名存储
* @param noRemoveOld 为 true 则不删除源文件
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFile(String file, Enum tag, String newFileName, boolean noRemoveOld)
{
return storeFile(Paths.get(file), tag, newFileName, noRemoveOld);
}
/**
* 异步将上传的文件存放至指定的存储类别中
* @param file 要存放的上传文件信息对象
* @param tag 存储类别标识枚举
* @param newFileName 新文件名,若为 null,则按原文件名存储
* @param noRemoveOld 为 true 则不删除源文件
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFile(UploadFileInfo file, Enum tag, String newFileName, boolean noRemoveOld)
{
if (file == null) {
return CompletableFuture.completedFuture(null);
}
return storeFile(file.getFile(), tag, newFileName, noRemoveOld);
}
/**
* 异步将上传的文件按源文件名存放至指定的存储类别中,并删除源文件
* @param file 要存放的上传文件信息对象
* @param tag 存储类别标识枚举
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFile(UploadFileInfo file, Enum tag)
{
if (file == null) {
return CompletableFuture.completedFuture(null);
}
if ((StringUtils.isEmpty(file.getFilename())) && ((file.getFile() == null) || (file.getFile().length() <= 0))) {
return CompletableFuture.completedFuture(null);
}
return storeFile(file.getFile(), tag, file.getFilename(), false);
}
/**
* 异步将上传的文件以随机文件名(保持扩展名)存放至指定的存储类别中,并删除源文件
* @param file 要存放的上传文件信息对象
* @param tag 存储类别标识枚举
* @return 指示存放是否完成的 CompletableFuture 对象,并包含文件相对于该分类存储目录的相对路径
*/
public CompletableFuture<Path> storeFileWithRandomName(UploadFileInfo file, Enum tag)
{
if (file == null) {
return CompletableFuture.completedFuture(null);
}
if ((StringUtils.isEmpty(file.getFilename())) && ((file.getFile() == null) || (file.getFile().length() <= 0))) {
return CompletableFuture.completedFuture(null);
}
String fn = file.getFilename();
int e = fn.lastIndexOf('.');
String ext = e > 0 ? fn.substring(e) : "";
String filename = UUID.randomUUID().toString() + ext;
return storeFile(file.getFile(), tag, filename, false);
}
/**
* 获取文件在某一存储类别中的完整路径
* @param tag 存储类别标识枚举
* @param file 要获取完整路径的文件
* @return 该文件的完整路径
*/
public Path resolveFile(Enum tag, Path file)
{
return storagePaths.get(tag).resolve(file);
}
/**
* 获取文件中某一存储类别中的相对路径
* @param tag 存储类别标识枚举
* @param file 要获取相对路径的文件
* @return 该文件的相对路径
*/
public Path relativize(Enum tag, Path file)
{
return getStoragePath(tag).relativize(file);
}
private void addServerRoute(RouteInfo route)
{
Method m;
try {
m = CowherdFileStorageService.class.getMethod("getFile", Enum.class, String.class);
} catch (NoSuchMethodException e) {
log.e("No action for file storage!", e);
return;
}
RouteManager.addRoute(route, new ActionMethodInfo(m));
}
/**
* 注册一条直接访问指定文件存储的路由
* @param tag 存储类别标识枚举
* @param routeRegex 路由规则,必须包含一个名为 path 的命名匹配组,用于匹配要访问的文件的相对路径
*/
public void registerServerRoute(Enum tag, String routeRegex)
{
RouteInfo info = new RouteInfo();
info.setPath(routeRegex);
info.setType(RouteType.Http);
info.setOtherParameters(new Object[] { tag });
addServerRoute(info);
}
public void registerServerSimpleRoute(Enum tag, String route)
{
RouteInfo info = new RouteInfo();
info.setPath(route);
info.setType(RouteType.Http);
info.setOtherParameters(new Object[] { tag });
info.setFastRoute(true);
addServerRoute(info);
}
public void removeStoragePathIf(Predicate<Enum> predicate) {
storagePaths.entrySet().removeIf(e -> predicate.test(e.getKey()));
}
}
| notsyncing/cowherd | cowherd-core/src/main/java/io/github/notsyncing/cowherd/files/FileStorage.java | Java | gpl-3.0 | 11,054 |
package com.limelight.binding.input.driver;
public interface UsbDriverListener {
void reportControllerState(int controllerId, short buttonFlags,
float leftStickX, float leftStickY,
float rightStickX, float rightStickY,
float leftTrigger, float rightTrigger);
void deviceRemoved(int controllerId);
void deviceAdded(int controllerId);
}
| GTMoogle/StreamTheater | src/com/limelight/binding/input/driver/UsbDriverListener.java | Java | gpl-3.0 | 442 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
// Referenced classes of package net.minecraft.src:
// GuiScreen, AchievementList, Achievement, GuiSmallButton,
// StatCollector, GuiButton, GameSettings, KeyBinding,
// FontRenderer, MathHelper, RenderEngine, Block,
// StatFileWriter, RenderItem, RenderHelper
public class GuiAchievements extends GuiScreen
{
private static final int field_27126_s;
private static final int field_27125_t;
private static final int field_27124_u;
private static final int field_27123_v;
protected int field_27121_a;
protected int field_27119_i;
protected int field_27118_j;
protected int field_27117_l;
protected double field_27116_m;
protected double field_27115_n;
protected double field_27114_o;
protected double field_27113_p;
protected double field_27112_q;
protected double field_27111_r;
private int field_27122_w;
private StatFileWriter field_27120_x;
public GuiAchievements(StatFileWriter p_i575_1_)
{
field_27121_a = 256;
field_27119_i = 202;
field_27118_j = 0;
field_27117_l = 0;
field_27122_w = 0;
field_27120_x = p_i575_1_;
char c = '\215';
char c1 = '\215';
field_27116_m = field_27114_o = field_27112_q = AchievementList.field_25195_b.field_25075_a * 24 - c / 2 - 12;
field_27115_n = field_27113_p = field_27111_r = AchievementList.field_25195_b.field_25074_b * 24 - c1 / 2;
}
public void func_6448_a()
{
field_949_e.clear();
field_949_e.add(new GuiSmallButton(1, field_951_c / 2 + 24, field_950_d / 2 + 74, 80, 20, StatCollector.func_25200_a("gui.done")));
}
protected void func_572_a(GuiButton p_572_1_)
{
if(p_572_1_.field_938_f == 1)
{
field_945_b.func_6272_a(null);
field_945_b.func_6259_e();
}
super.func_572_a(p_572_1_);
}
protected void func_580_a(char p_580_1_, int p_580_2_)
{
if(p_580_2_ == field_945_b.field_6304_y.field_1570_o.field_1370_b)
{
field_945_b.func_6272_a(null);
field_945_b.func_6259_e();
} else
{
super.func_580_a(p_580_1_, p_580_2_);
}
}
public void func_571_a(int p_571_1_, int p_571_2_, float p_571_3_)
{
if(Mouse.isButtonDown(0))
{
int i = (field_951_c - field_27121_a) / 2;
int j = (field_950_d - field_27119_i) / 2;
int k = i + 8;
int l = j + 17;
if((field_27122_w == 0 || field_27122_w == 1) && p_571_1_ >= k && p_571_1_ < k + 224 && p_571_2_ >= l && p_571_2_ < l + 155)
{
if(field_27122_w == 0)
{
field_27122_w = 1;
} else
{
field_27114_o -= p_571_1_ - field_27118_j;
field_27113_p -= p_571_2_ - field_27117_l;
field_27112_q = field_27116_m = field_27114_o;
field_27111_r = field_27115_n = field_27113_p;
}
field_27118_j = p_571_1_;
field_27117_l = p_571_2_;
}
if(field_27112_q < (double)field_27126_s)
{
field_27112_q = field_27126_s;
}
if(field_27111_r < (double)field_27125_t)
{
field_27111_r = field_27125_t;
}
if(field_27112_q >= (double)field_27124_u)
{
field_27112_q = field_27124_u - 1;
}
if(field_27111_r >= (double)field_27123_v)
{
field_27111_r = field_27123_v - 1;
}
} else
{
field_27122_w = 0;
}
func_578_i();
func_27109_b(p_571_1_, p_571_2_, p_571_3_);
GL11.glDisable(2896);
GL11.glDisable(2929);
func_27110_k();
GL11.glEnable(2896);
GL11.glEnable(2929);
}
public void func_570_g()
{
field_27116_m = field_27114_o;
field_27115_n = field_27113_p;
double d = field_27112_q - field_27114_o;
double d1 = field_27111_r - field_27113_p;
if(d * d + d1 * d1 < 4D)
{
field_27114_o += d;
field_27113_p += d1;
} else
{
field_27114_o += d * 0.84999999999999998D;
field_27113_p += d1 * 0.84999999999999998D;
}
}
protected void func_27110_k()
{
int i = (field_951_c - field_27121_a) / 2;
int j = (field_950_d - field_27119_i) / 2;
field_6451_g.func_873_b("Achievements", i + 15, j + 5, 0x404040);
}
protected void func_27109_b(int p_27109_1_, int p_27109_2_, float p_27109_3_)
{
int i = MathHelper.func_1108_b(field_27116_m + (field_27114_o - field_27116_m) * (double)p_27109_3_);
int j = MathHelper.func_1108_b(field_27115_n + (field_27113_p - field_27115_n) * (double)p_27109_3_);
if(i < field_27126_s)
{
i = field_27126_s;
}
if(j < field_27125_t)
{
j = field_27125_t;
}
if(i >= field_27124_u)
{
i = field_27124_u - 1;
}
if(j >= field_27123_v)
{
j = field_27123_v - 1;
}
int k = field_945_b.field_6315_n.func_1070_a("/terrain.png");
int l = field_945_b.field_6315_n.func_1070_a("/achievement/bg.png");
int i1 = (field_951_c - field_27121_a) / 2;
int j1 = (field_950_d - field_27119_i) / 2;
int k1 = i1 + 16;
int l1 = j1 + 17;
field_923_k = 0.0F;
GL11.glDepthFunc(518);
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, 0.0F, -200F);
GL11.glEnable(3553);
GL11.glDisable(2896);
GL11.glEnable(32826);
GL11.glEnable(2903);
field_945_b.field_6315_n.func_1076_b(k);
int i2 = i + 288 >> 4;
int j2 = j + 288 >> 4;
int k2 = (i + 288) % 16;
int l2 = (j + 288) % 16;
Random random = new Random();
for(int i3 = 0; i3 * 16 - l2 < 155; i3++)
{
float f = 0.6F - ((float)(j2 + i3) / 25F) * 0.3F;
GL11.glColor4f(f, f, f, 1.0F);
for(int k3 = 0; k3 * 16 - k2 < 224; k3++)
{
random.setSeed(1234 + i2 + k3);
random.nextInt();
int j4 = random.nextInt(1 + j2 + i3) + (j2 + i3) / 2;
int l4 = Block.field_393_F.field_378_bb;
if(j4 > 37 || j2 + i3 == 35)
{
l4 = Block.field_403_A.field_378_bb;
} else
if(j4 == 22)
{
if(random.nextInt(2) == 0)
{
l4 = Block.field_391_ax.field_378_bb;
} else
{
l4 = Block.field_433_aO.field_378_bb;
}
} else
if(j4 == 10)
{
l4 = Block.field_388_I.field_378_bb;
} else
if(j4 == 8)
{
l4 = Block.field_386_J.field_378_bb;
} else
if(j4 > 4)
{
l4 = Block.field_338_u.field_378_bb;
} else
if(j4 > 0)
{
l4 = Block.field_336_w.field_378_bb;
}
func_550_b((k1 + k3 * 16) - k2, (l1 + i3 * 16) - l2, l4 % 16 << 4, (l4 >> 4) << 4, 16, 16);
}
}
GL11.glEnable(2929);
GL11.glDepthFunc(515);
GL11.glDisable(3553);
for(int j3 = 0; j3 < AchievementList.field_27388_e.size(); j3++)
{
Achievement achievement1 = (Achievement)AchievementList.field_27388_e.get(j3);
if(achievement1.field_25076_c == null)
{
continue;
}
int l3 = (achievement1.field_25075_a * 24 - i) + 11 + k1;
int k4 = (achievement1.field_25074_b * 24 - j) + 11 + l1;
int i5 = (achievement1.field_25076_c.field_25075_a * 24 - i) + 11 + k1;
int l5 = (achievement1.field_25076_c.field_25074_b * 24 - j) + 11 + l1;
boolean flag = field_27120_x.func_27183_a(achievement1);
boolean flag1 = field_27120_x.func_27181_b(achievement1);
char c = Math.sin(((double)(System.currentTimeMillis() % 600L) / 600D) * 3.1415926535897931D * 2D) <= 0.59999999999999998D ? '\202' : '\377';
int i8 = 0xff000000;
if(flag)
{
i8 = 0xff707070;
} else
if(flag1)
{
i8 = 65280 + (c << 24);
}
func_27100_a(l3, i5, k4, i8);
func_27099_b(i5, k4, l5, i8);
}
Achievement achievement = null;
RenderItem renderitem = new RenderItem();
RenderHelper.func_41089_c();
GL11.glDisable(2896);
GL11.glEnable(32826);
GL11.glEnable(2903);
for(int i4 = 0; i4 < AchievementList.field_27388_e.size(); i4++)
{
Achievement achievement2 = (Achievement)AchievementList.field_27388_e.get(i4);
int j5 = achievement2.field_25075_a * 24 - i;
int i6 = achievement2.field_25074_b * 24 - j;
if(j5 < -24 || i6 < -24 || j5 > 224 || i6 > 155)
{
continue;
}
if(field_27120_x.func_27183_a(achievement2))
{
float f1 = 1.0F;
GL11.glColor4f(f1, f1, f1, 1.0F);
} else
if(field_27120_x.func_27181_b(achievement2))
{
float f2 = Math.sin(((double)(System.currentTimeMillis() % 600L) / 600D) * 3.1415926535897931D * 2D) >= 0.59999999999999998D ? 0.8F : 0.6F;
GL11.glColor4f(f2, f2, f2, 1.0F);
} else
{
float f3 = 0.3F;
GL11.glColor4f(f3, f3, f3, 1.0F);
}
field_945_b.field_6315_n.func_1076_b(l);
int k6 = k1 + j5;
int j7 = l1 + i6;
if(achievement2.func_27093_f())
{
func_550_b(k6 - 2, j7 - 2, 26, 202, 26, 26);
} else
{
func_550_b(k6 - 2, j7 - 2, 0, 202, 26, 26);
}
if(!field_27120_x.func_27181_b(achievement2))
{
float f4 = 0.1F;
GL11.glColor4f(f4, f4, f4, 1.0F);
renderitem.field_27004_a = false;
}
GL11.glEnable(2896);
GL11.glEnable(2884);
renderitem.func_161_a(field_945_b.field_6314_o, field_945_b.field_6315_n, achievement2.field_27097_d, k6 + 3, j7 + 3);
GL11.glDisable(2896);
if(!field_27120_x.func_27181_b(achievement2))
{
renderitem.field_27004_a = true;
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if(p_27109_1_ >= k1 && p_27109_2_ >= l1 && p_27109_1_ < k1 + 224 && p_27109_2_ < l1 + 155 && p_27109_1_ >= k6 && p_27109_1_ <= k6 + 22 && p_27109_2_ >= j7 && p_27109_2_ <= j7 + 22)
{
achievement = achievement2;
}
}
GL11.glDisable(2929);
GL11.glEnable(3042);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
field_945_b.field_6315_n.func_1076_b(l);
func_550_b(i1, j1, 0, 0, field_27121_a, field_27119_i);
GL11.glPopMatrix();
field_923_k = 0.0F;
GL11.glDepthFunc(515);
GL11.glDisable(2929);
GL11.glEnable(3553);
super.func_571_a(p_27109_1_, p_27109_2_, p_27109_3_);
if(achievement != null)
{
String s = StatCollector.func_25200_a(achievement.func_44020_i());
String s1 = achievement.func_27090_e();
int k5 = p_27109_1_ + 12;
int j6 = p_27109_2_ - 4;
if(field_27120_x.func_27181_b(achievement))
{
int l6 = Math.max(field_6451_g.func_871_a(s), 120);
int k7 = field_6451_g.func_27277_a(s1, l6);
if(field_27120_x.func_27183_a(achievement))
{
k7 += 12;
}
func_549_a(k5 - 3, j6 - 3, k5 + l6 + 3, j6 + k7 + 3 + 12, 0xc0000000, 0xc0000000);
field_6451_g.func_27278_a(s1, k5, j6 + 12, l6, 0xffa0a0a0);
if(field_27120_x.func_27183_a(achievement))
{
field_6451_g.func_50103_a(StatCollector.func_25200_a("achievement.taken"), k5, j6 + k7 + 4, 0xff9090ff);
}
} else
{
int i7 = Math.max(field_6451_g.func_871_a(s), 120);
String s2 = StatCollector.func_25199_a("achievement.requires", new Object[] {
StatCollector.func_25200_a(achievement.field_25076_c.func_44020_i())
});
int l7 = field_6451_g.func_27277_a(s2, i7);
func_549_a(k5 - 3, j6 - 3, k5 + i7 + 3, j6 + l7 + 12 + 3, 0xc0000000, 0xc0000000);
field_6451_g.func_27278_a(s2, k5, j6 + 12, i7, 0xff705050);
}
field_6451_g.func_50103_a(s, k5, j6, field_27120_x.func_27181_b(achievement) ? achievement.func_27093_f() ? -128 : -1 : achievement.func_27093_f() ? 0xff808040 : 0xff808080);
}
GL11.glEnable(2929);
GL11.glEnable(2896);
RenderHelper.func_1159_a();
}
public boolean func_6450_b()
{
return true;
}
static
{
field_27126_s = AchievementList.field_27392_a * 24 - 112;
field_27125_t = AchievementList.field_27391_b * 24 - 112;
field_27124_u = AchievementList.field_27390_c * 24 - 77;
field_27123_v = AchievementList.field_27389_d * 24 - 77;
}
}
| sethten/MoDesserts | mcp50/temp/src/minecraft/net/minecraft/src/GuiAchievements.java | Java | gpl-3.0 | 14,368 |
/*
* Copyright (c) 2014 Amahi
*
* This file is part of Amahi.
*
* Amahi 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.
*
* Amahi 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 Amahi. If not, see <http ://www.gnu.org/licenses/>.
*/
package org.amahi.anywhere;
import android.app.Application;
import android.content.Context;
import org.amahi.anywhere.activity.AuthenticationActivity;
import org.amahi.anywhere.activity.NavigationActivity;
import org.amahi.anywhere.activity.ServerAppActivity;
import org.amahi.anywhere.activity.ServerFileAudioActivity;
import org.amahi.anywhere.activity.ServerFileImageActivity;
import org.amahi.anywhere.activity.ServerFileVideoActivity;
import org.amahi.anywhere.activity.ServerFileWebActivity;
import org.amahi.anywhere.activity.ServerFilesActivity;
import org.amahi.anywhere.fragment.ServerFileDownloadingFragment;
import org.amahi.anywhere.fragment.NavigationFragment;
import org.amahi.anywhere.fragment.ServerAppsFragment;
import org.amahi.anywhere.fragment.ServerFileImageFragment;
import org.amahi.anywhere.fragment.ServerFilesFragment;
import org.amahi.anywhere.fragment.ServerSharesFragment;
import org.amahi.anywhere.fragment.SettingsFragment;
import org.amahi.anywhere.server.ApiModule;
import org.amahi.anywhere.service.AudioService;
import org.amahi.anywhere.service.VideoService;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Application dependency injection module. Includes {@link org.amahi.anywhere.server.ApiModule} and
* provides application's {@link android.content.Context} for possible consumers.
*/
@Module(
includes = {
ApiModule.class
},
injects = {
AuthenticationActivity.class,
NavigationActivity.class,
ServerAppActivity.class,
ServerFilesActivity.class,
ServerFileAudioActivity.class,
ServerFileImageActivity.class,
ServerFileVideoActivity.class,
ServerFileWebActivity.class,
NavigationFragment.class,
ServerSharesFragment.class,
ServerAppsFragment.class,
ServerFilesFragment.class,
ServerFileImageFragment.class,
ServerFileDownloadingFragment.class,
SettingsFragment.class,
AudioService.class,
VideoService.class
}
)
class AmahiModule
{
private final Application application;
public AmahiModule(Application application) {
this.application = application;
}
@Provides
@Singleton
Context provideContext() {
return application;
}
}
| mehtamanan0/android | src/main/java/org/amahi/anywhere/AmahiModule.java | Java | gpl-3.0 | 2,855 |
/*
* 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/>.
*/
/*
* ExifTagWriteOperation.java
* Copyright (C) 2019 University of Waikato, Hamilton, NZ
*/
package adams.flow.transformer.exiftagoperation;
/**
* Interface for EXIF tag write operations.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
*/
public interface ExifTagWriteOperation<I, O>
extends ExifTagOperation<I, O> {
}
| waikato-datamining/adams-base | adams-imaging/src/main/java/adams/flow/transformer/exiftagoperation/ExifTagWriteOperation.java | Java | gpl-3.0 | 1,014 |
package org.fnppl.opensdx.security;
/*
* Copyright (C) 2010-2015
* fine people e.V. <[email protected]>
* Henning Thieß <[email protected]>
*
* http://fnppl.org
*/
/*
* Software license
*
* As far as this file or parts of this file is/are software, rather than documentation, this software-license applies / shall be applied.
*
* This file is part of openSDX
* openSDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* openSDX 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 Lesser General Public License
* and GNU General Public License along with openSDX.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* Documentation license
*
* As far as this file or parts of this file is/are documentation, rather than software, this documentation-license applies / shall be applied.
*
* This file is part of openSDX.
* Permission is granted to copy, distribute and/or modify this document
* under the terms of the GNU Free Documentation License, Version 1.3
* or any later version published by the Free Software Foundation;
* with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
* A copy of the license is included in the section entitled "GNU
* Free Documentation License" resp. in the file called "FDL.txt".
*
*/
public class SubKey extends OSDXKey {
protected MasterKey parentKey = null;
protected String parentkeyid = null;//could be the parentkey is not loaded - then *only* the id is present
protected SubKey() {
super();
super.setLevel(LEVEL_SUB);
}
//public Result uploadToKeyServer(KeyVerificator keyverificator) {
public Result uploadToKeyServer(KeyClient client) {
if (!hasPrivateKey()) {
System.out.println("uploadToKeyServer::!hasprivatekey");
return Result.error("no private key available");
}
if (!isPrivateKeyUnlocked()) {
System.out.println("uploadToKeyServer::!privatekeyunlocked");
return Result.error("private key is locked");
}
if (authoritativekeyserver.equals("LOCAL")) {
System.out.println("uploadToKeyServer::authoritativekeyserver==local");
return Result.error("authoritative keyserver can not be LOCAL");
}
//if (authoritativekeyserverPort<=0) return Result.error("authoritative keyserver port not set");
if (parentKey==null) {
System.out.println("uploadToKeyServer::parentkey==null");
return Result.error("missing parent key");
}
try {
//KeyClient client = new KeyClient(authoritativekeyserver, KeyClient.OSDX_KEYSERVER_DEFAULT_PORT, "", keyverificator);
// KeyClient client = new KeyClient(
// authoritativekeyserver,
// 80, //TODO HT 2011-06-26 check me!!!
// //KeyClient.OSDX_KEYSERVER_DEFAULT_PORT,
// "",
// keyverificator
// );
//System.out.println("Before SubKey.putSubkey...");
boolean ok = client.putSubKey(this, parentKey);
//System.out.println("AFTER SubKey.putSubkey -> "+ok);
if (ok) {
return Result.succeeded();
} else {
return Result.error(client.getMessage());
}
} catch (Exception ex) {
ex.printStackTrace();
return Result.error(ex);
}
}
public String getParentKeyID() {
if (parentKey!=null) return parentKey.getKeyID();
else return parentkeyid;
}
public void setParentKey(MasterKey parent) {
unsavedChanges = true;
parentKey = parent;
parentkeyid = parent.getKeyID();
authoritativekeyserver = parent.authoritativekeyserver;
//authoritativekeyserverPort = parent.authoritativekeyserverPort;
}
public MasterKey getParentKey() {
return parentKey;
}
public void setLevel(int level) {
if (this instanceof RevokeKey && isSub()) {
super.setLevel(LEVEL_REVOKE);
} else {
throw new RuntimeException("ERROR not allowed to set level for SubKey");
}
}
public void setParentKeyID(String id) {
unsavedChanges = true;
parentkeyid = id;
parentKey = null;
}
}
| fnppl/openSDX | src/org/fnppl/opensdx/security/SubKey.java | Java | gpl-3.0 | 4,292 |
package bpmn;
public class DataStore extends Artifact {
public DataStore() {
super();
}
public DataStore(int xPos, int yPos, String text) {
super();
setText(text);
}
public String toString() {
return "BPMN data store";
}
}
| AndreasMaring/text2model | src/bpmn/DataStore.java | Java | gpl-3.0 | 311 |
package com.fomdeveloper.planket.injection;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import com.fomdeveloper.planket.BuildConfig;
import com.fomdeveloper.planket.NetworkManager;
import com.fomdeveloper.planket.bus.RxEventBus;
import com.fomdeveloper.planket.data.PlanketDatabase;
import com.fomdeveloper.planket.data.PaginatedDataManager;
import com.fomdeveloper.planket.data.api.FlickrOauthService;
import com.fomdeveloper.planket.data.api.FlickrService;
import com.fomdeveloper.planket.data.api.oauth.OAuthManager;
import com.fomdeveloper.planket.data.api.oauth.OAuthManagerImpl;
import com.fomdeveloper.planket.data.api.oauth.OAuthToken;
import com.fomdeveloper.planket.data.prefs.PlanketBoxPreferences;
import com.fomdeveloper.planket.data.prefs.UserHelper;
import com.fomdeveloper.planket.data.repository.FlickrRepository;
import com.fomdeveloper.planket.ui.presentation.base.oauth.OauthPresenter;
import com.fomdeveloper.planket.ui.presentation.ego.EgoPresenter;
import com.fomdeveloper.planket.ui.presentation.main.MainPresenter;
import com.fomdeveloper.planket.ui.presentation.photodetail.PhotoDetailPresenter;
import com.fomdeveloper.planket.ui.presentation.profile.ProfilePresenter;
import com.fomdeveloper.planket.ui.presentation.searchphotos.SearchPresenter;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import org.mockito.Mockito;
import java.io.IOException;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
import se.akerfeldt.okhttp.signpost.SigningInterceptor;
/**
* Created by Fernando on 24/12/2016.
*/
@Module
public class MockAppModule {
/************* MOCKS *************/
@Provides @Singleton
public UserHelper provideUserHelper(){
return Mockito.mock(PlanketBoxPreferences.class);
}
@Provides @Singleton
public FlickrRepository provideFlickrRepository(){
return Mockito.mock(FlickrRepository.class);
}
@Provides @Singleton
public NetworkManager provideNetworkManager(){
return Mockito.mock(NetworkManager.class);
}
/**************************/
private Application application;
public MockAppModule(Application application) {
this.application = application;
}
@Provides @Singleton
public Context provideContext(){
return this.application;
}
@Provides @Singleton
public Gson provideGson(){
return new Gson();
}
@Provides @Singleton
public ConnectivityManager provideConnectivityManager(){
return (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
}
@Provides @Singleton
public PlanketBoxPreferences providePlanketPreferences(Context context, Gson gson){
return new PlanketBoxPreferences(context,gson);
}
@Provides @Singleton
public PlanketDatabase providePlanketDatabase(Context context){
return new PlanketDatabase(context);
}
@Provides @Singleton @Named("main_thread")
public Scheduler provideMainScheduler(){
return AndroidSchedulers.mainThread();
}
@Provides @Singleton @Named("io_thread")
public Scheduler provideIOScheduler(){
return Schedulers.io();
}
@Provides @Singleton
public RxEventBus provideRxBus(){
return new RxEventBus();
}
@Provides @Singleton
public Picasso providePicasso(Context context){
return Picasso.with(context);
}
@Provides @Named("non_oauth") @Singleton
public OkHttpClient provideOkHttpClient(OkHttpOAuthConsumer okHttpOAuthConsumer, PlanketBoxPreferences planketBoxPreferences){
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel( BuildConfig.DEBUG? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
Interceptor paramInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl url = request.url().newBuilder()
.addQueryParameter(FlickrService.PARAM_API_KEY, BuildConfig.FLICKR_API_KEY)
.addQueryParameter(FlickrService.PARAM_FORMAT,"json")
.addQueryParameter(FlickrService.PARAM_JSONCALLBACK,"1")
.build();
request = request.newBuilder().url(url).build();
return chain.proceed(request);
}
};
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.addInterceptor(paramInterceptor)
.addInterceptor(loggingInterceptor)
.addInterceptor(new SigningInterceptor(okHttpOAuthConsumer));
if (planketBoxPreferences.getAccessToken()!=null){
OAuthToken oAuthToken = planketBoxPreferences.getAccessToken();
okHttpOAuthConsumer.setTokenWithSecret(oAuthToken.getToken(),oAuthToken.getTokenSecret());
}
return okHttpClientBuilder.build();
}
@Provides @Singleton
public OkHttpOAuthConsumer provideOkHttpOAuthConsumer(){
return new OkHttpOAuthConsumer(BuildConfig.FLICKR_API_KEY, BuildConfig.FLICKR_CONSUMER_SECRET);
}
@Provides @Named("oauth") @Singleton
public OkHttpClient provideOauthOkHttpClient(OkHttpOAuthConsumer okHttpOAuthConsumer){
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel( BuildConfig.DEBUG? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
return new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(new SigningInterceptor(okHttpOAuthConsumer))
.build();
}
@Provides @Named("non_oauth") @Singleton
public Retrofit provideRetrofit(@Named("non_oauth") OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl( FlickrService.ENDPOINT )
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
@Provides @Named("oauth") @Singleton
public Retrofit provideOauthRetrofit(@Named("oauth") OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl( FlickrOauthService.ENDPOINT )
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
@Provides @Singleton
public FlickrService provideFlickrService(@Named("non_oauth") Retrofit retrofit){
return retrofit.create(FlickrService.class);
}
@Provides @Singleton
public FlickrOauthService provideFlickrOauthService(@Named("oauth") Retrofit retrofit){
return retrofit.create(FlickrOauthService.class);
}
@Provides @Singleton
public OAuthManager provideOAuthManager(FlickrOauthService flickrOauthService,OkHttpOAuthConsumer okHttpOAuthConsumer, PlanketBoxPreferences planketBoxPreferences, Context context){
return new OAuthManagerImpl(flickrOauthService,okHttpOAuthConsumer, planketBoxPreferences, context);
}
@Provides
public PaginatedDataManager providePaginatedManager(){
return new PaginatedDataManager();
}
@Provides
public MainPresenter provideMainPresenter(FlickrRepository flickrRepository, PlanketBoxPreferences planketBoxPreferences, RxEventBus rxEventBus, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new MainPresenter(flickrRepository, planketBoxPreferences, rxEventBus, mainScheduler, ioScheduler);
}
@Provides
public OauthPresenter provideFlickrLoginPresenter(OAuthManager oAuthManager, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new OauthPresenter(oAuthManager, mainScheduler, ioScheduler);
}
@Provides
public SearchPresenter provideSearchPresenter(FlickrRepository flickrRepository, PaginatedDataManager paginatedDataManager, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new SearchPresenter(flickrRepository, paginatedDataManager, mainScheduler, ioScheduler);
}
@Provides
public PhotoDetailPresenter providePhotoDetailPresenter(FlickrRepository flickrRepository, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new PhotoDetailPresenter(flickrRepository, mainScheduler, ioScheduler);
}
@Provides
public EgoPresenter provideEgoPresenter(FlickrRepository flickrRepository, PaginatedDataManager paginatedDataManager, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new EgoPresenter(flickrRepository, paginatedDataManager, mainScheduler, ioScheduler);
}
@Provides
public ProfilePresenter provideProfilePresenter(FlickrRepository flickrRepository, @Named("main_thread") Scheduler mainScheduler, @Named("io_thread") Scheduler ioScheduler){
return new ProfilePresenter(flickrRepository, mainScheduler, ioScheduler);
}
}
| FernandoOrtegaMartinez/Planket | app/src/androidTest/java/com/fomdeveloper/planket/injection/MockAppModule.java | Java | gpl-3.0 | 9,898 |
package asdf.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class Solution {
/**
* (反转单词串 ) Given an input string, reverse the string word by word.
*
* For example, Given s = "the sky is blue", return "blue is sky the".
*
* Clarification:
*
* What constitutes a word?
*
* A sequence of non-space characters constitutes a word.
*
* Could the input string contain leading or trailing spaces?
*
* Yes. However, your reversed string should not contain leading or trailing
* spaces.
*
* How about multiple spaces between two words?
*
* Reduce them to a single space in the reversed string.
*/
// 首尾空格
// 中间空格
public String reverseWords(String s) {
String[] strs = s.trim().split(" ");
StringBuffer sb = new StringBuffer();
for (int i = strs.length - 1; i > 0; i--) {
if (strs[i].length()>0&&strs[i].charAt(0)!=' ') {//空格串
sb.append(strs[i]);
sb.append(' ');
}
}
if (strs.length > 0) {
sb.append(strs[0]);
}
return sb.toString();
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.reverseWords(""));
System.out.println(solution.reverseWords(" "));
System.out.println(solution.reverseWords("the sky is blue"));
System.out.println(solution.reverseWords(" the sky is blue "));
System.out.println(solution.reverseWords(" 1"));
}
}
| asdfdypro/LeetCode | 151 Reverse Words in a String/src/asdf/test/Solution.java | Java | gpl-3.0 | 1,517 |
package com.osiykm.flist.services.programs;
import com.osiykm.flist.entities.Book;
import com.osiykm.flist.enums.BookStatus;
import com.osiykm.flist.repositories.BookRepository;
import com.osiykm.flist.services.parser.FanfictionUrlParserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/***
* @author osiykm
* created 28.09.2017 22:49
*/
@Component
@Slf4j
public class BookUpdaterProgram extends BaseProgram {
private final FanfictionUrlParserService urlParserService;
private final BookRepository bookRepository;
@Autowired
public BookUpdaterProgram(FanfictionUrlParserService urlParserService, BookRepository bookRepository) {
this.urlParserService = urlParserService;
this.bookRepository = bookRepository;
}
@Override
public void run() {
List<Book> books;
List<Book> updatedBooks;
log.info("Start update books");
books = bookRepository.findByStatusNot(BookStatus.COMPLETED);
log.info("find " + books.size() + "books for update");
updatedBooks = new ArrayList<>();
for (Book book :
books) {
if (isAlive()) {
Book updatedBook = urlParserService.getBook(book.getUrl());
updatedBooks.add(book.setSize(updatedBook.getSize()).setChapters(updatedBook.getChapters()).setStatus(updatedBook.getStatus()));
} else {
break;
}
}
log.info("updated " + updatedBooks.size() + " books");
bookRepository.save(updatedBooks);
stop();
}
}
| osiykm/flist | src/main/java/com/osiykm/flist/services/programs/BookUpdaterProgram.java | Java | gpl-3.0 | 1,723 |
/**
* Copyright (C) 2005-2013, Stefan Strömberg <[email protected]>
*
* This file is part of OpenNetHome (http://www.nethome.nu)
*
* OpenNetHome 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.
*
* OpenNetHome 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 nu.nethome.home.items.nexa;
import nu.nethome.home.item.HomeItem;
import nu.nethome.home.item.HomeItemType;
import nu.nethome.home.items.RemapButton;
import nu.nethome.home.system.Event;
import nu.nethome.util.plugin.Plugin;
/**
* @author Stefan
*/
@SuppressWarnings("UnusedDeclaration")
@Plugin
@HomeItemType(value = "Controls", creationEvents = "Nexa_Message")
public class NexaRemapButton extends RemapButton implements HomeItem {
private static final String MODEL = ("<?xml version = \"1.0\"?> \n"
+ "<HomeItem Class=\"NexaRemapButton\" Category=\"Controls\" >"
+ " <Attribute Name=\"State\" Type=\"String\" Get=\"getState\" Init=\"setState\" Default=\"true\" />"
+ " <Attribute Name=\"HouseCode\" Type=\"StringList\" Get=\"getHouseCode\" Set=\"setHouseCode\" >"
+ " <item>A</item> <item>B</item> <item>C</item> <item>D</item> <item>E</item> <item>F</item> <item>G</item> <item>H</item> </Attribute>"
+ " <Attribute Name=\"Button\" Type=\"StringList\" Get=\"getButton\" Set=\"setButton\" >"
+ " <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> <item>8</item> </Attribute>"
+ " <Attribute Name=\"OnCommand\" Type=\"Command\" Get=\"getOnCommand\" Set=\"setOnCommand\" />"
+ " <Attribute Name=\"OffCommand\" Type=\"Command\" Get=\"getOffCommand\" Set=\"setOffCommand\" />"
+ " <Attribute Name=\"HoldOffTime\" Type=\"StringList\" Get=\"getHoldOffTime\" Set=\"setHoldOffTime\" >"
+ " <item>0</item> <item>100</item> <item>150</item> <item>200</item> <item>300</item> <item>400</item> </Attribute>"
+ " <Action Name=\"on\" Method=\"on\" />"
+ " <Action Name=\"off\" Method=\"off\" />"
+ " <Action Name=\"enable\" Method=\"enable\" />"
+ " <Action Name=\"disable\" Method=\"disable\" />"
+ "</HomeItem> ");
// Public attributes
private int buttonHouseCode = 0;
private int buttonNumber = 1;
public NexaRemapButton() {
}
public boolean receiveEvent(Event event) {
// Check the event and see if they affect our current state.
if (event.getAttribute(Event.EVENT_TYPE_ATTRIBUTE).equals("Nexa_Message") &&
event.getAttribute("Direction").equals("In") &&
(event.getAttributeInt("Nexa.HouseCode") == buttonHouseCode) &&
(event.getAttributeInt("Nexa.Button") == buttonNumber)) {
processEvent(event);
return true;
} else {
return handleInit(event);
}
}
@Override
protected boolean initAttributes(Event event) {
buttonHouseCode = event.getAttributeInt("Nexa.HouseCode");
buttonNumber = event.getAttributeInt("Nexa.Button");
return true;
}
@Override
protected void actOnEvent(Event event) {
if (event.getAttribute("Nexa.Command").equals("1")) {
this.on();
} else {
this.off();
}
}
public String getModel() {
return MODEL;
}
/**
* @return Returns the deviceCode.
*/
@SuppressWarnings("UnusedDeclaration")
public String getButton() {
return Integer.toString(buttonNumber);
}
/**
* @param deviceCode The deviceCode to set.
*/
@SuppressWarnings("UnusedDeclaration")
public void setButton(String deviceCode) {
try {
int result = Integer.parseInt(deviceCode);
if ((result > 0) && (result <= 8)) {
buttonNumber = result;
}
} catch (NumberFormatException e) {
// Ignore
}
}
/**
* @return Returns the houseCode.
*/
@SuppressWarnings("UnusedDeclaration")
public String getHouseCode() {
if ((buttonHouseCode >= 0) && (buttonHouseCode <= 7)) {
return Character.toString("ABCDEFGH".charAt(buttonHouseCode));
}
return "A";
}
/**
* @param houseCode The HouseCode to set.
*/
@SuppressWarnings("UnusedDeclaration")
public void setHouseCode(String houseCode) {
String hc = houseCode.toUpperCase();
if ((hc.length() == 1) && (hc.compareTo("A") >= 0) &&
(hc.compareTo("H") <= 0)) {
buttonHouseCode = (int) hc.charAt(0) - (int) 'A';
}
}
}
| SourceCodeSourcerer/NetHomeServer | home-items/rf-items/src/main/java/nu/nethome/home/items/nexa/NexaRemapButton.java | Java | gpl-3.0 | 5,234 |
/***************************************************************************
* Project file: NPlugins - NTalk - TimedFilter.java *
* Full Class name: fr.ribesg.bukkit.ntalk.filter.bean.TimedFilter *
* *
* Copyright (c) 2012-2015 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.bukkit.ntalk.filter.bean;
import fr.ribesg.bukkit.ntalk.filter.ChatFilterResult;
import java.util.Map;
/**
* @author Ribesg
*/
public abstract class TimedFilter extends Filter {
private final long duration;
protected TimedFilter(final String outputString, final String filteredString, final boolean regex, final ChatFilterResult responseType, final long duration) {
super(outputString, filteredString, regex, responseType);
this.duration = duration;
}
public long getDuration() {
return this.duration;
}
// ############ //
// ## Saving ## //
// ############ //
@Override
public Map<String, Object> getConfigMap() {
final Map<String, Object> map = super.getConfigMap();
map.put("duration", this.duration);
return map;
}
}
| Ribesg/NPlugins | NTalk/src/main/java/fr/ribesg/bukkit/ntalk/filter/bean/TimedFilter.java | Java | gpl-3.0 | 1,459 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.projectzombie.regionrotation.modules;
import com.sk89q.worldguard.bukkit.WGBukkit;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.util.UUID;
/**
* Parent class for modules to store their world and respective WorldGuard
* region manager.
*
* @author Jesse Bannon ([email protected])
*/
public abstract class RegionWorld
{
private final UUID worldUID;
private final boolean isValid;
protected RegionWorld(final UUID worldUID)
{
this.worldUID = worldUID;
this.isValid = this.getWorld() != null && getRegionManager() != null;
}
/** @return Whether the object is valid for use or not. */
protected boolean isValid() { return this.isValid; }
protected UUID getWorldUID() { return this.worldUID; }
protected World getWorld() { return Bukkit.getWorld(worldUID); }
protected LocalWorld getLocalWorld() { return com.sk89q.worldedit.bukkit.BukkitUtil.getLocalWorld(this.getWorld()); }
protected RegionManager getRegionManager() { return WGBukkit.getRegionManager(getWorld()); }
}
| jmbannon/RegionRotation | src/main/java/net/projectzombie/regionrotation/modules/RegionWorld.java | Java | gpl-3.0 | 1,404 |
package com.plutomc.power.common.blocks;
import com.plutomc.core.common.blocks.BlockMetal;
import com.plutomc.power.Power;
import com.plutomc.power.common.tileentities.TileEntityCombustionEngine;
import com.plutomc.power.init.BlockRegistry;
import com.plutomc.power.init.GuiHandler;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* plutomc_power
* Copyright (C) 2016 Kevin Boxhoorn
*
* plutomc_power 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.
*
* plutomc_power 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 plutomc_power. If not, see <http://www.gnu.org/licenses/>.
*/
public class BlockCombustionEngine extends BlockMetal implements ITileEntityProvider
{
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
public BlockCombustionEngine()
{
super(BlockRegistry.Data.COMBUSTION_ENGINE);
setDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
}
@Nonnull
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, FACING);
}
@Nonnull
@Override
public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand)
{
return getDefaultState().withProperty(FACING, placer.getHorizontalFacing().getOpposite());
}
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta)
{
return getDefaultState().withProperty(FACING, EnumFacing.getFront(meta));
}
@Override
public int getMetaFromState(IBlockState state)
{
return state.getValue(FACING).getIndex();
}
@Nullable
@Override
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileEntityCombustionEngine();
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
TileEntity tileEntity = worldIn.getTileEntity(pos);
if (tileEntity instanceof TileEntityCombustionEngine)
{
InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityCombustionEngine) tileEntity);
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@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)
{
playerIn.openGui(Power.instance(), GuiHandler.ENGINE_COMBUSTION, worldIn, pos.getX(), pos.getY(), pos.getZ());
}
return true;
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
TileEntity tileEntity = worldIn.getTileEntity(pos);
if (tileEntity instanceof TileEntityCombustionEngine)
{
((TileEntityCombustionEngine) tileEntity).setCustomName(stack.getDisplayName());
}
}
}
| plutomc/power | src/main/java/com/plutomc/power/common/blocks/BlockCombustionEngine.java | Java | gpl-3.0 | 3,925 |
package nl.jappieklooster;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Wraps arround the java.util.logging.Logger, just to save some typing time. & it makes all the
* loging go trough here so sutting it down is easy
*
* @author jappie
*/
public class Log {
private static final Logger LOGGER = Logger.getLogger("Logger");
private static final Level LOG_LEVEL = Level.FINER;
static {
LOGGER.setLevel(LOG_LEVEL);
ConsoleHandler handler = new ConsoleHandler();
// PUBLISH this level
handler.setLevel(LOG_LEVEL);
LOGGER.addHandler(handler);
}
// no initilization of this class allowed
private Log() {
}
private static void write(Level severity, String message, Object... params) {
LOGGER.log(severity, message, params);
}
private static void write(Level severity, String message) {
LOGGER.log(severity, message);
}
private static void write(String message) {
write(Level.INFO, message);
}
public static void debug(String message) {
write(Level.FINER, message);
}
public static void verbose(String message) {
write(Level.FINEST, message);
}
public static void write(String message, Object... params) {
write(Level.INFO, message, params);
}
public static void debug(String message, Object... params) {
write(Level.FINER, message, params);
}
public static void verbose(String message, Object... params) {
write(Level.FINEST, message, params);
}
public static void panic(String message, Object... params) {
write(Level.SEVERE, message, params);
}
public static void panic(String message) {
write(Level.SEVERE, message);
}
public static void warn(String message, Object... params) {
write(Level.WARNING, message, params);
}
public static void warn(String message) {
write(Level.WARNING, message);
}
}
| jappeace/hw-isad2gp-groovy | src/nl/jappieklooster/Log.java | Java | gpl-3.0 | 1,848 |
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import edu.pitt.isg.Converter;
import edu.pitt.isg.dc.TestConvertDatsToJava;
import edu.pitt.isg.dc.WebApplication;
import edu.pitt.isg.dc.entry.Entry;
import edu.pitt.isg.dc.entry.EntryService;
import edu.pitt.isg.dc.entry.classes.EntryView;
import edu.pitt.isg.dc.entry.classes.IsAboutItems;
import edu.pitt.isg.dc.entry.classes.PersonOrganization;
import edu.pitt.isg.dc.repository.utils.ApiUtil;
import edu.pitt.isg.dc.utils.DatasetFactory;
import edu.pitt.isg.dc.utils.DatasetFactoryPerfectTest;
import edu.pitt.isg.dc.utils.ReflectionFactory;
import edu.pitt.isg.dc.validator.*;
import edu.pitt.isg.mdc.dats2_2.Dataset;
import edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity;
import edu.pitt.isg.mdc.dats2_2.Type;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.*;
import static edu.pitt.isg.dc.validator.ValidatorHelperMethods.validatorErrors;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebApplication.class})
@TestPropertySource("/application.properties")
public class DatasetValidatorTest {
public static final java.lang.reflect.Type mapType = new TypeToken<TreeMap<String, Object>>() {
}.getType();
private final Converter converter = new Converter();
Gson gson = new GsonBuilder().serializeNulls().enableComplexMapKeySerialization().create();
@Autowired
private ApiUtil apiUtil;
@Autowired
private EntryService repo;
private WebFlowReflectionValidator webFlowReflectionValidator = new WebFlowReflectionValidator();
@Test
public void testEmptyDataset() {
Dataset dataset = new Dataset();
}
private Dataset createTestDataset(Long entryId) {
Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId);
EntryView entryView = new EntryView(entry);
Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class);
DatasetFactory datasetFactory = new DatasetFactory(true);
dataset = datasetFactory.createDatasetForWebFlow(dataset);
// Dataset dataset = (Dataset) ReflectionFactory.create(Dataset.class);
//make your dataset here
return dataset;
}
private Dataset createPerfectDataset() {
return DatasetFactoryPerfectTest.createDatasetForWebFlow(null);
}
private List<ValidatorError> test(Dataset dataset) {
//don't have to do this yet
String breadcrumb = "";
List<ValidatorError> errors = new ArrayList<>();
try {
ReflectionValidator reflectionValidator = new ReflectionValidator();
reflectionValidator.validate(Dataset.class, dataset, true, breadcrumb, null, errors);
//somehow "expect" error messages....
} catch (Exception e) {
e.printStackTrace();
fail();
}
return validatorErrors(errors);
}
@Test
public void testPerfectDatasetWithAllPossibleFields() {
Dataset dataset = createPerfectDataset();
List<ValidatorError> errors = test(dataset);
assertTrue(errors.isEmpty());
}
@Test
public void testPerfectDatasetForceErrors() {
Dataset dataset = createPerfectDataset();
dataset.setTitle(null);
ListIterator<? extends Type> iterator = dataset.getTypes().listIterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
dataset.getStoredIn().setName(null);
((PersonOrganization) dataset.getCreators().get(1)).setName(null);
dataset.getDistributions().get(0).getAccess().setLandingPage(null);
dataset.getDistributions().get(0).getDates().get(0).getType().setValue(null);
dataset.getDistributions().get(0).getDates().get(0).getType().setValueIRI(null);
dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValue(null);
dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValueIRI(null);
dataset.getLicenses().get(0).setName(null);
((PersonOrganization) dataset.getCreators().get(0)).getAffiliations().get(0).getLocation().getIdentifier().setIdentifierSource(null);
dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setName(null);
DatasetFactory datasetFactory = new DatasetFactory(true);
dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setFunders(datasetFactory.createPersonComprisedEntityList(null));
((IsAboutItems) dataset.getIsAbout().get(0)).setName(null);
dataset.getProducedBy().setName(null);
dataset.getProducedBy().getEndDate().setDate(null);
List<ValidatorError> errors = test(dataset);
if (!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->title");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(1).getPath(), "(root)->types");
assertEquals(errors.get(1).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(2).getPath(), "(root)->creators->0->affiliations->0->location->identifier->identifierSource");
assertEquals(errors.get(2).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(3).getPath(), "(root)->creators->1->name");
assertEquals(errors.get(3).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(4).getPath(), "(root)->storedIn->name");
assertEquals(errors.get(4).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(5).getPath(), "(root)->distributions->0->access->landingPage");
assertEquals(errors.get(5).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(6).getPath(), "(root)->distributions->0->dates->0->type");
assertEquals(errors.get(6).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(7).getPath(), "(root)->distributions->0->conformsTo->0->type");
assertEquals(errors.get(7).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(8).getPath(), "(root)->primaryPublications->0->acknowledges->0->name");
assertEquals(errors.get(8).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(9).getPath(), "(root)->primaryPublications->0->acknowledges->0->funders");
assertEquals(errors.get(9).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(10).getPath(), "(root)->producedBy->name");
assertEquals(errors.get(10).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(11).getPath(), "(root)->producedBy->endDate->date");
assertEquals(errors.get(11).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(12).getPath(), "(root)->licenses->0->name");
assertEquals(errors.get(12).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertEquals(errors.get(13).getPath(), "(root)->isAbout->0->name");
assertEquals(errors.get(13).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced.");
}
/*
@Test
public void testDatasetWithoutTitleOnly() throws Exception {
// Dataset dataset = createTestDataset(566L);
Dataset dataset = createPerfectDataset();
dataset.setTitle(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->title");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Title");
}
@Test
public void testDatasetCreatorOrganizationNameMissing() {
Dataset dataset = createPerfectDataset();
((PersonOrganization) dataset.getCreators().get(1)).setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->creators->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Creator Organization name.");
}
*/
@Test
public void testDatasetWithoutCreatorsOnly() {
Dataset dataset = createPerfectDataset();
ListIterator<? extends PersonComprisedEntity> iterator = dataset.getCreators().listIterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
List<ValidatorError> errors = test(dataset);
if (!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->creators");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Creators");
}
/*
@Test
public void testDatasetWithoutTyesOnly() {
Dataset dataset = createPerfectDataset();
ListIterator<? extends Type> iterator = dataset.getTypes().listIterator();
while (iterator.hasNext()) {
Type type = iterator.next();
iterator.remove();
}
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->types");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Types");
}
@Test
public void testDatasetWithoutStoredInName() {
Dataset dataset = createPerfectDataset();
dataset.getStoredIn().setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->storedIn->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing StoredIn (Data Repository) name.");
}
*/
@Test
public void testDatasetWithoutDistributionAccess() {
Dataset dataset = createPerfectDataset();
dataset.getDistributions().get(0).setAccess(null);
List<ValidatorError> errors = test(dataset);
if (!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->distributions->0->access");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for empty Distribution Access.");
}
/*
@Test
public void testDatasetWithoutDistributionAccessLandingPage() {
Dataset dataset = createPerfectDataset();
dataset.getDistributions().get(0).getAccess().setLandingPage(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->distributions->access->landingPage");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for empty Distribution Access LandingPage.");
}
@Test
public void testPerfectDatasetExceptLicenseIsMissingName() {
Dataset dataset = createPerfectDataset();
dataset.getLicenses().get(0).setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->licenses->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for empty License name.");
}
@Test
public void testDatasetWithoutIdentifierSource() {
Dataset dataset = createPerfectDataset();
((PersonOrganization) dataset.getCreators().get(0)).getAffiliations().get(0).getLocation().getIdentifier().setIdentifierSource(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->creators->affiliations->location->identifier->identifierSource");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing IdenfifierSource");
}
@Test
public void testDatasetWithoutDatesAnnotation() {
Dataset dataset = createPerfectDataset();
dataset.getDistributions().get(0).getDates().get(0).getType().setValue(null);
dataset.getDistributions().get(0).getDates().get(0).getType().setValueIRI(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->distributions->dates->type");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Types");
}
@Test
public void testDatasetWithoutPrimaryPublicationsAcknowledgesName() {
Dataset dataset = createPerfectDataset();
dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->primaryPublications->acknowledges->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing name");
}
@Test
public void testDatasetWithoutPrimaryPublicationsAcknowledgesFunders() {
Dataset dataset = createPerfectDataset();
dataset.getPrimaryPublications().get(0).getAcknowledges().get(0).setFunders(DatasetFactory.createPersonComprisedEntityList(null));
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->primaryPublications->acknowledges->funders");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Funders");
}
@Test
public void testDatasetWithoutIsAboutBiologicalEntityName() {
Dataset dataset = createPerfectDataset();
((IsAboutItems) dataset.getIsAbout().get(0)).setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->isAbout->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing IsAbout (Biological Entity) name");
}
@Test
public void testDatasetWithoutStudyName() {
Dataset dataset = createPerfectDataset();
dataset.getProducedBy().setName(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->producedBy->name");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing name of Produced By");
}
@Test
public void testDatasetWithoutDate() {
Dataset dataset = createPerfectDataset();
dataset.getProducedBy().getEndDate().setDate(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->producedBy->endDate->date");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing End Date for Produced By");
}
@Test
public void testDatasetWithoutDistributionConformsToTypes() {
Dataset dataset = createPerfectDataset();
dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValue(null);
dataset.getDistributions().get(0).getConformsTo().get(0).getType().setValueIRI(null);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
assertEquals(errors.get(0).getPath(), "(root)->distributions->conformsTo->type");
assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
} else fail("No error messages produced for missing Types");
}
*/
/*
@Test
public void testRealDataset() {
Dataset dataset = createTestDataset(86L);
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()) {
// assertEquals(errors.get(0).getPath(), "(root)->isAbout->name");
// assertEquals(errors.get(0).getErrorType(), ValidatorErrorType.NULL_VALUE_IN_REQUIRED_FIELD);
assertTrue(false);
} else assertTrue(true);
}
*/
/*
@Test
public void testValidationErrorsByDataset() {
Set<String> types = new HashSet<>();
types.add(Dataset.class.getTypeName());
List<Entry> entriesList = repo.filterEntryIdsByTypes(types);
Map<Dataset, List<ValidatorError>> datasetErrorListMap = new HashMap<Dataset, List<ValidatorError>>();
for (Entry entry : entriesList) {
Dataset dataset = createTestDataset(entry.getId().getEntryId());
List<ValidatorError> errors = test(dataset);
if(!errors.isEmpty()){
datasetErrorListMap.put(dataset,errors);
}
}
if(datasetErrorListMap.isEmpty()) {
assertTrue(true);
} else fail("Errors were found!");
}
*/
@Test
public void testValidationErrorCountByBreadcrumbForAllDatasets() {
Set<String> types = new HashSet<>();
types.add(Dataset.class.getTypeName());
List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types);
Map<String, Integer> errorPathCount = new HashMap<String, Integer>();
for (Entry entry : entriesList) {
// System.out.println(entry.getId().getEntryId());
Dataset dataset = createTestDataset(entry.getId().getEntryId());
List<ValidatorError> errors = test(dataset);
if (!errors.isEmpty()) {
for (ValidatorError error : errors) {
if (errorPathCount.containsKey(error.getPath())) {
errorPathCount.put(error.getPath(), errorPathCount.get(error.getPath()) + 1);
} else errorPathCount.put(error.getPath(), 1);
}
}
}
assertEquals(errorPathCount.size(), 0);
}
@Test
public void testGetEntryIdByErrorBreadcrumbForAllDatasets() {
Set<String> types = new HashSet<>();
types.add(Dataset.class.getTypeName());
List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types);
Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>();
for (Entry entry : entriesList) {
Dataset dataset = createTestDataset(entry.getId().getEntryId());
List<ValidatorError> errors = test(dataset);
if (!errors.isEmpty()) {
for (ValidatorError error : errors) {
if (errorPathForEntryIds.containsKey(error.getPath())) {
errorPathForEntryIds.get(error.getPath()).add(entry.getId().getEntryId());
} else {
ArrayList<Long> longList = new ArrayList<Long>();
longList.add(entry.getId().getEntryId());
errorPathForEntryIds.put(error.getPath(), longList);
}
}
}
}
assertEquals(errorPathForEntryIds.size(), 0);
}
private String sortJsonObject(JsonObject jsonObject) {
List<String> jsonElements = new ArrayList<>();
Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entries)
jsonElements.add(entry.getKey());
Collections.sort(jsonElements);
JsonArray jsonArray = new JsonArray();
for (String elementName : jsonElements) {
JsonObject newJsonObject = new JsonObject();
JsonElement jsonElement = jsonObject.get(elementName);
if (jsonElement.isJsonObject())
newJsonObject.add(elementName, new JsonPrimitive(sortJsonObject(jsonObject.get(elementName).getAsJsonObject())));
else if (jsonElement.isJsonArray()) {
newJsonObject.add(elementName, sortJsonArray(jsonElement));
} else
newJsonObject.add(elementName, jsonElement);
jsonArray.add(newJsonObject);
}
return jsonArray.toString();
}
private JsonArray sortJsonArray(JsonElement jsonElement) {
JsonArray sortedArray = new JsonArray();
JsonArray jsonElementAsArray = jsonElement.getAsJsonArray();
for (JsonElement arrayMember : jsonElementAsArray)
if (arrayMember.isJsonObject()) {
sortedArray.add(new JsonPrimitive(sortJsonObject(arrayMember.getAsJsonObject())));
} else if (arrayMember.isJsonArray()) {
sortedArray.add(sortJsonArray(arrayMember));
} else {
sortedArray.add(arrayMember.toString());
}
return sortedArray;
}
/*
@Test
public void testDatasetCreationComparision() {
Long entryId = 566L;
Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId);
EntryView entryView = new EntryView(entry);
Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class);
Dataset datasetJohn = null;
Dataset datasetJeff = null;
try {
datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, dataset);
//Reflection Factory
// datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, createTestDataset(entryId));
//Dataset Factory
datasetJeff = createTestDataset(entryId);
// datasetJeff = DatasetFactory.createDatasetForWebFlow(null);
} catch (Exception e) {
e.printStackTrace();
fail();
}
assertTrue(datasetComparision(datasetJohn, datasetJeff, entry));
datasetJeff.getDistributions().get(0).getDates().get(4);
datasetJohn.getDistributions().get(0).getDates().get(4);
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
String xmlJohn = xstream.toXML(datasetJohn).
replaceAll("edu.pitt.isg.dc.utils.ReflectionFactoryElementFactory", "org.springframework.util.AutoPopulatingList\\$ReflectiveElementFactory").
replaceAll("dats2_2", "dats2__2");
String xmlJeff = xstream.toXML(datasetJeff).
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDateWrapper", "edu.pitt.isg.mdc.dats2_2.Date").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedOrganizationWrapper", "edu.pitt.isg.mdc.dats2_2.Organization").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPersonComprisedEntityWrapper", "edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedLicenseWrapper", "edu.pitt.isg.mdc.dats2_2.License").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedAccessWrapper", "edu.pitt.isg.mdc.dats2_2.Access").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPlaceWrapper", "edu.pitt.isg.mdc.dats2_2.Place").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedTypeWrapper", "edu.pitt.isg.mdc.dats2_2.Type").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDistributionWrapper", "edu.pitt.isg.mdc.dats2_2.Distribution").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedGrantWrapper", "edu.pitt.isg.mdc.dats2_2.Grant").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPublicationWrapper", "edu.pitt.isg.mdc.dats2_2.Publication").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedIsAboutWrapper", "edu.pitt.isg.mdc.dats2_2.IsAbout").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedCategoryValuePairWrapper", "edu.pitt.isg.mdc.dats2_2.CategoryValuePair").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDataStandardWrapper", "edu.pitt.isg.mdc.dats2_2.DataStandard").
replaceAll("dats2_2", "dats2__2");
assertEquals(xmlJeff, xmlJohn);
}
*/
@Test
public void testDatasetCreationComparisionForAllDatasets() {
Set<String> types = new HashSet<>();
types.add(Dataset.class.getTypeName());
List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types);
Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>();
for (Entry entry : entriesList) {
EntryView entryView = new EntryView(entry);
Dataset dataset = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class);
Dataset datasetJohn = null;
Dataset datasetJeff = null;
try {
//Reflection Factory
datasetJohn = (Dataset) ReflectionFactory.create(Dataset.class, dataset);
//Dataset Factory
datasetJeff = createTestDataset(entryView.getId().getEntryId());
} catch (Exception e) {
e.printStackTrace();
fail();
}
assertTrue(datasetComparision(datasetJohn, datasetJeff, entry));
// datasetJeff.getDistributions().get(0).getDates().get(4);
// datasetJohn.getDistributions().get(0).getDates().get(4);
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
String xmlJohn = xstream.toXML(datasetJohn).
replaceAll("edu.pitt.isg.dc.utils.ReflectionFactoryElementFactory", "org.springframework.util.AutoPopulatingList\\$ReflectiveElementFactory").
replaceAll("dats2_2", "dats2__2");
String xmlJeff = xstream.toXML(datasetJeff).
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDateWrapper", "edu.pitt.isg.mdc.dats2_2.Date").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedOrganizationWrapper", "edu.pitt.isg.mdc.dats2_2.Organization").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPersonComprisedEntityWrapper", "edu.pitt.isg.mdc.dats2_2.PersonComprisedEntity").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedLicenseWrapper", "edu.pitt.isg.mdc.dats2_2.License").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedAccessWrapper", "edu.pitt.isg.mdc.dats2_2.Access").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPlaceWrapper", "edu.pitt.isg.mdc.dats2_2.Place").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedTypeWrapper", "edu.pitt.isg.mdc.dats2_2.Type").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDistributionWrapper", "edu.pitt.isg.mdc.dats2_2.Distribution").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedGrantWrapper", "edu.pitt.isg.mdc.dats2_2.Grant").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedPublicationWrapper", "edu.pitt.isg.mdc.dats2_2.Publication").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedIsAboutWrapper", "edu.pitt.isg.mdc.dats2_2.IsAbout").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedCategoryValuePairWrapper", "edu.pitt.isg.mdc.dats2_2.CategoryValuePair").
replaceAll("edu.pitt.isg.dc.utils.AutoPopulatedWrapper.AutoPopulatedDataStandardWrapper", "edu.pitt.isg.mdc.dats2_2.DataStandard").
replaceAll("dats2_2", "dats2__2");
assertEquals(xmlJeff, xmlJohn); }
}
public Boolean datasetComparision(Dataset datasetLeft, Dataset datasetRight, Entry entry) {
Class clazz = Dataset.class;
//issues with converter.toJsonObject -- with regards to isAbout and PersonComprisedEntity
//for example PeronComprisedEntity is only returning identifier and alternateIdentifier; isAbout isn't returning anything
JsonObject jsonObjectFromDatabaseLeft = converter.toJsonObject(clazz, datasetLeft);
JsonObject jsonObjectFromDatabaseRight = converter.toJsonObject(clazz, datasetRight);
Map<String, Object> databaseMapLeft = gson.fromJson(jsonObjectFromDatabaseLeft, mapType);
Map<String, Object> databaseMapRight = gson.fromJson(jsonObjectFromDatabaseRight, mapType);
MapDifference<String, Object> d = Maps.difference(databaseMapLeft, databaseMapRight);
if (datasetLeft.equals(datasetRight) && d.areEqual()) {
return true;
} else {
if (!d.toString().equalsIgnoreCase("equal")) {
if (d.entriesOnlyOnLeft().size() > 0) {
System.out.print("Entry " + jsonObjectFromDatabaseRight.get("title") + " (" + entry.getId().getEntryId() + "), Left contains");
Iterator<String> it = d.entriesOnlyOnLeft().keySet().iterator();
while (it.hasNext()) {
String field = it.next();
System.out.print(" " + field + ",");
}
System.out.print(" but Right does not.\n");
}
if (d.entriesOnlyOnRight().size() > 0) {
System.out.print("Entry " + jsonObjectFromDatabaseRight.get("title") + " (" + entry.getId().getEntryId() + "), Right contains");
Iterator<String> it = d.entriesOnlyOnRight().keySet().iterator();
while (it.hasNext()) {
String field = it.next();
System.out.print(" " + field + ",");
}
System.out.print(" but Left does not.\n");
}
if (d.entriesDiffering().size() > 0) {
Iterator<String> it = d.entriesDiffering().keySet().iterator();
while (it.hasNext()) {
String value = it.next();
String left;
if (jsonObjectFromDatabaseLeft.get(value).isJsonArray()) {
left = sortJsonObject(jsonObjectFromDatabaseLeft.get(value).getAsJsonArray().get(0).getAsJsonObject());
} else {
left = sortJsonObject(jsonObjectFromDatabaseLeft.get(value).getAsJsonObject());
}
String right;
if (jsonObjectFromDatabaseRight.get(value).isJsonArray()) {
right = sortJsonObject(jsonObjectFromDatabaseRight.get(value).getAsJsonArray().get(0).getAsJsonObject());
} else {
right = sortJsonObject(jsonObjectFromDatabaseRight.get(value).getAsJsonObject());
}
if (!left.equals(right)) {
int idxOfDifference = TestConvertDatsToJava.indexOfDifference(left, right);
try {
System.out.println("In " + value + " section from Left: ...\n" + left.substring(0, idxOfDifference) + Converter.ANSI_CYAN + left.substring(idxOfDifference, left.length()) + Converter.ANSI_RESET);
System.out.println("In " + value + " section from Right: ...\n" + right.substring(0, idxOfDifference) + Converter.ANSI_CYAN + right.substring(idxOfDifference, right.length()) + Converter.ANSI_RESET);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("idxOfDifference:" + idxOfDifference);
// System.out.println("end:" + end);
throw e;
}
} else {
System.out.println(d);
}
}
}
}
return false;
}
}
/*
@Test
public void testCleanseSingleDataset(){
Long entryId = 566L;
Entry entry = apiUtil.getEntryByIdIncludeNonPublic(entryId);
EntryView entryView = new EntryView(entry);
//create and clean datasetOriginal -- remove Emtpy Strings
Dataset datasetOriginal = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class);
try {
datasetOriginal = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, datasetOriginal);
} catch (FatalReflectionValidatorException e) {
e.printStackTrace();
}
//create and run dataset through Factory
Dataset dataset = new Dataset();
try {
dataset = (Dataset) ReflectionFactory.create(Dataset.class, datasetOriginal);
// dataset = createTestDataset(entry.getId().getEntryId());
} catch (Exception e) {
e.printStackTrace();
fail();
}
//clean dataset
try {
dataset = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, dataset);
} catch (FatalReflectionValidatorException e) {
e.printStackTrace();
}
//compare original (cleaned) with dataset ran through Factory and cleaned
assertTrue(datasetComparision(datasetOriginal, dataset, entry));
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
String xmlCleansed = xstream.toXML(dataset);
String xmlOriginal = xstream.toXML(datasetOriginal);
assertEquals(xmlOriginal, xmlCleansed);
}
*/
@Test
public void testCleanseForAllDatasets() {
Set<String> types = new HashSet<>();
types.add(Dataset.class.getTypeName());
List<Entry> entriesList = repo.filterEntryIdsByTypesMaxRevisionID(types);
Map<String, List<Long>> errorPathForEntryIds = new HashMap<String, List<Long>>();
for (Entry entry : entriesList) {
EntryView entryView = new EntryView(entry);
//create and clean datasetOriginal -- remove Emtpy Strings
Dataset datasetOriginal = (Dataset) converter.fromJson(entryView.getUnescapedEntryJsonString(), Dataset.class);
try {
datasetOriginal = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, datasetOriginal, true, true);
} catch (FatalReflectionValidatorException e) {
e.printStackTrace();
}
//create and run dataset through Factory
Dataset dataset = new Dataset();
try {
dataset = (Dataset) ReflectionFactory.create(Dataset.class, datasetOriginal);
// dataset = createTestDataset(entry.getId().getEntryId());
} catch (Exception e) {
e.printStackTrace();
fail();
}
//clean dataset
try {
dataset = (Dataset) webFlowReflectionValidator.cleanse(Dataset.class, dataset, true, true);
} catch (FatalReflectionValidatorException e) {
e.printStackTrace();
}
//compare original (cleaned) with dataset ran through Factory and cleaned
assertTrue(datasetComparision(datasetOriginal, dataset, entry));
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
String xmlCleansed = xstream.toXML(dataset);
String xmlOriginal = xstream.toXML(datasetOriginal);
assertEquals(xmlOriginal, xmlCleansed);
}
}
}
| midas-isg/digital-commons | src/test/java/DatasetValidatorTest.java | Java | gpl-3.0 | 37,788 |
package com.success.txn.jpa.repos;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import com.success.txn.jpa.entities.Student;
@Repository
@Transactional(isolation = Isolation.REPEATABLE_READ)
public class RepetableReadRepo {
@Autowired private EntityManager em;
private static final Logger logger = LoggerFactory.getLogger(RepetableReadRepo.class);
public String insertOne() {
Student s = new Student();
String address = "" + new Date();
s.setName(address);
s.setAddress(address);
em.persist(s);
logger.info("new row inserted with address {}", address);
Student s1 = em.find(Student.class, 1);
logger.info("new name for student 1 {}", address);
s1.setName(address);
sleep(2000);
logger.info("awoke");
return address;
}
public String getCount() {
// when this method and insertOne are executed in parallel in two different txn, this code
// executed but data stayed same (even after the insertOne is completed before "after sleep" lines
// are execcted)
// meaning the data modified by insertOne did not reflect in this method (even after the
// insertOne txn is completed before this)
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Student.class)));
logger.info("total rows before sleep {}", em.createQuery(cq).getSingleResult());
sleep(10000);
logger.info("total rows after sleep {}", em.createQuery(cq).getSingleResult());
logger.info("name of the student 1 {}", em.find(Student.class, 1).getName());
return "total rows " + em.createQuery(cq).getSingleResult();
}
private void sleep(long seconds) {
try {
Thread.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| btamilselvan/tamils | springtxn/src/main/java/com/success/txn/jpa/repos/RepetableReadRepo.java | Java | gpl-3.0 | 2,233 |
/*
* Copyright (c) 2011 Nicholas Okunew
* All rights reserved.
*
* This file is part of the com.atomicleopard.webelemental library
*
* The com.atomicleopard.webelemental library is free software: you
* can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* The com.atomicleopard.webelemental library 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the com.atomicleopard.webelemental library. If not, see
* http://www.gnu.org/licenses/lgpl-3.0.html.
*/
package com.atomicleopard.webelemental;
import static org.hamcrest.Matchers.*;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import com.atomicleopard.webelemental.matchers.HasAttributeMatcher;
import com.atomicleopard.webelemental.matchers.HasClassMatcher;
import com.atomicleopard.webelemental.matchers.HasIdMatcher;
import com.atomicleopard.webelemental.matchers.HasSizeMatcher;
import com.atomicleopard.webelemental.matchers.HasTextMatcher;
import com.atomicleopard.webelemental.matchers.HasValueMatcher;
import com.atomicleopard.webelemental.matchers.IsVisibleMatcher;
/**
* <p>
* {@link ElementMatchers} provides static factory methods for producing
* hamcrest {@link Matcher}s for different {@link Element} properties.
* </p>
* <p>
* As an alternative, consider using an {@link ElementMatcher} obtained from
* {@link Element#verify()} for a fluent, declarative API.
* </p>
*/
public final class ElementMatchers {
ElementMatchers() {
}
public static Matcher<Element> id(String string) {
return id(is(string));
}
public static Matcher<Element> id(Matcher<String> matcher) {
return new HasIdMatcher(matcher);
}
public static Matcher<Element> cssClass(String string) {
return cssClass(Matchers.is(string));
}
public static Matcher<Element> cssClass(Matcher<String> matcher) {
return new HasClassMatcher(matcher);
}
public static Matcher<Element> attr(String attribute, String value) {
return attr(attribute, Matchers.is(value));
}
public static Matcher<Element> attr(String attribute, Matcher<String> matcher) {
return new HasAttributeMatcher(attribute, matcher);
}
public static Matcher<Element> value(String string) {
return value(Matchers.is(string));
}
public static Matcher<Element> value(Matcher<String> matcher) {
return new HasValueMatcher(matcher);
}
public static Matcher<Element> size(int size) {
return size(is(size));
}
public static Matcher<Element> size(Matcher<Integer> matcher) {
return new HasSizeMatcher(matcher);
}
public static Matcher<Element> text(String string) {
return text(Matchers.is(string));
}
public static Matcher<Element> text(Matcher<String> matcher) {
return new HasTextMatcher(matcher);
}
public static Matcher<Element> visible() {
return new IsVisibleMatcher();
}
public static Matcher<Element> notVisible() {
return not(new IsVisibleMatcher());
}
}
| atomicleopard/WebElemental | src/main/java/com/atomicleopard/webelemental/ElementMatchers.java | Java | gpl-3.0 | 3,429 |
package edu.casetools.icase.mreasoner.gui.model.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderModel {
FileReader fileReader = null;
BufferedReader br = null;
public void open(String fileName){
try {
fileReader = new FileReader(fileName);
br = new BufferedReader(fileReader);
} catch (IOException e) {
e.printStackTrace();
}
}
public String read(String fileName) throws IOException{
this.open(fileName);
String result= "",sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
result = result + sCurrentLine+"\n";
}
this.close();
return result;
}
public void close(){
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| ualegre/mreasoner-gui | mreasoner-gui/src/main/java/edu/casetools/icase/mreasoner/gui/model/io/FileReaderModel.java | Java | gpl-3.0 | 830 |
package alexiil.mc.mod.load.baked.render;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.gui.FontRenderer;
import alexiil.mc.mod.load.render.MinecraftDisplayerRenderer;
import buildcraft.lib.expression.api.IExpressionNode.INodeDouble;
import buildcraft.lib.expression.api.IExpressionNode.INodeLong;
import buildcraft.lib.expression.node.value.NodeVariableDouble;
import buildcraft.lib.expression.node.value.NodeVariableObject;
public abstract class BakedTextRender extends BakedRenderPositioned {
protected final NodeVariableObject<String> varText;
protected final INodeDouble scale;
protected final INodeDouble x;
protected final INodeDouble y;
protected final INodeLong colour;
protected final String fontTexture;
private String _text;
private double _scale;
private double _width;
private long _colour;
private double _x, _y;
public BakedTextRender(
NodeVariableObject<String> varText, NodeVariableDouble varWidth, NodeVariableDouble varHeight,
INodeDouble scale, INodeDouble x, INodeDouble y, INodeLong colour, String fontTexture
) {
super(varWidth, varHeight);
this.varText = varText;
this.scale = scale;
this.x = x;
this.y = y;
this.colour = colour;
this.fontTexture = fontTexture;
}
@Override
public void evaluateVariables(MinecraftDisplayerRenderer renderer) {
_text = getText();
_scale = scale.evaluate();
FontRenderer font = renderer.fontRenderer(fontTexture);
_width = (int) (font.getStringWidth(_text) * _scale);
varWidth.value = _width;
varHeight.value = font.FONT_HEIGHT * _scale;
_x = x.evaluate();
_y = y.evaluate();
_colour = colour.evaluate();
if ((_colour & 0xFF_00_00_00) == 0) {
_colour |= 0xFF_00_00_00;
} else if ((_colour & 0xFF_00_00_00) == 0x01_00_00_00) {
_colour &= 0xFF_FF_FF;
}
}
@Override
public void render(MinecraftDisplayerRenderer renderer) {
FontRenderer font = renderer.fontRenderer(fontTexture);
GL11.glPushMatrix();
GL11.glTranslated(_x, _y, 0);
GL11.glScaled(_scale, _scale, _scale);
font.drawString(_text, 0, 0, (int) _colour, false);
GL11.glPopMatrix();
GL11.glColor4f(1, 1, 1, 1);
}
public abstract String getText();
@Override
public String getLocation() {
return fontTexture;
}
}
| AlexIIL/CustomLoadingScreen | src/main/java/alexiil/mc/mod/load/baked/render/BakedTextRender.java | Java | gpl-3.0 | 2,497 |
package com.tianyu.mesimp.survey.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.tianyu.mesimp.survey.bean.CompanyNum;
@Service
public class SunrveyService {
private Map<String, CompanyNum> testNumMap = new HashMap<String, CompanyNum>();
public SunrveyService(){
testNumMap.put("110000", new CompanyNum("110000", "沈阳市", 7834,1));
testNumMap.put("116000",new CompanyNum("116000", "大连市", 42305,2));
testNumMap.put("114000",new CompanyNum("114000", "鞍山市", 2040,3));
testNumMap.put("113000", new CompanyNum("113000", "抚顺市", 2589,4));
testNumMap.put("117000",new CompanyNum("117000", "本溪市", 706,5));
testNumMap.put("118000",new CompanyNum("118000", "丹东市", 21456,6));
testNumMap.put("121000",new CompanyNum("121000", "锦州市", 9831,7));
testNumMap.put("115000",new CompanyNum("115000", "营口市", 25230,8));
testNumMap.put("123000",new CompanyNum("123000", "阜新市", 132,9));
testNumMap.put("111000",new CompanyNum("111000", "辽阳市", 98,10));
testNumMap.put("124000",new CompanyNum("124000", "盘锦市", 10234,11));
testNumMap.put("112000",new CompanyNum("112000", "铁岭市", 348,12));
testNumMap.put("122000",new CompanyNum("122000", "朝阳市", 143,13));
testNumMap.put("125000",new CompanyNum("125000", "葫芦岛市", 12387,14));
}
public List<CompanyNum> getCompanyNumData(String codes) throws Exception{
List<CompanyNum> datalist = new ArrayList<CompanyNum>();
if("liaoning".equals(codes)){
datalist.addAll(testNumMap.values());
}else{
datalist.add(new CompanyNum("116000", "中山区", 9831,1));
datalist.add(new CompanyNum("116000", "西岗区", 4835,2));
datalist.add(new CompanyNum("116000", "沙河口区", 1234,3));
datalist.add(new CompanyNum("116000", "甘井子区", 2123,4));
datalist.add(new CompanyNum("116000", "旅顺口区", 7912,5));
datalist.add(new CompanyNum("116000", "金州新区", 3214,6));
datalist.add(new CompanyNum("116400", "庄河市", 2763,7));
datalist.add(new CompanyNum("116300", "瓦房店市", 2031,8));
datalist.add(new CompanyNum("116200", "普兰店区", 2341,9));
datalist.add(new CompanyNum("116500", "长海县", 6021,10));
}
return datalist;
}
}
| xuhw158/mesimp | src/main/java/com/tianyu/mesimp/survey/service/SunrveyService.java | Java | gpl-3.0 | 2,400 |
package eu.siacs.conversations.persistance;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.v4.content.FileProvider;
import android.system.Os;
import android.system.StructStat;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
import android.util.LruCache;
import android.webkit.MimeTypeMap;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.ExifHelper;
import eu.siacs.conversations.utils.FileUtils;
import eu.siacs.conversations.utils.FileWriterException;
import eu.siacs.conversations.utils.MimeUtils;
import eu.siacs.conversations.xmpp.pep.Avatar;
public class FileBackend {
private static final Object THUMBNAIL_LOCK = new Object();
private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
public static final String FILE_PROVIDER = ".files";
private XmppConnectionService mXmppConnectionService;
private static final List<String> BLACKLISTED_PATH_ELEMENTS = Arrays.asList("org.mozilla.firefox");
public FileBackend(XmppConnectionService service) {
this.mXmppConnectionService = service;
}
private void createNoMedia() {
final File nomedia = new File(getConversationsDirectory("Files") + ".nomedia");
if (!nomedia.exists()) {
try {
nomedia.createNewFile();
} catch (Exception e) {
Log.d(Config.LOGTAG, "could not create nomedia file");
}
}
}
public void updateMediaScanner(File file) {
String path = file.getAbsolutePath();
if (!path.startsWith(getConversationsDirectory("Files"))) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mXmppConnectionService.sendBroadcast(intent);
} else {
createNoMedia();
}
}
public boolean deleteFile(Message message) {
File file = getFile(message);
if (file.delete()) {
updateMediaScanner(file);
return true;
} else {
return false;
}
}
public DownloadableFile getFile(Message message) {
return getFile(message, true);
}
public DownloadableFile getFileForPath(String path, String mime) {
final DownloadableFile file;
if (path.startsWith("/")) {
file = new DownloadableFile(path);
} else {
if (mime != null && mime.startsWith("image/")) {
file = new DownloadableFile(getConversationsDirectory("Images") + path);
} else if (mime != null && mime.startsWith("video/")) {
file = new DownloadableFile(getConversationsDirectory("Videos") + path);
} else {
file = new DownloadableFile(getConversationsDirectory("Files") + path);
}
}
return file;
}
public DownloadableFile getFile(Message message, boolean decrypted) {
final boolean encrypted = !decrypted
&& (message.getEncryption() == Message.ENCRYPTION_PGP
|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
String path = message.getRelativeFilePath();
if (path == null) {
path = message.getUuid();
}
final DownloadableFile file = getFileForPath(path, message.getMimeType());
if (encrypted) {
return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
} else {
return file;
}
}
public static long getFileSize(Context context, Uri uri) {
try {
final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
cursor.close();
return size;
} else {
return -1;
}
} catch (Exception e) {
return -1;
}
}
public static boolean allFilesUnderSize(Context context, List<Uri> uris, long max) {
if (max <= 0) {
Log.d(Config.LOGTAG, "server did not report max file size for http upload");
return true; //exception to be compatible with HTTP Upload < v0.2
}
for (Uri uri : uris) {
String mime = context.getContentResolver().getType(uri);
if (mime != null && mime.startsWith("video/")) {
try {
Dimensions dimensions = FileBackend.getVideoDimensions(context, uri);
if (dimensions.getMin() > 720) {
Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check");
continue;
}
} catch (NotAVideoFile notAVideoFile) {
//ignore and fall through
}
}
if (FileBackend.getFileSize(context, uri) > max) {
Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle");
return false;
}
}
return true;
}
public String getConversationsDirectory(final String type) {
if (Config.ONLY_INTERNAL_STORAGE) {
return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/" + type + "/";
} else {
return Environment.getExternalStorageDirectory() + "/Conversations/Media/Conversations " + type + "/";
}
}
public static String getConversationsLogsDirectory() {
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/";
}
public Bitmap resize(Bitmap originalBitmap, int size) {
int w = originalBitmap.getWidth();
int h = originalBitmap.getHeight();
if (Math.max(w, h) > size) {
int scalledW;
int scalledH;
if (w <= h) {
scalledW = (int) (w / ((double) h / size));
scalledH = size;
} else {
scalledW = size;
scalledH = (int) (h / ((double) w / size));
}
Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
if (originalBitmap != null && !originalBitmap.isRecycled()) {
originalBitmap.recycle();
}
return result;
} else {
return originalBitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, int degree) {
if (degree == 0) {
return bitmap;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(degree);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
return result;
}
public boolean useImageAsIs(Uri uri) {
String path = getOriginalPath(uri);
if (path == null || isPathBlacklisted(path)) {
return false;
}
File file = new File(path);
long size = file.length();
if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
return false;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
return false;
}
return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
} catch (FileNotFoundException e) {
return false;
}
}
public static boolean isPathBlacklisted(String path) {
for(String element : BLACKLISTED_PATH_ELEMENTS) {
if (path.contains(element)) {
return true;
}
}
return false;
}
public String getOriginalPath(Uri uri) {
return FileUtils.getPath(mXmppConnectionService, uri);
}
public void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
file.getParentFile().mkdirs();
OutputStream os = null;
InputStream is = null;
try {
file.createNewFile();
os = new FileOutputStream(file);
is = mXmppConnectionService.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
try {
os.write(buffer, 0, length);
} catch (IOException e) {
throw new FileWriterException();
}
}
try {
os.flush();
} catch (IOException e) {
throw new FileWriterException();
}
} catch (FileNotFoundException e) {
throw new FileCopyException(R.string.error_file_not_found);
} catch (FileWriterException e) {
throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
} catch (IOException e) {
e.printStackTrace();
throw new FileCopyException(R.string.error_io_exception);
} finally {
close(os);
close(is);
}
}
public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
String mime = type != null ? type : MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri);
Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
String extension = MimeUtils.guessExtensionFromMimeType(mime);
if (extension == null) {
extension = getExtensionFromUri(uri);
}
message.setRelativeFilePath(message.getUuid() + "." + extension);
copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
}
private String getExtensionFromUri(Uri uri) {
String[] projection = {MediaStore.MediaColumns.DATA};
String filename = null;
Cursor cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
filename = cursor.getString(0);
}
} catch (Exception e) {
filename = null;
} finally {
cursor.close();
}
}
int pos = filename == null ? -1 : filename.lastIndexOf('.');
return pos > 0 ? filename.substring(pos + 1) : null;
}
private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
file.getParentFile().mkdirs();
InputStream is = null;
OutputStream os = null;
try {
if (!file.exists() && !file.createNewFile()) {
throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
}
is = mXmppConnectionService.getContentResolver().openInputStream(image);
if (is == null) {
throw new FileCopyException(R.string.error_not_an_image_file);
}
Bitmap originalBitmap;
BitmapFactory.Options options = new BitmapFactory.Options();
int inSampleSize = (int) Math.pow(2, sampleSize);
Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
options.inSampleSize = inSampleSize;
originalBitmap = BitmapFactory.decodeStream(is, null, options);
is.close();
if (originalBitmap == null) {
throw new FileCopyException(R.string.error_not_an_image_file);
}
Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
int rotation = getRotation(image);
scaledBitmap = rotate(scaledBitmap, rotation);
boolean targetSizeReached = false;
int quality = Config.IMAGE_QUALITY;
final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
while (!targetSizeReached) {
os = new FileOutputStream(file);
boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
if (!success) {
throw new FileCopyException(R.string.error_compressing_image);
}
os.flush();
targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
quality -= 5;
}
scaledBitmap.recycle();
} catch (FileNotFoundException e) {
throw new FileCopyException(R.string.error_file_not_found);
} catch (IOException e) {
e.printStackTrace();
throw new FileCopyException(R.string.error_io_exception);
} catch (SecurityException e) {
throw new FileCopyException(R.string.error_security_exception_during_image_copy);
} catch (OutOfMemoryError e) {
++sampleSize;
if (sampleSize <= 3) {
copyImageToPrivateStorage(file, image, sampleSize);
} else {
throw new FileCopyException(R.string.error_out_of_memory);
}
} finally {
close(os);
close(is);
}
}
public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
copyImageToPrivateStorage(file, image, 0);
}
public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
switch (Config.IMAGE_FORMAT) {
case JPEG:
message.setRelativeFilePath(message.getUuid() + ".jpg");
break;
case PNG:
message.setRelativeFilePath(message.getUuid() + ".png");
break;
case WEBP:
message.setRelativeFilePath(message.getUuid() + ".webp");
break;
}
copyImageToPrivateStorage(getFile(message), image);
updateFileParams(message);
}
private int getRotation(File file) {
return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
}
private int getRotation(Uri image) {
InputStream is = null;
try {
is = mXmppConnectionService.getContentResolver().openInputStream(image);
return ExifHelper.getOrientation(is);
} catch (FileNotFoundException e) {
return 0;
} finally {
close(is);
}
}
public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws FileNotFoundException {
final String uuid = message.getUuid();
final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
Bitmap thumbnail = cache.get(uuid);
if ((thumbnail == null) && (!cacheOnly)) {
synchronized (THUMBNAIL_LOCK) {
thumbnail = cache.get(uuid);
if (thumbnail != null) {
return thumbnail;
}
DownloadableFile file = getFile(message);
final String mime = file.getMimeType();
if (mime.startsWith("video/")) {
thumbnail = getVideoPreview(file, size);
} else {
Bitmap fullsize = getFullsizeImagePreview(file, size);
if (fullsize == null) {
throw new FileNotFoundException();
}
thumbnail = resize(fullsize, size);
thumbnail = rotate(thumbnail, getRotation(file));
if (mime.equals("image/gif")) {
Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
drawOverlay(withGifOverlay, R.drawable.play_gif, 1.0f);
thumbnail.recycle();
thumbnail = withGifOverlay;
}
}
this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
}
}
return thumbnail;
}
private Bitmap getFullsizeImagePreview(File file, int size) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calcSampleSize(file, size);
try {
return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
} catch (OutOfMemoryError e) {
options.inSampleSize *= 2;
return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
}
}
private void drawOverlay(Bitmap bitmap, int resource, float factor) {
Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
Canvas canvas = new Canvas(bitmap);
float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
float left = (canvas.getWidth() - targetSize) / 2.0f;
float top = (canvas.getHeight() - targetSize) / 2.0f;
RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
}
private static Paint createAntiAliasingPaint() {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
return paint;
}
private Bitmap getVideoPreview(File file, int size) {
MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
Bitmap frame;
try {
metadataRetriever.setDataSource(file.getAbsolutePath());
frame = metadataRetriever.getFrameAtTime(0);
metadataRetriever.release();
frame = resize(frame, size);
} catch (RuntimeException e) {
frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
frame.eraseColor(0xff000000);
}
drawOverlay(frame, R.drawable.play_video, 0.75f);
return frame;
}
private static String getTakePhotoPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
}
public Uri getTakePhotoUri() {
File file;
if (Config.ONLY_INTERNAL_STORAGE) {
file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
} else {
file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
}
file.getParentFile().mkdirs();
return getUriForFile(mXmppConnectionService, file);
}
public static Uri getUriForFile(Context context, File file) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
try {
String packageId = context.getPackageName();
return FileProvider.getUriForFile(context, packageId + FILE_PROVIDER, file);
} catch (IllegalArgumentException e) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
throw new SecurityException(e);
} else {
return Uri.fromFile(file);
}
}
} else {
return Uri.fromFile(file);
}
}
public static Uri getIndexableTakePhotoUri(Uri original) {
if (Config.ONLY_INTERNAL_STORAGE || "file".equals(original.getScheme())) {
return original;
} else {
List<String> segments = original.getPathSegments();
return Uri.parse("file://" + getTakePhotoPath() + segments.get(segments.size() - 1));
}
}
public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
Bitmap bm = cropCenterSquare(image, size);
if (bm == null) {
return null;
}
if (hasAlpha(bm)) {
Log.d(Config.LOGTAG,"alpha in avatar detected; uploading as PNG");
bm.recycle();
bm = cropCenterSquare(image, 96);
return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
}
return getPepAvatar(bm, format, 100);
}
private static boolean hasAlpha(final Bitmap bitmap) {
for(int x = 0; x < bitmap.getWidth(); ++x) {
for(int y = 0; y < bitmap.getWidth(); ++y) {
if (Color.alpha(bitmap.getPixel(x,y)) < 255) {
return true;
}
}
}
return false;
}
private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
try {
ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
MessageDigest digest = MessageDigest.getInstance("SHA-1");
DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
if (!bitmap.compress(format, quality, mDigestOutputStream)) {
return null;
}
mDigestOutputStream.flush();
mDigestOutputStream.close();
long chars = mByteArrayOutputStream.size();
if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
int q = quality - 2;
Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
return getPepAvatar(bitmap, format, q);
}
Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
final Avatar avatar = new Avatar();
avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
avatar.image = new String(mByteArrayOutputStream.toByteArray());
if (format.equals(Bitmap.CompressFormat.WEBP)) {
avatar.type = "image/webp";
} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
avatar.type = "image/jpeg";
} else if (format.equals(Bitmap.CompressFormat.PNG)) {
avatar.type = "image/png";
}
avatar.width = bitmap.getWidth();
avatar.height = bitmap.getHeight();
return avatar;
} catch (Exception e) {
return null;
}
}
public Avatar getStoredPepAvatar(String hash) {
if (hash == null) {
return null;
}
Avatar avatar = new Avatar();
File file = new File(getAvatarPath(hash));
FileInputStream is = null;
try {
avatar.size = file.length();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
is = new FileInputStream(file);
ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
MessageDigest digest = MessageDigest.getInstance("SHA-1");
DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
byte[] buffer = new byte[4096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
os.close();
avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
avatar.image = new String(mByteArrayOutputStream.toByteArray());
avatar.height = options.outHeight;
avatar.width = options.outWidth;
avatar.type = options.outMimeType;
return avatar;
} catch (IOException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} finally {
close(is);
}
}
public boolean isAvatarCached(Avatar avatar) {
File file = new File(getAvatarPath(avatar.getFilename()));
return file.exists();
}
public boolean save(Avatar avatar) {
File file;
if (isAvatarCached(avatar)) {
file = new File(getAvatarPath(avatar.getFilename()));
avatar.size = file.length();
} else {
String filename = getAvatarPath(avatar.getFilename());
file = new File(filename + ".tmp");
file.getParentFile().mkdirs();
OutputStream os = null;
try {
file.createNewFile();
os = new FileOutputStream(file);
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
final byte[] bytes = avatar.getImageAsBytes();
mDigestOutputStream.write(bytes);
mDigestOutputStream.flush();
mDigestOutputStream.close();
String sha1sum = CryptoHelper.bytesToHex(digest.digest());
if (sha1sum.equals(avatar.sha1sum)) {
file.renameTo(new File(filename));
} else {
Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
file.delete();
return false;
}
avatar.size = bytes.length;
} catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
return false;
} finally {
close(os);
}
}
return true;
}
public String getAvatarPath(String avatar) {
return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
}
public Uri getAvatarUri(String avatar) {
return Uri.parse("file:" + getAvatarPath(avatar));
}
public Bitmap cropCenterSquare(Uri image, int size) {
if (image == null) {
return null;
}
InputStream is = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calcSampleSize(image, size);
is = mXmppConnectionService.getContentResolver().openInputStream(image);
if (is == null) {
return null;
}
Bitmap input = BitmapFactory.decodeStream(is, null, options);
if (input == null) {
return null;
} else {
input = rotate(input, getRotation(image));
return cropCenterSquare(input, size);
}
} catch (SecurityException e) {
return null; // happens for example on Android 6.0 if contacts permissions get revoked
} catch (FileNotFoundException e) {
return null;
} finally {
close(is);
}
}
public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
if (image == null) {
return null;
}
InputStream is = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
is = mXmppConnectionService.getContentResolver().openInputStream(image);
if (is == null) {
return null;
}
Bitmap source = BitmapFactory.decodeStream(is, null, options);
if (source == null) {
return null;
}
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
if (source.isRecycled()) {
source.recycle();
}
return dest;
} catch (SecurityException e) {
return null; //android 6.0 with revoked permissions for example
} catch (FileNotFoundException e) {
return null;
} finally {
close(is);
}
}
public Bitmap cropCenterSquare(Bitmap input, int size) {
int w = input.getWidth();
int h = input.getHeight();
float scale = Math.max((float) size / h, (float) size / w);
float outWidth = scale * w;
float outHeight = scale * h;
float left = (size - outWidth) / 2;
float top = (size - outHeight) / 2;
RectF target = new RectF(left, top, left + outWidth, top + outHeight);
Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
if (!input.isRecycled()) {
input.recycle();
}
return output;
}
private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
return calcSampleSize(options, size);
}
private static int calcSampleSize(File image, int size) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getAbsolutePath(), options);
return calcSampleSize(options, size);
}
public static int calcSampleSize(BitmapFactory.Options options, int size) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
if (height > size || width > size) {
int halfHeight = height / 2;
int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > size
&& (halfWidth / inSampleSize) > size) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public void updateFileParams(Message message) {
updateFileParams(message, null);
}
public void updateFileParams(Message message, URL url) {
DownloadableFile file = getFile(message);
final String mime = file.getMimeType();
boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
boolean video = mime != null && mime.startsWith("video/");
boolean audio = mime != null && mime.startsWith("audio/");
final StringBuilder body = new StringBuilder();
if (url != null) {
body.append(url.toString());
}
body.append('|').append(file.getSize());
if (image || video) {
try {
Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
body.append('|').append(dimensions.width).append('|').append(dimensions.height);
} catch (NotAVideoFile notAVideoFile) {
Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
//fall threw
}
} else if (audio) {
body.append("|0|0|").append(getMediaRuntime(file));
}
message.setBody(body.toString());
}
public int getMediaRuntime(Uri uri) {
try {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
} catch (RuntimeException e) {
return 0;
}
}
private int getMediaRuntime(File file) {
try {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(file.toString());
return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
} catch (RuntimeException e) {
return 0;
}
}
private Dimensions getImageDimensions(File file) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int rotation = getRotation(file);
boolean rotated = rotation == 90 || rotation == 270;
int imageHeight = rotated ? options.outWidth : options.outHeight;
int imageWidth = rotated ? options.outHeight : options.outWidth;
return new Dimensions(imageHeight, imageWidth);
}
private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
try {
metadataRetriever.setDataSource(file.getAbsolutePath());
} catch (RuntimeException e) {
throw new NotAVideoFile(e);
}
return getVideoDimensions(metadataRetriever);
}
private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
try {
mediaMetadataRetriever.setDataSource(context, uri);
} catch (RuntimeException e) {
throw new NotAVideoFile(e);
}
return getVideoDimensions(mediaMetadataRetriever);
}
private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
if (hasVideo == null) {
throw new NotAVideoFile();
}
int rotation = extractRotationFromMediaRetriever(metadataRetriever);
boolean rotated = rotation == 90 || rotation == 270;
int height;
try {
String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
height = Integer.parseInt(h);
} catch (Exception e) {
height = -1;
}
int width;
try {
String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
width = Integer.parseInt(w);
} catch (Exception e) {
width = -1;
}
metadataRetriever.release();
Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
}
private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
int rotation;
if (Build.VERSION.SDK_INT >= 17) {
String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
try {
rotation = Integer.parseInt(r);
} catch (Exception e) {
rotation = 0;
}
} else {
rotation = 0;
}
return rotation;
}
private static class Dimensions {
public final int width;
public final int height;
public Dimensions(int height, int width) {
this.width = width;
this.height = height;
}
public int getMin() {
return Math.min(width, height);
}
}
private static class NotAVideoFile extends Exception {
public NotAVideoFile(Throwable t) {
super(t);
}
public NotAVideoFile() {
super();
}
}
public class FileCopyException extends Exception {
private static final long serialVersionUID = -1010013599132881427L;
private int resId;
public FileCopyException(int resId) {
this.resId = resId;
}
public int getResId() {
return resId;
}
}
public Bitmap getAvatar(String avatar, int size) {
if (avatar == null) {
return null;
}
Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
if (bm == null) {
return null;
}
return bm;
}
public boolean isFileAvailable(Message message) {
return getFile(message).exists();
}
public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
public static void close(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
public static boolean weOwnFile(Context context, Uri uri) {
if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
return false;
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return fileIsInFilesDir(context, uri);
} else {
return weOwnFileLollipop(uri);
}
}
/**
* This is more than hacky but probably way better than doing nothing
* Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
* and check against those as well
*/
private static boolean fileIsInFilesDir(Context context, Uri uri) {
try {
final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
final String needle = new File(uri.getPath()).getCanonicalPath();
return needle.startsWith(haystack);
} catch (IOException e) {
return false;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean weOwnFileLollipop(Uri uri) {
try {
File file = new File(uri.getPath());
FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
StructStat st = Os.fstat(fd);
return st.st_uid == android.os.Process.myUid();
} catch (FileNotFoundException e) {
return false;
} catch (Exception e) {
return true;
}
}
}
| andre-hub/Conversations | src/main/java/eu/siacs/conversations/persistance/FileBackend.java | Java | gpl-3.0 | 34,726 |
package net.mosstest.tests;
import net.mosstest.scripting.NodePosition;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.fail;
public class NodePositionTest {
public static final int CHUNK_DIMENSION = 16;
public static final int[] coords = {0, 1, -1, 16, -16, 67, -66, 269, -267,
65601, -65601, Integer.MAX_VALUE, Integer.MIN_VALUE};
@Test
public void testHashCode() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x += 8) {
for (byte y = 0; y < CHUNK_DIMENSION; y += 8) {
for (byte z = 0; z < CHUNK_DIMENSION; z += 8) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertEquals(
"Mismatched hashCodes for value-identical NodePosition objects",
pos1.hashCode(), pos2.hashCode());
}
}
}
}
}
}
}
@Test
public void testByteArrayReadWrite() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=8) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
for (byte z = 0; z < CHUNK_DIMENSION; z+=4) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
byte[] bytes = pos1.toBytes();
NodePosition pos2;
try {
pos2 = new NodePosition(bytes);
Assert.assertTrue(
"NodePosition nmarshaled from byte[] fails equals() check with original NodePosition.",
pos1.equals(pos2));
} catch (IOException e) {
fail("IOException caught in unmarshaling NodePosition from byte[]");
}
}
}
}
}
}
}
}
@Test
public void testEqualsObject() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=8) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
for (byte z = 0; z < CHUNK_DIMENSION; z+=4) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos1.equals(pos2));
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos2.equals(pos1));
NodePosition pos3 = new NodePosition(
0, coords[i] + 1, coords[j], coords[k],
x, y, z);
NodePosition pos4 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos3.equals(pos4));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos4.equals(pos3));
NodePosition pos5 = new NodePosition(0, coords[i],
coords[j] + 1, coords[k], x, y, z);
NodePosition pos6 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos5.equals(pos6));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos6.equals(pos5));
NodePosition pos7 = new NodePosition(0, coords[i],
coords[j], coords[k] + 1, x, y, z);
NodePosition pos8 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos7.equals(pos8));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos8.equals(pos7));
}
}
}
}
}
}
}
@Test
public void testToBytes() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x+=4) {
for (byte y = 0; y < CHUNK_DIMENSION; y+=8) {
NodePosition pos1 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, (byte)0);
NodePosition pos2 = new NodePosition(0, coords[i],
coords[j], coords[k], x, y, (byte)0);
org.junit.Assert.assertArrayEquals(
pos1.toBytes(), pos2.toBytes());
}
}
}
}
}
}
}
| mosstest/mosstest | tests/net/mosstest/tests/NodePositionTest.java | Java | gpl-3.0 | 7,454 |
/*
To Do:
Fix Reverse Driving
Make only one side fire (right)
*/
/* Copyright (c) 2014, 2015 Qualcomm Technologies Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Qualcomm Technologies Inc nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.*;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.hardware.*;
//red turns left
//blue turns right
/*
To Do;
Double gears on shooter
Rotate Block and Top Part of Beacon Pusher 90 degrees. The servo end position is currently level
with the end of the robot instead of sideways
*/
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.os.SystemClock.sleep;
/**
* Registers OpCode and Initializes Variables
*/
@com.qualcomm.robotcore.eventloop.opmode.Autonomous(name = "Autonomous α", group = "FTC772")
public class Autonomous extends LinearOpMode {
private ElapsedTime runtime = new ElapsedTime();
private DcMotor frontLeft, frontRight, intake, dispenserLeft, dispenserRight, liftLeft, liftRight, midtake;
private Servo dispenser, beaconAngleLeft, beaconAngleRight, forkliftLeft, forkliftRight;
private boolean drivingForward = true;
//private boolean init = false;
//private final double DISPENSER_POWER = 1;
private double BEACON_LEFT_IN;
private double BEACON_RIGHT_IN;
private final int INITIAL_FORWARD = 1000;
private final int RAMP_UP = 1000;
private final int TURN_ONE = 300;
private final int FORWARD_TWO = 500;
private final int TURN_TWO = 300;
private final int FORWARD_THREE = 300;
private final int COLOR_CORRECTION = 50;
private final int FORWARD_FOUR = 400;
private final int TURN_THREE = 500;
private final int FORWARD_FIVE = 500;
private final boolean isRed = true;
private boolean didColorCorrection = false;
private boolean wasChangingAngle = false;
private ColorSensor colorSensor;
private TouchSensor leftTouchSensor, rightTouchSensor;
// @Override
// public void init() {
// /*
// Initialize DcMotors
// */
// frontLeft = hardwareMap.dcMotor.get("frontLeft");
// frontRight = hardwareMap.dcMotor.get("frontRight");
//
// //intake = hardwareMap.dcMotor.get("intake");
// dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft");
// dispenserRight = hardwareMap.dcMotor.get("dispenserRight");
//
// /*
// Initialize Servos
// */
// dispenserAngle = hardwareMap.servo.get("dispenserAngle");
// beaconAngle = hardwareMap.servo.get("beaconAngle");
//
//
// /*
// Initialize Sensors
// */
// colorSensor = hardwareMap.colorSensor.get("colorSensor");
// leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor");
// rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor");
//
// //Display completion message
// telemetry.addData("Status", "Initialized");
// }
/*
* Code to run when the op mode is first enabled goes here
* @see com.qualcomm.robotcore.eventloop.opmode.OpMode#start()
@Override
public void init_loop() {
}*/
/*
* This method will be called ONCE when start is pressed
* @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop()
*/
/*
public void start() {
/*
Initialize all motors/servos to position
*/
//runtime.reset();
//dispenserAngle.setPosition(DEFAULT_ANGLE);
// }
/*
* This method will be called repeatedly in a loop
* @see com.qualcomm.robotcore.eventloop.opmode.OpMode#loop()
*/
@Override
public void runOpMode() throws InterruptedException {
frontLeft = hardwareMap.dcMotor.get("frontLeft");
frontRight = hardwareMap.dcMotor.get("frontRight");
intake = hardwareMap.dcMotor.get("intake");
midtake = hardwareMap.dcMotor.get("midtake");
dispenserLeft = hardwareMap.dcMotor.get("dispenserLeft");
dispenserRight = hardwareMap.dcMotor.get("dispenserRight");
dispenserLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
dispenserRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT);
liftLeft = hardwareMap.dcMotor.get("liftLeft");
liftRight = hardwareMap.dcMotor.get("liftRight");
liftLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
liftLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
liftRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
liftRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
/*
Initialize Servos
*/
dispenser = hardwareMap.servo.get("dispenser");
beaconAngleLeft = hardwareMap.servo.get("beaconAngleLeft");
beaconAngleRight = hardwareMap.servo.get("beaconAngleRight");
forkliftLeft = hardwareMap.servo.get("forkliftLeft");
forkliftRight = hardwareMap.servo.get("forkliftRight");
/*
Initialize Sensors
*/
//colorSensor = hardwareMap.colorSensor.get("colorSensor");
//leftTouchSensor = hardwareMap.touchSensor.get("leftTouchSensor");
//rightTouchSensor = hardwareMap.touchSensor.get("rightTouchSensor");
//Display completion message
telemetry.addData("Status", "Initialized");
/*
Steps to Autonomous:
Fire starting balls
Drive to beacon 1
Press beacon 1
Drive to beacon 2
Press beacon 2
Drive to center and park while knocking ball off
*/
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(INITIAL_FORWARD);
frontLeft.setPower(0);
frontRight.setPower(0);
dispenserLeft.setPower(1);
dispenserRight.setPower(1);
sleep(RAMP_UP);
intake.setPower(1);
midtake.setPower(1);
dispenser.setPosition(0);
sleep(500);
dispenser.setPosition(.45);
sleep(150);
dispenser.setPosition(0);
sleep(500);
dispenser.setPosition(.45);
intake.setPower(0);
midtake.setPower(0);
dispenserRight.setPower(0);
dispenserLeft.setPower(0);
if (isRed) {
frontLeft.setPower(1);
frontRight.setPower(1);
sleep(TURN_ONE);
frontRight.setPower(-1);
}
else {
frontLeft.setPower(-1);
frontRight.setPower(-1);
sleep(TURN_ONE);
frontLeft.setPower(1);
}
sleep(FORWARD_TWO);
if (!isRed) {
frontLeft.setPower(-1);
sleep(TURN_TWO);
frontLeft.setPower(1);
}
else {
frontRight.setPower(1);
sleep(TURN_TWO);
frontRight.setPower(-1);
}
sleep(FORWARD_THREE);
frontLeft.setPower(0);
frontRight.setPower(0);
if (!isRed) {
if (colorSensor.red()<colorSensor.blue()) {
beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN));
}
else {
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(COLOR_CORRECTION);
didColorCorrection = true;
frontLeft.setPower(0);
frontRight.setPower(0);
beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN));
}
}
else {
if (colorSensor.red()>colorSensor.blue()) {
beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN));
}
else {
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(COLOR_CORRECTION);
didColorCorrection = true;
frontLeft.setPower(0);
frontRight.setPower(0);
beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN));
}
}
frontLeft.setPower(1);
frontRight.setPower(-1);
if (didColorCorrection) {
sleep(FORWARD_FOUR-COLOR_CORRECTION);
}
else {
sleep(FORWARD_FOUR);
}
frontLeft.setPower(0);
frontRight.setPower(0);
if (!isRed) {
if (colorSensor.red()<colorSensor.blue()) {
beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN));
}
else {
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(COLOR_CORRECTION);
frontLeft.setPower(0);
frontRight.setPower(0);
beaconAngleRight.setPosition(Math.abs(.5-BEACON_RIGHT_IN));
}
}
else {
if (colorSensor.red()>colorSensor.blue()) {
beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN));
}
else {
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(COLOR_CORRECTION);
frontLeft.setPower(0);
frontRight.setPower(0);
beaconAngleLeft.setPosition(Math.abs(.5-BEACON_LEFT_IN));
}
}
frontLeft.setPower(1);
frontRight.setPower(1);
sleep(TURN_THREE);
frontRight.setPower(-1);
sleep(FORWARD_FIVE);
telemetry.addData("Status", "Run Time: " + runtime.toString());
/*
This section is the short version of the autonomous for in case the other part doesn't work.
It drives straight forward and knocks the cap ball off in the center.
*/
sleep(10000);
frontLeft.setPower(1);
frontRight.setPower(-1);
sleep(4000);
frontRight.setPower(0);
frontLeft.setPower(0);
sleep(10000);
}
}
| NeonRD1/FTC772 | ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Autonomous.java | Java | gpl-3.0 | 11,732 |
/*
* @file TestXMLNode.java
* @brief XMLNode unit tests
*
* @author Akiya Jouraku (Java conversion)
* @author Michael Hucka <[email protected]>
*
* $Id: TestXMLNode.java 11442 2010-07-09 02:23:35Z mhucka $
* $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/bindings/java/test/org/sbml/libsbml/test/xml/TestXMLNode.java $
*
* ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
*
* DO NOT EDIT THIS FILE.
*
* This file was generated automatically by converting the file located at
* src/xml/test/TestXMLNode.c
* using the conversion program dev/utilities/translateTests/translateTests.pl.
* Any changes made here will be lost the next time the file is regenerated.
*
* -----------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright 2005-2010 California Institute of Technology.
* Copyright 2002-2005 California Institute of Technology and
* Japan Science and Technology Corporation.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* -----------------------------------------------------------------------------
*/
package org.sbml.libsbml.test.xml;
import org.sbml.libsbml.*;
import java.io.File;
import java.lang.AssertionError;
public class TestXMLNode {
static void assertTrue(boolean condition) throws AssertionError
{
if (condition == true)
{
return;
}
throw new AssertionError();
}
static void assertEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
return;
}
else if ( (a == null) || (b == null) )
{
throw new AssertionError();
}
else if (a.equals(b))
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
throw new AssertionError();
}
else if ( (a == null) || (b == null) )
{
return;
}
else if (a.equals(b))
{
throw new AssertionError();
}
}
static void assertEquals(boolean a, boolean b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(boolean a, boolean b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
static void assertEquals(int a, int b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(int a, int b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
public void test_XMLNode_attribute_add_remove()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
XMLTriple xt1 = new XMLTriple("name1", "http://name1.org/", "p1");
XMLTriple xt2 = new XMLTriple("name2", "http://name2.org/", "p2");
XMLTriple xt3 = new XMLTriple("name3", "http://name3.org/", "p3");
XMLTriple xt1a = new XMLTriple("name1", "http://name1a.org/", "p1a");
XMLTriple xt2a = new XMLTriple("name2", "http://name2a.org/", "p2a");
node.addAttr( "name1", "val1", "http://name1.org/", "p1");
node.addAttr(xt2, "val2");
assertTrue( node.getAttributesLength() == 2 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(0).equals( "name1") == false );
assertTrue( !node.getAttrValue(0).equals( "val1" ) == false );
assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false );
assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false );
assertTrue( !node.getAttrName(1).equals( "name2") == false );
assertTrue( !node.getAttrValue(1).equals( "val2" ) == false );
assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false );
assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false );
assertTrue( node.getAttrValue( "name1").equals("") == true );
assertTrue( node.getAttrValue( "name2").equals("") == true );
assertTrue( !node.getAttrValue( "name1", "http://name1.org/").equals( "val1" ) == false );
assertTrue( !node.getAttrValue( "name2", "http://name2.org/").equals( "val2" ) == false );
assertTrue( !node.getAttrValue(xt1).equals( "val1" ) == false );
assertTrue( !node.getAttrValue(xt2).equals( "val2" ) == false );
assertTrue( node.hasAttr(-1) == false );
assertTrue( node.hasAttr(2) == false );
assertTrue( node.hasAttr(0) == true );
assertTrue( node.hasAttr( "name1", "http://name1.org/") == true );
assertTrue( node.hasAttr( "name2", "http://name2.org/") == true );
assertTrue( node.hasAttr( "name3", "http://name3.org/") == false );
assertTrue( node.hasAttr(xt1) == true );
assertTrue( node.hasAttr(xt2) == true );
assertTrue( node.hasAttr(xt3) == false );
node.addAttr( "noprefix", "val3");
assertTrue( node.getAttributesLength() == 3 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(2).equals( "noprefix") == false );
assertTrue( !node.getAttrValue(2).equals( "val3" ) == false );
assertTrue( node.getAttrURI(2).equals("") == true );
assertTrue( node.getAttrPrefix(2).equals("") == true );
assertTrue( !node.getAttrValue( "noprefix").equals( "val3" ) == false );
assertTrue( !node.getAttrValue( "noprefix", "").equals( "val3" ) == false );
assertTrue( node.hasAttr( "noprefix" ) == true );
assertTrue( node.hasAttr( "noprefix", "") == true );
node.addAttr(xt1, "mval1");
node.addAttr( "name2", "mval2", "http://name2.org/", "p2");
assertTrue( node.getAttributesLength() == 3 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(0).equals( "name1") == false );
assertTrue( !node.getAttrValue(0).equals( "mval1") == false );
assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false );
assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false );
assertTrue( !node.getAttrName(1).equals( "name2" ) == false );
assertTrue( !node.getAttrValue(1).equals( "mval2" ) == false );
assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false );
assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false );
assertTrue( node.hasAttr(xt1) == true );
assertTrue( node.hasAttr( "name1", "http://name1.org/") == true );
node.addAttr( "noprefix", "mval3");
assertTrue( node.getAttributesLength() == 3 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(2).equals( "noprefix") == false );
assertTrue( !node.getAttrValue(2).equals( "mval3" ) == false );
assertTrue( node.getAttrURI(2).equals("") == true );
assertTrue( node.getAttrPrefix(2).equals("") == true );
assertTrue( node.hasAttr( "noprefix") == true );
assertTrue( node.hasAttr( "noprefix", "") == true );
node.addAttr(xt1a, "val1a");
node.addAttr(xt2a, "val2a");
assertTrue( node.getAttributesLength() == 5 );
assertTrue( !node.getAttrName(3).equals( "name1") == false );
assertTrue( !node.getAttrValue(3).equals( "val1a") == false );
assertTrue( !node.getAttrURI(3).equals( "http://name1a.org/") == false );
assertTrue( !node.getAttrPrefix(3).equals( "p1a") == false );
assertTrue( !node.getAttrName(4).equals( "name2") == false );
assertTrue( !node.getAttrValue(4).equals( "val2a") == false );
assertTrue( !node.getAttrURI(4).equals( "http://name2a.org/") == false );
assertTrue( !node.getAttrPrefix(4).equals( "p2a") == false );
assertTrue( !node.getAttrValue( "name1", "http://name1a.org/").equals( "val1a" ) == false );
assertTrue( !node.getAttrValue( "name2", "http://name2a.org/").equals( "val2a" ) == false );
assertTrue( !node.getAttrValue(xt1a).equals( "val1a" ) == false );
assertTrue( !node.getAttrValue(xt2a).equals( "val2a" ) == false );
node.removeAttr(xt1a);
node.removeAttr(xt2a);
assertTrue( node.getAttributesLength() == 3 );
node.removeAttr( "name1", "http://name1.org/");
assertTrue( node.getAttributesLength() == 2 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(0).equals( "name2") == false );
assertTrue( !node.getAttrValue(0).equals( "mval2") == false );
assertTrue( !node.getAttrURI(0).equals( "http://name2.org/") == false );
assertTrue( !node.getAttrPrefix(0).equals( "p2") == false );
assertTrue( !node.getAttrName(1).equals( "noprefix") == false );
assertTrue( !node.getAttrValue(1).equals( "mval3") == false );
assertTrue( node.getAttrURI(1).equals("") == true );
assertTrue( node.getAttrPrefix(1).equals("") == true );
assertTrue( node.hasAttr( "name1", "http://name1.org/") == false );
node.removeAttr(xt2);
assertTrue( node.getAttributesLength() == 1 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(0).equals( "noprefix") == false );
assertTrue( !node.getAttrValue(0).equals( "mval3") == false );
assertTrue( node.getAttrURI(0).equals("") == true );
assertTrue( node.getAttrPrefix(0).equals("") == true );
assertTrue( node.hasAttr(xt2) == false );
assertTrue( node.hasAttr( "name2", "http://name2.org/") == false );
node.removeAttr( "noprefix");
assertTrue( node.getAttributesLength() == 0 );
assertTrue( node.isAttributesEmpty() == true );
assertTrue( node.hasAttr( "noprefix" ) == false );
assertTrue( node.hasAttr( "noprefix", "") == false );
node = null;
xt1 = null;
xt2 = null;
xt3 = null;
xt1a = null;
xt2a = null;
triple = null;
attr = null;
}
public void test_XMLNode_attribute_set_clear()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
XMLAttributes nattr = new XMLAttributes();
XMLTriple xt1 = new XMLTriple("name1", "http://name1.org/", "p1");
XMLTriple xt2 = new XMLTriple("name2", "http://name2.org/", "p2");
XMLTriple xt3 = new XMLTriple("name3", "http://name3.org/", "p3");
XMLTriple xt4 = new XMLTriple("name4", "http://name4.org/", "p4");
XMLTriple xt5 = new XMLTriple("name5", "http://name5.org/", "p5");
nattr.add(xt1, "val1");
nattr.add(xt2, "val2");
nattr.add(xt3, "val3");
nattr.add(xt4, "val4");
nattr.add(xt5, "val5");
node.setAttributes(nattr);
assertTrue( node.getAttributesLength() == 5 );
assertTrue( node.isAttributesEmpty() == false );
assertTrue( !node.getAttrName(0).equals( "name1") == false );
assertTrue( !node.getAttrValue(0).equals( "val1" ) == false );
assertTrue( !node.getAttrURI(0).equals( "http://name1.org/") == false );
assertTrue( !node.getAttrPrefix(0).equals( "p1" ) == false );
assertTrue( !node.getAttrName(1).equals( "name2") == false );
assertTrue( !node.getAttrValue(1).equals( "val2" ) == false );
assertTrue( !node.getAttrURI(1).equals( "http://name2.org/") == false );
assertTrue( !node.getAttrPrefix(1).equals( "p2" ) == false );
assertTrue( !node.getAttrName(2).equals( "name3") == false );
assertTrue( !node.getAttrValue(2).equals( "val3" ) == false );
assertTrue( !node.getAttrURI(2).equals( "http://name3.org/") == false );
assertTrue( !node.getAttrPrefix(2).equals( "p3" ) == false );
assertTrue( !node.getAttrName(3).equals( "name4") == false );
assertTrue( !node.getAttrValue(3).equals( "val4" ) == false );
assertTrue( !node.getAttrURI(3).equals( "http://name4.org/") == false );
assertTrue( !node.getAttrPrefix(3).equals( "p4" ) == false );
assertTrue( !node.getAttrName(4).equals( "name5") == false );
assertTrue( !node.getAttrValue(4).equals( "val5" ) == false );
assertTrue( !node.getAttrURI(4).equals( "http://name5.org/") == false );
assertTrue( !node.getAttrPrefix(4).equals( "p5" ) == false );
XMLTriple ntriple = new XMLTriple("test2","http://test2.org/","p2");
node.setTriple(ntriple);
assertTrue( !node.getName().equals( "test2") == false );
assertTrue( !node.getURI().equals( "http://test2.org/") == false );
assertTrue( !node.getPrefix().equals( "p2") == false );
node.clearAttributes();
assertTrue( node.getAttributesLength() == 0 );
assertTrue( node.isAttributesEmpty() != false );
triple = null;
ntriple = null;
node = null;
attr = null;
nattr = null;
xt1 = null;
xt2 = null;
xt3 = null;
xt4 = null;
xt5 = null;
}
public void test_XMLNode_convert()
{
String xmlstr = "<annotation>\n" + " <test xmlns=\"http://test.org/\" id=\"test\">test</test>\n" + "</annotation>";
XMLNode node;
XMLNode child, gchild;
XMLAttributes attr;
XMLNamespaces ns;
node = XMLNode.convertStringToXMLNode(xmlstr,null);
child = node.getChild(0);
gchild = child.getChild(0);
attr = child.getAttributes();
ns = child.getNamespaces();
assertTrue( !node.getName().equals( "annotation") == false );
assertTrue( !child.getName().equals("test" ) == false );
assertTrue( !gchild.getCharacters().equals("test" ) == false );
assertTrue( !attr.getName(0).equals( "id" ) == false );
assertTrue( !attr.getValue(0).equals( "test" ) == false );
assertTrue( !ns.getURI(0).equals( "http://test.org/" ) == false );
assertTrue( ns.getPrefix(0).equals("") == true );
String toxmlstring = node.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr) == false );
node = null;
}
public void test_XMLNode_convert_dummyroot()
{
String xmlstr_nodummy1 = "<notes>\n" + " <p>test</p>\n" + "</notes>";
String xmlstr_nodummy2 = "<html>\n" + " <p>test</p>\n" + "</html>";
String xmlstr_nodummy3 = "<body>\n" + " <p>test</p>\n" + "</body>";
String xmlstr_nodummy4 = "<p>test</p>";
String xmlstr_nodummy5 = "<test1>\n" + " <test2>test</test2>\n" + "</test1>";
String xmlstr_dummy1 = "<p>test1</p><p>test2</p>";
String xmlstr_dummy2 = "<test1>test1</test1><test2>test2</test2>";
XMLNode rootnode;
XMLNode child, gchild;
XMLAttributes attr;
XMLNamespaces ns;
String toxmlstring;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy1,null);
assertTrue( rootnode.getNumChildren() == 1 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !rootnode.getName().equals( "notes") == false );
assertTrue( !child.getName().equals("p" ) == false );
assertTrue( !gchild.getCharacters().equals("test" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_nodummy1) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy2,null);
assertTrue( rootnode.getNumChildren() == 1 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !rootnode.getName().equals( "html") == false );
assertTrue( !child.getName().equals("p" ) == false );
assertTrue( !gchild.getCharacters().equals("test" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_nodummy2) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy3,null);
assertTrue( rootnode.getNumChildren() == 1 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !rootnode.getName().equals( "body") == false );
assertTrue( !child.getName().equals("p" ) == false );
assertTrue( !gchild.getCharacters().equals("test" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_nodummy3) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy4,null);
assertTrue( rootnode.getNumChildren() == 1 );
child = rootnode.getChild(0);
assertTrue( !rootnode.getName().equals( "p") == false );
assertTrue( !child.getCharacters().equals("test" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_nodummy4) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_nodummy5,null);
assertTrue( rootnode.getNumChildren() == 1 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !rootnode.getName().equals( "test1") == false );
assertTrue( !child.getName().equals("test2" ) == false );
assertTrue( !gchild.getCharacters().equals("test" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_nodummy5) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_dummy1,null);
assertTrue( rootnode.isEOF() == true );
assertTrue( rootnode.getNumChildren() == 2 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !child.getName().equals( "p") == false );
assertTrue( !gchild.getCharacters().equals("test1" ) == false );
child = rootnode.getChild(1);
gchild = child.getChild(0);
assertTrue( !child.getName().equals( "p") == false );
assertTrue( !gchild.getCharacters().equals("test2" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_dummy1) == false );
rootnode = null;
rootnode = XMLNode.convertStringToXMLNode(xmlstr_dummy2,null);
assertTrue( rootnode.isEOF() == true );
assertTrue( rootnode.getNumChildren() == 2 );
child = rootnode.getChild(0);
gchild = child.getChild(0);
assertTrue( !child.getName().equals( "test1") == false );
assertTrue( !gchild.getCharacters().equals("test1" ) == false );
child = rootnode.getChild(1);
gchild = child.getChild(0);
assertTrue( !child.getName().equals( "test2") == false );
assertTrue( !gchild.getCharacters().equals("test2" ) == false );
toxmlstring = rootnode.toXMLString();
assertTrue( !toxmlstring.equals(xmlstr_dummy2) == false );
rootnode = null;
}
public void test_XMLNode_create()
{
XMLNode node = new XMLNode();
assertTrue( node != null );
assertTrue( node.getNumChildren() == 0 );
node = null;
node = new XMLNode();
assertTrue( node != null );
XMLNode node2 = new XMLNode();
assertTrue( node2 != null );
node.addChild(node2);
assertTrue( node.getNumChildren() == 1 );
XMLNode node3 = new XMLNode();
assertTrue( node3 != null );
node.addChild(node3);
assertTrue( node.getNumChildren() == 2 );
node = null;
node2 = null;
node3 = null;
}
public void test_XMLNode_createElement()
{
XMLTriple triple;
XMLAttributes attr;
XMLNamespaces ns;
XMLNode snode, enode, tnode;
XMLAttributes cattr;
String name = "test";
String uri = "http://test.org/";
String prefix = "p";
String text = "text node";
triple = new XMLTriple(name,uri,prefix);
ns = new XMLNamespaces();
attr = new XMLAttributes();
ns.add(uri,prefix);
attr.add("id", "value",uri,prefix);
snode = new XMLNode(triple,attr,ns);
assertTrue( snode != null );
assertTrue( snode.getNumChildren() == 0 );
assertTrue( !snode.getName().equals(name) == false );
assertTrue( !snode.getPrefix().equals(prefix) == false );
assertTrue( !snode.getURI().equals(uri) == false );
assertTrue( snode.isElement() == true );
assertTrue( snode.isStart() == true );
assertTrue( snode.isEnd() == false );
assertTrue( snode.isText() == false );
snode.setEnd();
assertTrue( snode.isEnd() == true );
snode.unsetEnd();
assertTrue( snode.isEnd() == false );
cattr = snode.getAttributes();
assertTrue( cattr != null );
assertTrue( !cattr.getName(0).equals( "id" ) == false );
assertTrue( !cattr.getValue(0).equals( "value") == false );
assertTrue( !cattr.getPrefix(0).equals(prefix) == false );
assertTrue( !cattr.getURI(0).equals(uri) == false );
triple = null;
attr = null;
ns = null;
snode = null;
attr = new XMLAttributes();
attr.add("id", "value");
triple = new XMLTriple(name, "", "");
snode = new XMLNode(triple,attr);
assertTrue( snode != null );
assertTrue( snode.getNumChildren() == 0 );
assertTrue( !snode.getName().equals( "test") == false );
assertTrue( snode.getPrefix().equals("") == true );
assertTrue( snode.getURI().equals("") == true );
assertTrue( snode.isElement() == true );
assertTrue( snode.isStart() == true );
assertTrue( snode.isEnd() == false );
assertTrue( snode.isText() == false );
cattr = snode.getAttributes();
assertTrue( cattr != null );
assertTrue( !cattr.getName(0).equals( "id" ) == false );
assertTrue( !cattr.getValue(0).equals( "value") == false );
assertTrue( cattr.getPrefix(0).equals("") == true );
assertTrue( cattr.getURI(0).equals("") == true );
enode = new XMLNode(triple);
assertTrue( enode != null );
assertTrue( enode.getNumChildren() == 0 );
assertTrue( !enode.getName().equals( "test") == false );
assertTrue( enode.getPrefix().equals("") == true );
assertTrue( enode.getURI().equals("") == true );
assertTrue( enode.isElement() == true );
assertTrue( enode.isStart() == false );
assertTrue( enode.isEnd() == true );
assertTrue( enode.isText() == false );
tnode = new XMLNode(text);
assertTrue( tnode != null );
assertTrue( !tnode.getCharacters().equals(text) == false );
assertTrue( tnode.getNumChildren() == 0 );
assertTrue( tnode.getName().equals("") == true );
assertTrue( tnode.getPrefix().equals("") == true );
assertTrue( tnode.getURI().equals("") == true );
assertTrue( tnode.isElement() == false );
assertTrue( tnode.isStart() == false );
assertTrue( tnode.isEnd() == false );
assertTrue( tnode.isText() == true );
triple = null;
attr = null;
snode = null;
enode = null;
tnode = null;
}
public void test_XMLNode_createFromToken()
{
XMLToken token;
XMLTriple triple;
XMLNode node;
triple = new XMLTriple("attr", "uri", "prefix");
token = new XMLToken(triple);
node = new XMLNode(token);
assertTrue( node != null );
assertTrue( node.getNumChildren() == 0 );
assertTrue( !node.getName().equals( "attr") == false );
assertTrue( !node.getPrefix().equals( "prefix") == false );
assertTrue( !node.getURI().equals( "uri") == false );
assertTrue( node.getChild(1) != null );
token = null;
triple = null;
node = null;
}
public void test_XMLNode_getters()
{
XMLToken token;
XMLNode node;
XMLTriple triple;
XMLAttributes attr;
XMLNamespaces NS;
NS = new XMLNamespaces();
NS.add( "http://test1.org/", "test1");
token = new XMLToken("This is a test");
node = new XMLNode(token);
assertTrue( node != null );
assertTrue( node.getNumChildren() == 0 );
assertTrue( !node.getCharacters().equals( "This is a test") == false );
assertTrue( node.getChild(1) != null );
attr = new XMLAttributes();
assertTrue( attr != null );
attr.add( "attr2", "value");
triple = new XMLTriple("attr", "uri", "prefix");
token = new XMLToken(triple,attr);
assertTrue( token != null );
node = new XMLNode(token);
assertTrue( !node.getName().equals( "attr") == false );
assertTrue( !node.getURI().equals( "uri") == false );
assertTrue( !node.getPrefix().equals( "prefix") == false );
XMLAttributes returnattr = node.getAttributes();
assertTrue( !returnattr.getName(0).equals( "attr2") == false );
assertTrue( !returnattr.getValue(0).equals( "value") == false );
token = new XMLToken(triple,attr,NS);
node = new XMLNode(token);
XMLNamespaces returnNS = node.getNamespaces();
assertTrue( returnNS.getLength() == 1 );
assertTrue( returnNS.isEmpty() == false );
triple = null;
token = null;
node = null;
}
public void test_XMLNode_insert()
{
XMLAttributes attr = new XMLAttributes();
XMLTriple trp_p = new XMLTriple("parent","","");
XMLTriple trp_c1 = new XMLTriple("child1","","");
XMLTriple trp_c2 = new XMLTriple("child2","","");
XMLTriple trp_c3 = new XMLTriple("child3","","");
XMLTriple trp_c4 = new XMLTriple("child4","","");
XMLTriple trp_c5 = new XMLTriple("child5","","");
XMLNode p = new XMLNode(trp_p,attr);
XMLNode c1 = new XMLNode(trp_c1,attr);
XMLNode c2 = new XMLNode(trp_c2,attr);
XMLNode c3 = new XMLNode(trp_c3,attr);
XMLNode c4 = new XMLNode(trp_c4,attr);
XMLNode c5 = new XMLNode(trp_c5,attr);
p.addChild(c2);
p.addChild(c4);
p.insertChild(0,c1);
p.insertChild(2,c3);
p.insertChild(4,c5);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(0).getName().equals( "child1") == false );
assertTrue( !p.getChild(1).getName().equals( "child2") == false );
assertTrue( !p.getChild(2).getName().equals( "child3") == false );
assertTrue( !p.getChild(3).getName().equals( "child4") == false );
assertTrue( !p.getChild(4).getName().equals( "child5") == false );
p.removeChildren();
p.insertChild(0,c1);
p.insertChild(0,c2);
p.insertChild(0,c3);
p.insertChild(0,c4);
p.insertChild(0,c5);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(0).getName().equals( "child5") == false );
assertTrue( !p.getChild(1).getName().equals( "child4") == false );
assertTrue( !p.getChild(2).getName().equals( "child3") == false );
assertTrue( !p.getChild(3).getName().equals( "child2") == false );
assertTrue( !p.getChild(4).getName().equals( "child1") == false );
p.removeChildren();
p.insertChild(1,c1);
p.insertChild(2,c2);
p.insertChild(3,c3);
p.insertChild(4,c4);
p.insertChild(5,c5);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(0).getName().equals( "child1") == false );
assertTrue( !p.getChild(1).getName().equals( "child2") == false );
assertTrue( !p.getChild(2).getName().equals( "child3") == false );
assertTrue( !p.getChild(3).getName().equals( "child4") == false );
assertTrue( !p.getChild(4).getName().equals( "child5") == false );
p.removeChildren();
XMLNode tmp;
tmp = p.insertChild(0,c1);
assertTrue( !tmp.getName().equals("child1") == false );
tmp = p.insertChild(0,c2);
assertTrue( !tmp.getName().equals("child2") == false );
tmp = p.insertChild(0,c3);
assertTrue( !tmp.getName().equals("child3") == false );
tmp = p.insertChild(0,c4);
assertTrue( !tmp.getName().equals("child4") == false );
tmp = p.insertChild(0,c5);
assertTrue( !tmp.getName().equals("child5") == false );
p.removeChildren();
tmp = p.insertChild(1,c1);
assertTrue( !tmp.getName().equals("child1") == false );
tmp = p.insertChild(2,c2);
assertTrue( !tmp.getName().equals("child2") == false );
tmp = p.insertChild(3,c3);
assertTrue( !tmp.getName().equals("child3") == false );
tmp = p.insertChild(4,c4);
assertTrue( !tmp.getName().equals("child4") == false );
tmp = p.insertChild(5,c5);
assertTrue( !tmp.getName().equals("child5") == false );
p = null;
c1 = null;
c2 = null;
c3 = null;
c4 = null;
c5 = null;
attr = null;
trp_p = null;
trp_c1 = null;
trp_c2 = null;
trp_c3 = null;
trp_c4 = null;
trp_c5 = null;
}
public void test_XMLNode_namespace_add()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
assertTrue( node.getNamespacesLength() == 0 );
assertTrue( node.isNamespacesEmpty() == true );
node.addNamespace( "http://test1.org/", "test1");
assertTrue( node.getNamespacesLength() == 1 );
assertTrue( node.isNamespacesEmpty() == false );
node.addNamespace( "http://test2.org/", "test2");
assertTrue( node.getNamespacesLength() == 2 );
assertTrue( node.isNamespacesEmpty() == false );
node.addNamespace( "http://test1.org/", "test1a");
assertTrue( node.getNamespacesLength() == 3 );
assertTrue( node.isNamespacesEmpty() == false );
node.addNamespace( "http://test1.org/", "test1a");
assertTrue( node.getNamespacesLength() == 3 );
assertTrue( node.isNamespacesEmpty() == false );
assertTrue( ! (node.getNamespaceIndex( "http://test1.org/") == -1) );
node = null;
triple = null;
attr = null;
}
public void test_XMLNode_namespace_get()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
node.addNamespace( "http://test6.org/", "test6");
node.addNamespace( "http://test7.org/", "test7");
node.addNamespace( "http://test8.org/", "test8");
node.addNamespace( "http://test9.org/", "test9");
assertTrue( node.getNamespacesLength() == 9 );
assertTrue( node.getNamespaceIndex( "http://test1.org/") == 0 );
assertTrue( !node.getNamespacePrefix(1).equals( "test2") == false );
assertTrue( !node.getNamespacePrefix( "http://test1.org/").equals( "test1") == false );
assertTrue( !node.getNamespaceURI(1).equals( "http://test2.org/") == false );
assertTrue( !node.getNamespaceURI( "test2").equals( "http://test2.org/") == false );
assertTrue( node.getNamespaceIndex( "http://test1.org/") == 0 );
assertTrue( node.getNamespaceIndex( "http://test2.org/") == 1 );
assertTrue( node.getNamespaceIndex( "http://test5.org/") == 4 );
assertTrue( node.getNamespaceIndex( "http://test9.org/") == 8 );
assertTrue( node.getNamespaceIndex( "http://testX.org/") == -1 );
assertTrue( node.hasNamespaceURI( "http://test1.org/") != false );
assertTrue( node.hasNamespaceURI( "http://test2.org/") != false );
assertTrue( node.hasNamespaceURI( "http://test5.org/") != false );
assertTrue( node.hasNamespaceURI( "http://test9.org/") != false );
assertTrue( node.hasNamespaceURI( "http://testX.org/") == false );
assertTrue( node.getNamespaceIndexByPrefix( "test1") == 0 );
assertTrue( node.getNamespaceIndexByPrefix( "test5") == 4 );
assertTrue( node.getNamespaceIndexByPrefix( "test9") == 8 );
assertTrue( node.getNamespaceIndexByPrefix( "testX") == -1 );
assertTrue( node.hasNamespacePrefix( "test1") != false );
assertTrue( node.hasNamespacePrefix( "test5") != false );
assertTrue( node.hasNamespacePrefix( "test9") != false );
assertTrue( node.hasNamespacePrefix( "testX") == false );
assertTrue( node.hasNamespaceNS( "http://test1.org/", "test1") != false );
assertTrue( node.hasNamespaceNS( "http://test5.org/", "test5") != false );
assertTrue( node.hasNamespaceNS( "http://test9.org/", "test9") != false );
assertTrue( node.hasNamespaceNS( "http://testX.org/", "testX") == false );
node = null;
triple = null;
attr = null;
}
public void test_XMLNode_namespace_remove()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
assertTrue( node.getNamespacesLength() == 5 );
node.removeNamespace(4);
assertTrue( node.getNamespacesLength() == 4 );
node.removeNamespace(3);
assertTrue( node.getNamespacesLength() == 3 );
node.removeNamespace(2);
assertTrue( node.getNamespacesLength() == 2 );
node.removeNamespace(1);
assertTrue( node.getNamespacesLength() == 1 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 0 );
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
assertTrue( node.getNamespacesLength() == 5 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 4 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 3 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 2 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 1 );
node.removeNamespace(0);
assertTrue( node.getNamespacesLength() == 0 );
node = null;
triple = null;
attr = null;
}
public void test_XMLNode_namespace_remove_by_prefix()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
assertTrue( node.getNamespacesLength() == 5 );
node.removeNamespace( "test1");
assertTrue( node.getNamespacesLength() == 4 );
node.removeNamespace( "test2");
assertTrue( node.getNamespacesLength() == 3 );
node.removeNamespace( "test3");
assertTrue( node.getNamespacesLength() == 2 );
node.removeNamespace( "test4");
assertTrue( node.getNamespacesLength() == 1 );
node.removeNamespace( "test5");
assertTrue( node.getNamespacesLength() == 0 );
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
assertTrue( node.getNamespacesLength() == 5 );
node.removeNamespace( "test5");
assertTrue( node.getNamespacesLength() == 4 );
node.removeNamespace( "test4");
assertTrue( node.getNamespacesLength() == 3 );
node.removeNamespace( "test3");
assertTrue( node.getNamespacesLength() == 2 );
node.removeNamespace( "test2");
assertTrue( node.getNamespacesLength() == 1 );
node.removeNamespace( "test1");
assertTrue( node.getNamespacesLength() == 0 );
node.addNamespace( "http://test1.org/", "test1");
node.addNamespace( "http://test2.org/", "test2");
node.addNamespace( "http://test3.org/", "test3");
node.addNamespace( "http://test4.org/", "test4");
node.addNamespace( "http://test5.org/", "test5");
assertTrue( node.getNamespacesLength() == 5 );
node.removeNamespace( "test3");
assertTrue( node.getNamespacesLength() == 4 );
node.removeNamespace( "test1");
assertTrue( node.getNamespacesLength() == 3 );
node.removeNamespace( "test4");
assertTrue( node.getNamespacesLength() == 2 );
node.removeNamespace( "test5");
assertTrue( node.getNamespacesLength() == 1 );
node.removeNamespace( "test2");
assertTrue( node.getNamespacesLength() == 0 );
node = null;
triple = null;
attr = null;
}
public void test_XMLNode_namespace_set_clear()
{
XMLTriple triple = new XMLTriple("test","","");
XMLAttributes attr = new XMLAttributes();
XMLNode node = new XMLNode(triple,attr);
XMLNamespaces ns = new XMLNamespaces();
assertTrue( node.getNamespacesLength() == 0 );
assertTrue( node.isNamespacesEmpty() == true );
ns.add( "http://test1.org/", "test1");
ns.add( "http://test2.org/", "test2");
ns.add( "http://test3.org/", "test3");
ns.add( "http://test4.org/", "test4");
ns.add( "http://test5.org/", "test5");
node.setNamespaces(ns);
assertTrue( node.getNamespacesLength() == 5 );
assertTrue( node.isNamespacesEmpty() == false );
assertTrue( !node.getNamespacePrefix(0).equals( "test1") == false );
assertTrue( !node.getNamespacePrefix(1).equals( "test2") == false );
assertTrue( !node.getNamespacePrefix(2).equals( "test3") == false );
assertTrue( !node.getNamespacePrefix(3).equals( "test4") == false );
assertTrue( !node.getNamespacePrefix(4).equals( "test5") == false );
assertTrue( !node.getNamespaceURI(0).equals( "http://test1.org/") == false );
assertTrue( !node.getNamespaceURI(1).equals( "http://test2.org/") == false );
assertTrue( !node.getNamespaceURI(2).equals( "http://test3.org/") == false );
assertTrue( !node.getNamespaceURI(3).equals( "http://test4.org/") == false );
assertTrue( !node.getNamespaceURI(4).equals( "http://test5.org/") == false );
node.clearNamespaces();
assertTrue( node.getNamespacesLength() == 0 );
assertTrue( node.isAttributesEmpty() != false );
ns = null;
node = null;
triple = null;
attr = null;
}
public void test_XMLNode_remove()
{
XMLAttributes attr = new XMLAttributes();
XMLTriple trp_p = new XMLTriple("parent","","");
XMLTriple trp_c1 = new XMLTriple("child1","","");
XMLTriple trp_c2 = new XMLTriple("child2","","");
XMLTriple trp_c3 = new XMLTriple("child3","","");
XMLTriple trp_c4 = new XMLTriple("child4","","");
XMLTriple trp_c5 = new XMLTriple("child5","","");
XMLNode p = new XMLNode(trp_p,attr);
XMLNode c1 = new XMLNode(trp_c1,attr);
XMLNode c2 = new XMLNode(trp_c2,attr);
XMLNode c3 = new XMLNode(trp_c3,attr);
XMLNode c4 = new XMLNode(trp_c4,attr);
XMLNode c5 = new XMLNode(trp_c5,attr);
XMLNode r;
p.addChild(c1);
p.addChild(c2);
p.addChild(c3);
p.addChild(c4);
p.addChild(c5);
r = p.removeChild(5);
assertTrue( r == null );
r = p.removeChild(1);
assertTrue( p.getNumChildren() == 4 );
assertTrue( !r.getName().equals("child2") == false );
r = null;
r = p.removeChild(3);
assertTrue( p.getNumChildren() == 3 );
assertTrue( !r.getName().equals("child5") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 2 );
assertTrue( !r.getName().equals("child1") == false );
r = null;
r = p.removeChild(1);
assertTrue( p.getNumChildren() == 1 );
assertTrue( !r.getName().equals("child4") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 0 );
assertTrue( !r.getName().equals("child3") == false );
r = null;
p.addChild(c1);
p.addChild(c2);
p.addChild(c3);
p.addChild(c4);
p.addChild(c5);
r = p.removeChild(4);
assertTrue( p.getNumChildren() == 4 );
assertTrue( !r.getName().equals("child5") == false );
r = null;
r = p.removeChild(3);
assertTrue( p.getNumChildren() == 3 );
assertTrue( !r.getName().equals("child4") == false );
r = null;
r = p.removeChild(2);
assertTrue( p.getNumChildren() == 2 );
assertTrue( !r.getName().equals("child3") == false );
r = null;
r = p.removeChild(1);
assertTrue( p.getNumChildren() == 1 );
assertTrue( !r.getName().equals("child2") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 0 );
assertTrue( !r.getName().equals("child1") == false );
r = null;
p.addChild(c1);
p.addChild(c2);
p.addChild(c3);
p.addChild(c4);
p.addChild(c5);
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 4 );
assertTrue( !r.getName().equals("child1") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 3 );
assertTrue( !r.getName().equals("child2") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 2 );
assertTrue( !r.getName().equals("child3") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 1 );
assertTrue( !r.getName().equals("child4") == false );
r = null;
r = p.removeChild(0);
assertTrue( p.getNumChildren() == 0 );
assertTrue( !r.getName().equals("child5") == false );
r = null;
p.addChild(c1);
p.addChild(c2);
p.addChild(c3);
p.addChild(c4);
p.addChild(c5);
r = p.removeChild(0);
assertTrue( !r.getName().equals("child1") == false );
p.insertChild(0,r);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(0).getName().equals("child1") == false );
r = null;
r = p.removeChild(1);
assertTrue( !r.getName().equals("child2") == false );
p.insertChild(1,r);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(1).getName().equals("child2") == false );
r = null;
r = p.removeChild(2);
assertTrue( !r.getName().equals("child3") == false );
p.insertChild(2,r);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(2).getName().equals("child3") == false );
r = null;
r = p.removeChild(3);
assertTrue( !r.getName().equals("child4") == false );
p.insertChild(3,r);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(3).getName().equals("child4") == false );
r = null;
r = p.removeChild(4);
assertTrue( !r.getName().equals("child5") == false );
p.insertChild(4,r);
assertTrue( p.getNumChildren() == 5 );
assertTrue( !p.getChild(4).getName().equals("child5") == false );
r = null;
p = null;
c1 = null;
c2 = null;
c3 = null;
c4 = null;
c5 = null;
attr = null;
trp_p = null;
trp_c1 = null;
trp_c2 = null;
trp_c3 = null;
trp_c4 = null;
trp_c5 = null;
}
/**
* Loads the SWIG-generated libSBML Java module when this class is
* loaded, or reports a sensible diagnostic message about why it failed.
*/
static
{
String varname;
String shlibname;
if (System.getProperty("mrj.version") != null)
{
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
shlibname = "libsbmlj.jnilib and/or libsbml.dylib";
}
else
{
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
shlibname = "libsbmlj.so and/or libsbml.so";
}
try
{
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (SecurityException e)
{
e.printStackTrace();
System.err.println("Could not load the libSBML library files due to a"+
" security exception.\n");
System.exit(1);
}
catch (UnsatisfiedLinkError e)
{
e.printStackTrace();
System.err.println("Error: could not link with the libSBML library files."+
" It is likely\nyour " + varname +
" environment variable does not include the directories\n"+
"containing the " + shlibname + " library files.\n");
System.exit(1);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.err.println("Error: unable to load the file libsbmlj.jar."+
" It is likely\nyour -classpath option and CLASSPATH" +
" environment variable\n"+
"do not include the path to libsbmlj.jar.\n");
System.exit(1);
}
}
}
| alexholehouse/SBMLIntegrator | libsbml-5.0.0/src/bindings/java/test/org/sbml/libsbml/test/xml/TestXMLNode.java | Java | gpl-3.0 | 44,048 |
/**********************************************************************
* Copyright (c) 2011 by the President and Fellows of Harvard College
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Contact information
*
* Office for Information Systems
* Harvard University Library
* Harvard University
* Cambridge, MA 02138
* (617)495-3724
* [email protected]
**********************************************************************/
package edu.harvard.hul.ois.ots.schemas.AES;
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
public class LayerTest extends junit.framework.TestCase {
/** Sample string for testing */
private final static String layerSample =
"<layer composition=\"123456\" order=\"1\" role=\"PROTECTIVE_LAYER\">\n" +
" <thickness unit=\"MILLIMETRES\">1</thickness>\n" +
"</layer>";
public void testRead () throws Exception {
// set up a parser
XMLInputFactory xmlif = XMLInputFactory.newInstance();
XMLStreamReader xmlr =
xmlif.createXMLStreamReader(new StringReader(layerSample));
xmlr.nextTag();
Layer la = new Layer (xmlr);
assertEquals ("123456", la.getComposition());
assertEquals ("PROTECTIVE_LAYER", la.getRole ());
assertEquals ((Integer) 1, la.getOrder ());
Measurement th = la.getThickness();
assertEquals ("MILLIMETRES", th.getUnit());
assertEquals ((Double) 1.0, th.toValue());
}
}
| opf-labs/ots-schema | test/edu/harvard/hul/ois/ots/schemas/AES/LayerTest.java | Java | gpl-3.0 | 2,208 |
/*
* Copyright (C) 2013 The OmniROM Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.android.systemui.tuner;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.android.systemui.R;
public class SeekBarPreference extends Preference implements
OnSeekBarChangeListener {
public static int maximum = 100;
public static int interval = 5;
private TextView monitorBox;
private SeekBar bar;
int currentValue = 100;
private OnPreferenceChangeListener changer;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected View onCreateView(ViewGroup parent) {
View layout = View.inflate(getContext(), R.layout.qs_slider_preference,
null);
monitorBox = (TextView) layout.findViewById(R.id.monitor_box);
bar = (SeekBar) layout.findViewById(R.id.seek_bar);
bar.setProgress(currentValue);
monitorBox.setText(String.valueOf(currentValue) + "%");
bar.setOnSeekBarChangeListener(this);
return layout;
}
public void setInitValue(int progress) {
currentValue = progress;
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// TODO Auto-generated method stub
return super.onGetDefaultValue(a, index);
}
@Override
public void setOnPreferenceChangeListener(
OnPreferenceChangeListener onPreferenceChangeListener) {
changer = onPreferenceChangeListener;
super.setOnPreferenceChangeListener(onPreferenceChangeListener);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
progress = Math.round(((float) progress) / interval) * interval;
currentValue = progress;
monitorBox.setText(String.valueOf(progress) + "%");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
changer.onPreferenceChange(this, Integer.toString(currentValue));
}
}
| OmniEvo/android_frameworks_base | packages/SystemUI/src/com/android/systemui/tuner/SeekBarPreference.java | Java | gpl-3.0 | 3,019 |
package com.example.channelmanager;
/**
* Created by Administrator on 2017/2/7.
* 频道列表
*/
public class ProjectChannelBean {
private String topicid;
// 设置该标签是否可编辑,如果出现在我的频道中,且值为1,则可在右上角显示删除按钮
private int editStatus;
private String cid;
private String tname;
private String ename;
// 标签类型,显示是我的频道还是更多频道
private int tabType;
private String tid;
private String column;
public ProjectChannelBean(){}
public ProjectChannelBean(String tname, String tid){
this.tname = tname;
this.tid = tid;
}
public ProjectChannelBean(String tname, String column, String tid){
this.tname = tname;
this.column = column;
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public int getTabType() {
return tabType;
}
public void setTabType(int tabType) {
this.tabType = tabType;
}
public int getEditStatus() {
return editStatus;
}
public void setEditStatus(int editStatus) {
this.editStatus = editStatus;
}
public String getTopicid() {
return topicid;
}
public void setTopicid(String topicid) {
this.topicid = topicid;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
}
| liaozhoubei/NetEasyNews | channelmanager/src/main/java/com/example/channelmanager/ProjectChannelBean.java | Java | gpl-3.0 | 1,956 |
/*
* Copyright (C) 2016 Douglas Wurtele
*
* 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 org.wurtele.ArmyTracker.models.enumerations;
/**
*
* @author Douglas Wurtele
*/
public enum AbsenceStatusType {
SUBMITTED,
APPROVED,
DISAPPROVED;
}
| dougwurtele/Army-Tracker | src/main/java/org/wurtele/ArmyTracker/models/enumerations/AbsenceStatusType.java | Java | gpl-3.0 | 857 |
package org.zarroboogs.weibo.widget.galleryview;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
public abstract class VersionedGestureDetector {
static final String LOG_TAG = "VersionedGestureDetector";
OnGestureListener mListener;
public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) {
final int sdkVersion = Build.VERSION.SDK_INT;
VersionedGestureDetector detector = null;
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
detector = new CupcakeDetector(context);
} else if (sdkVersion < Build.VERSION_CODES.FROYO) {
detector = new EclairDetector(context);
} else {
detector = new FroyoDetector(context);
}
detector.mListener = listener;
return detector;
}
public abstract boolean onTouchEvent(MotionEvent ev);
public abstract boolean isScaling();
public static interface OnGestureListener {
public void onDrag(float dx, float dy);
public void onFling(float startX, float startY, float velocityX, float velocityY);
public void onScale(float scaleFactor, float focusX, float focusY);
}
private static class CupcakeDetector extends VersionedGestureDetector {
float mLastTouchX;
float mLastTouchY;
final float mTouchSlop;
final float mMinimumVelocity;
public CupcakeDetector(Context context) {
final ViewConfiguration configuration = ViewConfiguration.get(context);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mTouchSlop = configuration.getScaledTouchSlop();
}
private VelocityTracker mVelocityTracker;
private boolean mIsDragging;
float getActiveX(MotionEvent ev) {
return ev.getX();
}
float getActiveY(MotionEvent ev) {
return ev.getY();
}
public boolean isScaling() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
mIsDragging = false;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = getActiveX(ev);
final float y = getActiveY(ev);
final float dx = x - mLastTouchX, dy = y - mLastTouchY;
if (!mIsDragging) {
// Use Pythagoras to see if drag length is larger than
// touch slop
mIsDragging = FloatMath.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
}
if (mIsDragging) {
mListener.onDrag(dx, dy);
mLastTouchX = x;
mLastTouchY = y;
if (null != mVelocityTracker) {
mVelocityTracker.addMovement(ev);
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
case MotionEvent.ACTION_UP: {
if (mIsDragging) {
if (null != mVelocityTracker) {
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
// Compute velocity within the last 1000ms
mVelocityTracker.addMovement(ev);
mVelocityTracker.computeCurrentVelocity(1000);
final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity();
// If the velocity is greater than minVelocity, call
// listener
if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) {
mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY);
}
}
}
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
}
return true;
}
}
@TargetApi(5)
private static class EclairDetector extends CupcakeDetector {
private static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private int mActivePointerIndex = 0;
public EclairDetector(Context context) {
super(context);
}
@Override
float getActiveX(MotionEvent ev) {
try {
return ev.getX(mActivePointerIndex);
} catch (Exception e) {
return ev.getX();
}
}
@Override
float getActiveY(MotionEvent ev) {
try {
return ev.getY(mActivePointerIndex);
} catch (Exception e) {
return ev.getY();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP:
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
}
break;
}
mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0);
return super.onTouchEvent(ev);
}
}
@TargetApi(8)
private static class FroyoDetector extends EclairDetector {
private final ScaleGestureDetector mDetector;
// Needs to be an inner class so that we don't hit
// VerifyError's on API 4.
private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY());
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
// NO-OP
}
};
public FroyoDetector(Context context) {
super(context);
mDetector = new ScaleGestureDetector(context, mScaleListener);
}
@Override
public boolean isScaling() {
return mDetector.isInProgress();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
}
}
| MehmetNuri/Beebo | app/src/main/java/org/zarroboogs/weibo/widget/galleryview/VersionedGestureDetector.java | Java | gpl-3.0 | 8,826 |
/*
* IIIFProducer
* Copyright (C) 2017 Leipzig University Library <[email protected]>
*
* 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 de.ubleipzig.iiifproducer.template;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.File;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
public class SerializerExceptionTest {
@Mock
private TemplateStructure mockStructure;
@BeforeEach
public void setUp() {
initMocks(this);
when(mockStructure.getStructureLabel()).thenReturn("a structure");
}
@Test
public void testError() {
when(mockStructure.getStructureLabel()).thenAnswer(inv -> {
sneakyJsonException();
return "a structure";
});
final Optional<String> json = ManifestSerializer.serialize(mockStructure);
assertFalse(json.isPresent());
}
@Test
void testIOException() {
final String json = "{}";
final File outfile = new File("/an-invalid-path");
assertEquals(false, ManifestSerializer.writeToFile(json, outfile));
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow(final Throwable e) throws T {
throw (T) e;
}
private static void sneakyJsonException() {
sneakyThrow(new JsonProcessingException("expected") {
});
}
}
| ubleipzig/iiif-producer | templates/src/test/java/de/ubleipzig/iiifproducer/template/SerializerExceptionTest.java | Java | gpl-3.0 | 2,279 |
package com.github.ypid.complexalarm;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import com.evgenii.jsevaluator.JsEvaluator;
import com.evgenii.jsevaluator.JsFunctionCallFormatter;
import com.evgenii.jsevaluator.interfaces.JsCallback;
/*
* Simple wrapper for the API documented here:
* https://github.com/ypid/opening_hours.js#library-api
*/
public class OpeningHours {
private JsEvaluator mJsEvaluator;
final private String nominatiomTestJSONString = "{\"place_id\":\"44651229\",\"licence\":\"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\"osm_type\":\"way\",\"osm_id\":\"36248375\",\"lat\":\"49.5400039\",\"lon\":\"9.7937133\",\"display_name\":\"K 2847, Lauda-K\u00f6nigshofen, Main-Tauber-Kreis, Regierungsbezirk Stuttgart, Baden-W\u00fcrttemberg, Germany, European Union\",\"address\":{\"road\":\"K 2847\",\"city\":\"Lauda-K\u00f6nigshofen\",\"county\":\"Main-Tauber-Kreis\",\"state_district\":\"Regierungsbezirk Stuttgart\",\"state\":\"Baden-W\u00fcrttemberg\",\"country\":\"Germany\",\"country_code\":\"de\",\"continent\":\"European Union\"}}";
private Scanner scanner;
private String globalResult;
private String getFileContent(String fileName, Context context)
throws IOException {
final AssetManager am = context.getAssets();
final InputStream inputStream = am.open(fileName);
scanner = new Scanner(inputStream, "UTF-8");
return scanner.useDelimiter("\\A").next();
}
private String loadJs(String fileName, Context context) {
try {
return getFileContent(fileName, context);
} catch (final IOException e) {
e.printStackTrace();
}
return null;
}
protected OpeningHours(Context context) {
Log.d("OpeningHours", "Loading up opening_hours.js");
mJsEvaluator = new JsEvaluator(context);
String librarySrouce = loadJs("javascript-libs/suncalc/suncalc.min.js",
context);
mJsEvaluator.evaluate(librarySrouce);
librarySrouce = loadJs(
"javascript-libs/opening_hours/opening_hours.min.js", context);
mJsEvaluator.evaluate(librarySrouce);
}
protected String evalOpeningHours(String value, String nominatiomJSON,
byte oh_mode) {
String ohConstructorCall = "new opening_hours('" + value
+ "', JSON.parse('" + nominatiomJSON + "'), " + oh_mode + ")";
Log.d("OpeningHours constructor", ohConstructorCall);
final String code = "var oh, warnings, crashed = true;" + "try {"
+ " oh = " + ohConstructorCall + ";"
+ " warnings = oh.getWarnings();" + " crashed = false;"
+ "} catch(err) {" + " crashed = err;" + "}"
+ "oh.getNextChange().toString();" +
// "crashed.toString();" +
"";
mJsEvaluator.evaluate(code, new JsCallback() {
@Override
public void onResult(final String resultValue) {
Log.d("OpeningHours", String.format("Result: %s", resultValue));
}
});
return "test";
}
protected String getDate() {
globalResult = null;
mJsEvaluator.evaluate("new Date().toString()", new JsCallback() {
@Override
public void onResult(final String resultValue) {
Log.d("Date", String.format("Result: %s", resultValue));
// Block until event occurs.
globalResult = resultValue;
Log.d("Date", String.format("globalResult: %s", globalResult));
}
});
for (int i = 0; i < 100; i++) {
Log.d("Date", String.format("%d, %s", i, globalResult));
try {
Log.d("Date", "sleep");
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d("Date", "Catch");
e.printStackTrace();
}
if (globalResult != null) {
break;
}
}
return globalResult;
}
protected String returnDate() {
return globalResult;
}
protected String evalOpeningHours(String value, String nominatiomJSON) {
return evalOpeningHours(value, nominatiomJSON, (byte) 0);
}
protected String evalOpeningHours(String value) {
// evalOpeningHours(value, "{}");
return evalOpeningHours(value, nominatiomTestJSONString); // FIXME
// testing
// only
}
}
| ypid/ComplexAlarm | src/com/github/ypid/complexalarm/OpeningHours.java | Java | gpl-3.0 | 4,883 |
/**
* Copyright (c) 2000-2004 Liferay, LLC. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dotmarketing.portlets.mailinglists.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.dotcms.repackage.portlet.javax.portlet.PortletConfig;
import com.dotcms.repackage.portlet.javax.portlet.RenderRequest;
import com.dotcms.repackage.portlet.javax.portlet.RenderResponse;
import com.dotcms.repackage.portlet.javax.portlet.WindowState;
import javax.servlet.jsp.PageContext;
import com.dotcms.repackage.commons_beanutils.org.apache.commons.beanutils.BeanUtils;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionForm;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionForward;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionMapping;
import com.dotmarketing.business.Role;
import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory;
import com.dotmarketing.portlets.mailinglists.model.MailingList;
import com.dotmarketing.portlets.userfilter.factories.UserFilterFactory;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portal.util.Constants;
/**
* <a href="ViewQuestionsAction.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
* @version $Revision: 1.4 $
*
*/
public class ViewMailingListsAction extends PortletAction {
public ActionForward render(
ActionMapping mapping, ActionForm form, PortletConfig config,
RenderRequest req, RenderResponse res)
throws Exception {
Logger.debug(this, "Running ViewMailingListsAction");
try {
//get the user, order, direction
User user = com.liferay.portal.util.PortalUtil.getUser(req);
String orderBy = req.getParameter("orderby");
String direction = req.getParameter("direction");
String condition = req.getParameter("query");
//get their lists
List list = null;
List roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(user.getUserId());
boolean isMarketingAdmin = false;
Iterator rolesIt = roles.iterator();
while (rolesIt.hasNext()) {
Role role = (Role) rolesIt.next();
if (UtilMethods.isSet(role.getRoleKey()) && role.getRoleKey().equals(Config.getStringProperty("MAILINGLISTS_ADMIN_ROLE"))) {
isMarketingAdmin = true;
break;
}
}
if (isMarketingAdmin) {
if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) {
//list = MailingListFactory.getAllMailingLists(orderBy, direction);
list = MailingListFactory.getAllMailingLists();
list.addAll(UserFilterFactory.getAllUserFilter());
if (orderBy.equals("title")) {
if (direction.equals(" asc"))
Collections.sort(list, new ComparatorTitleAsc());
else
Collections.sort(list, new ComparatorTitleDesc());
}
} else if(UtilMethods.isSet(condition)) {
list = MailingListFactory.getAllMailingListsCondition(condition);
list.addAll(UserFilterFactory.getUserFilterByTitle(condition));
Collections.sort(list, new ComparatorTitleAsc());
} else {
list = MailingListFactory.getAllMailingLists();
list.addAll(UserFilterFactory.getAllUserFilter());
Collections.sort(list, new ComparatorTitleAsc());
}
} else {
if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) {
//list = MailingListFactory.getMailingListsByUser(user, orderBy, direction);
list = MailingListFactory.getMailingListsByUser(user);
list.add(MailingListFactory.getUnsubscribersMailingList());
list.addAll(UserFilterFactory.getAllUserFilterByUser(user));
if (orderBy.equals("title")) {
if (direction.equals(" asc"))
Collections.sort(list, new ComparatorTitleAsc());
else
Collections.sort(list, new ComparatorTitleDesc());
}
} else if(UtilMethods.isSet(condition)) {
list = MailingListFactory.getMailingListsByUserCondition(user, condition);
list.add(MailingListFactory.getUnsubscribersMailingList());
list.addAll(UserFilterFactory.getUserFilterByTitleAndUser(condition, user));
Collections.sort(list, new ComparatorTitleAsc());
} else {
list = MailingListFactory.getMailingListsByUser(user);
list.add(MailingListFactory.getUnsubscribersMailingList());
list.addAll(UserFilterFactory.getAllUserFilterByUser(user));
Collections.sort(list, new ComparatorTitleAsc());
}
}
if (req.getWindowState().equals(WindowState.NORMAL)) {
// if (list != null)
// list = orderMailingListByDescDate(list);
req.setAttribute(WebKeys.MAILING_LIST_VIEW_PORTLET, list);
return mapping.findForward("portlet.ext.mailinglists.view");
}
else {
req.setAttribute(WebKeys.MAILING_LIST_VIEW, list);
return mapping.findForward("portlet.ext.mailinglists.view_mailinglists");
}
}
catch (Exception e) {
req.setAttribute(PageContext.EXCEPTION, e);
return mapping.findForward(Constants.COMMON_ERROR);
}
}
private List<MailingList> orderMailingListByDescDate(List<MailingList> list) {
List<MailingList> result = new ArrayList<MailingList>(list.size());
int i;
boolean added;
MailingList mailingList2;
for (MailingList mailingList1: list) {
if (result.size() == 0) {
result.add(mailingList1);
} else {
added = false;
for (i = 0; i < result.size(); ++i) {
mailingList2 = result.get(i);
if (mailingList2.getIDate().before(mailingList1.getIDate())) {
result.add(i, mailingList1);
added = true;
break;
}
}
if (!added)
result.add(mailingList1);
}
}
return result;
}
private class ComparatorTitleAsc implements Comparator {
public int compare(Object o1, Object o2) {
String title1, title2;
try {
if (o1 instanceof MailingList)
title1 = BeanUtils.getProperty(o1, "title");
else
title1 = BeanUtils.getProperty(o1, "userFilterTitle");
} catch (Exception e) {
title1 = "";
}
try {
if (o2 instanceof MailingList)
title2 = BeanUtils.getProperty(o2, "title");
else
title2 = BeanUtils.getProperty(o2, "userFilterTitle");
} catch (Exception e) {
title2 = "";
}
return title1.compareToIgnoreCase(title2);
}
}
private class ComparatorTitleDesc implements Comparator {
public int compare(Object o1, Object o2) {
String title1, title2;
try {
if (o1 instanceof MailingList)
title1 = BeanUtils.getProperty(o1, "title");
else
title1 = BeanUtils.getProperty(o1, "userFilterTitle");
} catch (Exception e) {
title1 = "";
}
try {
if (o2 instanceof MailingList)
title2 = BeanUtils.getProperty(o2, "title");
else
title2 = BeanUtils.getProperty(o2, "userFilterTitle");
} catch (Exception e) {
title2 = "";
}
return title2.compareToIgnoreCase(title1);
}
}
} | austindlawless/dotCMS | src/com/dotmarketing/portlets/mailinglists/action/ViewMailingListsAction.java | Java | gpl-3.0 | 8,207 |
/*
* Copyright (c) 2017 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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 org.obiba.mica.core.service;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import net.minidev.json.JSONArray;
import org.obiba.mica.core.domain.SchemaFormContentAware;
import org.obiba.mica.file.FileStoreService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.google.common.collect.Sets;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.internal.JsonReader;
import static com.jayway.jsonpath.Configuration.defaultConfiguration;
@Service
public class SchemaFormContentFileService {
@Inject
private FileStoreService fileStoreService;
public void save(@NotNull SchemaFormContentAware newEntity, SchemaFormContentAware oldEntity, String entityPath) {
Assert.notNull(newEntity, "New content cannot be null");
Object json = defaultConfiguration().jsonProvider().parse(newEntity.getContent());
DocumentContext newContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json);
Map<String, JSONArray> newPaths = getPathFilesMap(newContext, json);
if (newPaths == null) return; // content does not have any file field
if (oldEntity != null) {
Object oldJson = defaultConfiguration().jsonProvider().parse(oldEntity.getContent());
DocumentContext oldContext = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(oldJson);
Map<String, JSONArray> oldPaths = getPathFilesMap(oldContext, oldJson);
if (oldPaths != null) {
saveAndDelete(oldPaths, newPaths, entityPath);
} else {
// schema and definition now have files
newPaths.values().forEach(v -> saveFiles(v, entityPath));
}
} else {
newPaths.values().forEach(v -> saveFiles(v, entityPath));
}
cleanup(newPaths, newContext);
newEntity.setContent(newContext.jsonString());
}
public void deleteFiles(SchemaFormContentAware entity) {
Object json = defaultConfiguration().jsonProvider().parse(entity.getContent());
DocumentContext context = JsonPath.using(defaultConfiguration().addOptions(Option.AS_PATH_LIST)).parse(json);
DocumentContext reader =
new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);
try {
((JSONArray)context.read("$..obibaFiles")).stream()
.map(p -> (JSONArray) reader.read(p.toString()))
.flatMap(Collection::stream)
.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString()));
} catch(PathNotFoundException e) {
}
}
/**
* Removes the fields with empty obibaFiles from content.
*
* @param newPaths
* @param newContext
*/
private void cleanup(Map<String, JSONArray> newPaths, DocumentContext newContext) {
newPaths.keySet().forEach(p -> {
if (newPaths.get(p).isEmpty()) {
newContext.delete(p.replace("['obibaFiles']", ""));
}
});
}
private void saveAndDelete(Map<String, JSONArray> oldPaths, Map<String, JSONArray> newPaths, String entityPath) {
newPaths.keySet().forEach(p -> {
if (oldPaths.containsKey(p)) {
saveAndDeleteFiles(oldPaths.get(p), newPaths.get(p), entityPath);
} else {
saveFiles(newPaths.get(p), entityPath);
}
});
}
private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) {
DocumentContext reader =
new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);
JSONArray paths = null;
try {
paths = context.read("$..obibaFiles");
} catch(PathNotFoundException e) {
return null;
}
return paths.stream().collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString())));
}
private Iterable<Object> saveAndDeleteFiles(JSONArray oldFiles, JSONArray newFiles, String entityPath) {
cleanFileJsonArrays(oldFiles, newFiles);
Iterable<Object> toDelete = Sets.difference(Sets.newHashSet(oldFiles), Sets.newHashSet(newFiles));
Iterable<Object> toSave = Sets.difference(Sets.newHashSet(newFiles), Sets.newHashSet(oldFiles));
toDelete.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString()));
saveFiles(toSave, entityPath);
return toDelete;
}
private void cleanFileJsonArrays(JSONArray... arrays) {
if (arrays != null) {
Arrays.stream(arrays).forEach(s -> s.forEach(a -> {
if (a instanceof LinkedHashMap) {
LinkedHashMap<String, String> jsonMap = (LinkedHashMap<String, String>) a;
jsonMap.keySet().stream().filter(k -> k.contains("$")).collect(Collectors.toList()).forEach(jsonMap::remove);
}
}));
}
}
private void saveFiles(Iterable files, String entityPath) {
if(files != null) files.forEach(file -> {
LinkedHashMap map = (LinkedHashMap)file;
map.put("path", entityPath);
fileStoreService.save(map.get("id").toString());
});
}
}
| Rima-B/mica2 | mica-core/src/main/java/org/obiba/mica/core/service/SchemaFormContentFileService.java | Java | gpl-3.0 | 5,584 |
package com.dank.festivalapp.lib;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static final String DATABASE_NAME = "FestivalApp.db";
private static final int DATABASE_VERSION = 1;
private static DataBaseHelper mInstance = null;
private DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DataBaseHelper getInstance(Context ctx) {
/**
* use the application context as suggested by CommonsWare.
* this will ensure that you dont accidentally leak an Activitys
* context (see this article for more information:
* http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
*/
if (mInstance == null) {
mInstance = new DataBaseHelper(ctx);
}
return mInstance;
}
public boolean isTableExists(SQLiteDatabase db, String tableName)
{
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ tableName +"'", null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DataBaseHelper.class.getName(), "TODO ");
}
}
| dankl/festivalapp-lib | src/com/dank/festivalapp/lib/DataBaseHelper.java | Java | gpl-3.0 | 1,650 |
package ems.server.protocol;
import ems.server.domain.Device;
import ems.server.domain.EventSeverity;
import ems.server.domain.EventType;
import ems.server.utils.EventHelper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* EventAwareResponseHandler
* Created by thebaz on 9/15/14.
*/
public class EventAwareResponseHandler implements ResponseHandler {
private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
private final Device device;
public EventAwareResponseHandler(Device device) {
this.device = device;
format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override
public void onTimeout(String variable) {
EventHelper.getInstance().addEvent(device, EventType.EVENT_NETWORK, EventSeverity.EVENT_WARN);
}
@Override
public void onSuccess(String variable) {
//do nothing
}
@Override
public void onError(String variable, int errorCode, String errorDescription) {
EventSeverity eventSeverity = EventSeverity.EVENT_ERROR;
EventType eventType = EventType.EVENT_PROTOCOL;
String description = "Event of type: \'" + eventType + "\' at: " +
format.format(new Date(System.currentTimeMillis())) + " with severity: \'" +
eventSeverity + "\' for device: " + device.getName() + ". Error code:" +
errorCode + ", Error description: " + errorDescription;
EventHelper.getInstance().addEvent(device, eventType, eventSeverity, description);
}
}
| thebaz73/ems-server | src/main/java/ems/server/protocol/EventAwareResponseHandler.java | Java | gpl-3.0 | 1,600 |
/* This file is part of Arkhados.
Arkhados 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.
Arkhados 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 Arkhados. If not, see <http://www.gnu.org/licenses/>. */
package arkhados.spell.buffs.info;
import arkhados.controls.CRotation;
import arkhados.controls.CTrackLocation;
import arkhados.effects.BuffEffect;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
public class MineralArmorInfo extends BuffInfo {
{
setIconPath("Interface/Images/SpellIcons/MineralArmor.png");
}
@Override
public BuffEffect createBuffEffect(BuffInfoParameters params) {
MineralArmorEffect effect = new MineralArmorEffect(params.duration);
effect.addToCharacter(params);
return effect;
}
}
class MineralArmorEffect extends BuffEffect {
private Node centralNode = null;
public MineralArmorEffect(float timeLeft) {
super(timeLeft);
}
public void addToCharacter(BuffInfoParameters params) {
Node character = (Node) params.buffControl.getSpatial();
Spatial crystals1 = assets.loadModel("Models/crystals.j3o");
Spatial crystals2 = assets.loadModel("Models/crystals.j3o");
Spatial crystals3 = assets.loadModel("Models/crystals.j3o");
Spatial crystals4 = assets.loadModel("Models/crystals.j3o");
centralNode = new Node("mineral-armor-node");
centralNode.attachChild(crystals1);
centralNode.attachChild(crystals2);
centralNode.attachChild(crystals3);
centralNode.attachChild(crystals4);
crystals1.setLocalTranslation(-7.5f, 0f, 0f);
crystals2.setLocalTranslation(7.5f, 0f, 0f);
crystals3.setLocalTranslation(0f, 0f, -7.5f);
crystals4.setLocalTranslation(0f, 0f, 7.5f);
Node world = character.getParent();
world.attachChild(centralNode);
centralNode.addControl(
new CTrackLocation(character, new Vector3f(0f, 10f, 0f)));
centralNode.addControl(new CRotation(0f, 2f, 0f));
}
@Override
public void destroy() {
super.destroy();
centralNode.removeFromParent();
}
}
| TripleSnail/Arkhados | src/arkhados/spell/buffs/info/MineralArmorInfo.java | Java | gpl-3.0 | 2,655 |
/**
* Copyright (c) 2010-11 The AEminium Project (see AUTHORS file)
*
* This file is part of Plaid Programming Language.
*
* Plaid Programming Language 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.
*
* Plaid Programming Language 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 Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>.
*/
package aeminium.runtime.tools.benchmark;
public class RTBench {
private static Benchmark[] benchmarks = {
new TaskCreationBenchmark(),
new IndependentTaskGraph(),
new LinearTaskGraph(),
new FixedParallelMaxDependencies(),
new ChildTaskBenchmark(),
new FibonacciBenchmark()
};
public static void usage() {
System.out.println();
System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND");
System.out.println("");
System.out.println("COMMANDS:");
System.out.println(" list - List available benchmarks.");
System.out.println(" run BENCHMARK - Run specified benchmark.");
System.out.println();
}
public static void main(String[] args) {
if ( args.length == 0 ) {
usage();
return;
}
if ( args[0].equals("list") ) {
for( Benchmark benchmark : benchmarks ) {
System.out.println(benchmark.getName());
}
} else if ( args[0].equals("run") && args.length == 2 ) {
Benchmark benchmark = null;
for ( Benchmark b : benchmarks ) {
if ( b.getName().equals(args[1])) {
benchmark = b;
}
}
if ( benchmark != null ) {
Reporter reporter = new StringBuilderReporter();
reporter.startBenchmark(benchmark.getName());
benchmark.run(reporter);
reporter.stopBenchmark(benchmark.getName());
reporter.flush();
} else {
usage();
}
} else {
usage();
}
}
protected static void reportVMStats(Reporter reporter) {
reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory(),
Runtime.getRuntime().freeMemory()));
}
}
| AEminium/AeminiumRuntime | src/aeminium/runtime/tools/benchmark/RTBench.java | Java | gpl-3.0 | 2,591 |
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.NumberFormatException;
import java.util.Collections;
public class FanMapMaker {
private static class IntList extends ArrayList<Integer> {}
private void printChargesArray(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge:");
for(int i = 0; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
}
}
private void printChargesArrayStatAll(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge_tab:");
for(int i = 0; i <= size; i++) {
percent = (100*i)/size;
System.out.println("\XORLW\t\t."+i+"\n"+
"\tBTFSC\t\tSTATUS,Z\n"+
"\tMOVLW\t\t."+distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n"
);
}
System.out.println("\tGOTO\t\ttemp2tcharge_tab_end");
}
private void printChargesArrayStatic(int[] distribution, int size) {
int percent;
String tmpRegName = "TMP0";
String endLabel = "temp2tcharge_tab_end";
System.out.println("temp2tcharge_tab:");
System.out.println("\tMOVLW\t\t.255\n\tMOVF\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\tnext1\n\tGOTO\t\t"+endLabel);
for(int i = 1; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
//System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
System.out.println("next"+i+":\n\tMOVLW\t\t."+ distribution[percent]+"\t\t; [" + i + "] " +
percent + "%\n\tDECFSZ\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\t"+
((i<size) ? "next"+(i+1) : endLabel) + "\n\tGOTO\t\t"+endLabel);
}
}
public static void main(String[] a) {
FanMapMaker fmp = new FanMapMaker();
IntList percentToCharge[] = new IntList[101];
int res[] = new int[101];
for(int i = 0; i < percentToCharge.length; i++)
percentToCharge[i] = new IntList();
File decFile = new File("allDec.dat");
File incFile = new File("allInc.dat");
BufferedReader decReader = null;
BufferedReader incReader = null;
Integer tchrg;
Integer fanPercx;
Float sum;
Float fanPerc;
try {
//decReader = new BufferedReader(new FileReader(decFile));
//incReader = new BufferedReader(new FileReader(incFile));
Scanner decScan = new Scanner(decFile);
Scanner incScan = new Scanner(incFile);
int cnt = 0;
while (decScan.hasNext()) {
tchrg = decScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += decScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
while (incScan.hasNext()) {
tchrg = incScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += incScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
for (int i = 0; i < percentToCharge.length; i++) {
Collections.sort(percentToCharge[i]);
//System.out.print("" + i + " " + "[");
for(Integer e: percentToCharge[i]) {
//System.out.print(e + " ");
}
//System.out.println("]");
}
int last = 1;
for (int i = percentToCharge.length - 1; i >= 0; i--) {
if(percentToCharge[i].size() > 0) {
res[i] = percentToCharge[i].get(0);
last = res[i];
} else {
res[i] = last;
}
//System.out.println(i + " " + res[i]);
}
fmp.printChargesArrayStatAll(res, 50);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
/*try {
if (decReader != null) {
//decReader.close();
}
} //catch (IOException e) {
//}
try {
if (incReader != null) {
//incReader.close();
}
} //catch (IOException e) {
//}
*/
}
}
}
| pworkshop/FanReg | tools/FanMapMaker.java | Java | gpl-3.0 | 4,595 |
package com.bytezone.diskbrowser.nufx;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import com.bytezone.diskbrowser.prodos.write.DiskFullException;
import com.bytezone.diskbrowser.prodos.write.FileAlreadyExistsException;
import com.bytezone.diskbrowser.prodos.write.ProdosDisk;
import com.bytezone.diskbrowser.prodos.write.VolumeCatalogFullException;
// -----------------------------------------------------------------------------------//
public class Binary2
// -----------------------------------------------------------------------------------//
{
private static final String UNDERLINE =
"------------------------------------------------------"
+ "-----------------------";
Binary2Header binary2Header;
byte[] buffer;
List<Binary2Header> headers = new ArrayList<> ();
int totalBlocks;
String fileName;
// ---------------------------------------------------------------------------------//
public Binary2 (Path path) throws IOException
// ---------------------------------------------------------------------------------//
{
fileName = path.toFile ().getName ();
buffer = Files.readAllBytes (path);
read (buffer);
}
// ---------------------------------------------------------------------------------//
private void read (byte[] buffer)
// ---------------------------------------------------------------------------------//
{
int ptr = 0;
do
{
binary2Header = new Binary2Header (buffer, ptr);
System.out.println (binary2Header);
headers.add (binary2Header);
totalBlocks += binary2Header.totalBlocks;
ptr += ((binary2Header.eof - 1) / 128 + 1) * 128 + 128;
} while (binary2Header.filesToFollow > 0);
}
// ---------------------------------------------------------------------------------//
public byte[] getDiskBuffer () throws DiskFullException, VolumeCatalogFullException,
FileAlreadyExistsException, IOException
// ---------------------------------------------------------------------------------//
{
ProdosDisk disk = new ProdosDisk (800, "DiskBrowser");
for (Binary2Header header : headers)
{
byte[] dataBuffer = new byte[header.eof]; // this sux
System.arraycopy (buffer, header.ptr + 128, dataBuffer, 0, dataBuffer.length);
disk.addFile (header.fileName, header.fileType, header.auxType, header.created,
header.modified, dataBuffer, header.eof);
}
disk.close ();
return disk.getBuffer ();
}
// ---------------------------------------------------------------------------------//
@Override
public String toString ()
// ---------------------------------------------------------------------------------//
{
StringBuilder text = new StringBuilder ();
text.append (String.format (
" %-15.15s Files:%5d%n%n",
fileName, headers.size ()));
text.append (" Name Type Auxtyp Modified"
+ " Fmat Length\n");
text.append (String.format ("%s%n", UNDERLINE));
for (Binary2Header header : headers)
text.append (String.format ("%s%n", header.getLine ()));
text.append (String.format ("%s%n", UNDERLINE));
return text.toString ();
}
}
| dmolony/DiskBrowser | src/com/bytezone/diskbrowser/nufx/Binary2.java | Java | gpl-3.0 | 3,371 |
package componentes;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class JTextFieldPrazo extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = -8020852662258513751L;
private int iMaxLength;
private JTextField txt;
private long num;
public JTextFieldPrazo(int pMaxLen, JTextField pText) {
super();
iMaxLength = pMaxLen;
txt = pText;
}
public void insertString(int pOffSet, String pString, AttributeSet pAttributSet)
throws BadLocationException {
if (pString == null)
return;
if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres
super.insertString(pOffSet, pString, pAttributSet);
return;
}
long ilen = (getLength() + pString.length());
try {
if(pString.length()==1 && !pString.equals("-"))
setNum(Long.parseLong(pString));
if(pString.equals("0") && txt.getText().length() == 0){
/**return;*/
}
if (ilen <= iMaxLength) // se o comprimento final for menor...
super.insertString(pOffSet, pString, pAttributSet); // ...aceita str
else if (getLength() == iMaxLength)
return; // nada a fazer
else {
String newStr = pString.substring(0, (iMaxLength - getLength()));
super.insertString(pOffSet, newStr, pAttributSet);
}
}
catch(Exception e) {}
}
public long getNum() {
return num;
}
public void setNum(long num) {
this.num = num;
}
} | DiegoEveling/RHFacil | src/componentes/JTextFieldPrazo.java | Java | gpl-3.0 | 1,557 |
package se.vidstige.jadb;
import se.vidstige.jadb.managers.Bash;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class JadbDevice {
public enum State {
Unknown,
Offline,
Device,
Recovery,
BootLoader
};
private final String serial;
private final ITransportFactory transportFactory;
JadbDevice(String serial, String type, ITransportFactory tFactory) {
this.serial = serial;
this.transportFactory = tFactory;
}
static JadbDevice createAny(JadbConnection connection) {
return new JadbDevice(connection);
}
private JadbDevice(ITransportFactory tFactory) {
serial = null;
this.transportFactory = tFactory;
}
private State convertState(String type) {
switch (type) {
case "device": return State.Device;
case "offline": return State.Offline;
case "bootloader": return State.BootLoader;
case "recovery": return State.Recovery;
default: return State.Unknown;
}
}
private Transport getTransport() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:transport-any");
transport.verifyResponse();
} else {
transport.send("host:transport:" + serial);
transport.verifyResponse();
}
return transport;
}
public String getSerial() {
return serial;
}
public State getState() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:get-state");
transport.verifyResponse();
} else {
transport.send("host-serial:" + serial + ":get-state");
transport.verifyResponse();
}
State state = convertState(transport.readString());
transport.close();
return state;
}
/** <p>Execute a shell command.</p>
*
* <p>For Lollipop and later see: {@link #execute(String, String...)}</p>
*
* @param command main command to run. E.g. "ls"
* @param args arguments to the command.
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream executeShell(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream()));
}
/**
*
* @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with
* Stream.copy(in, out), it is possible to achieve the same effect.
*/
@Deprecated
public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
if (output != null) {
AdbFilterOutputStream out = new AdbFilterOutputStream(output);
try {
transport.readResponseTo(out);
} finally {
out.close();
}
}
}
/** <p>Execute a command with raw binary output.</p>
*
* <p>Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary
* data with that version or later. For earlier versions of Android, use
* {@link #executeShell(String, String...)}.</p>
*
* @param command main command to run, e.g. "screencap"
* @param args arguments to the command, e.g. "-p".
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream execute(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "exec:" + shellLine.toString());
return new BufferedInputStream(transport.getInputStream());
}
/**
* Builds a command line string from the command and its arguments.
*
* @param command the command.
* @param args the list of arguments.
* @return the command line.
*/
private StringBuilder buildCmdLine(String command, String... args) {
StringBuilder shellLine = new StringBuilder(command);
for (String arg : args) {
shellLine.append(" ");
shellLine.append(Bash.quote(arg));
}
return shellLine;
}
public List<RemoteFile> list(String remotePath) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("LIST", remotePath);
List<RemoteFile> result = new ArrayList<RemoteFile>();
for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) {
result.add(dent);
}
return result;
}
private int getMode(File file) {
//noinspection OctalInteger
return 0664;
}
public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("SEND", remote.getPath() + "," + Integer.toString(mode));
sync.sendStream(source);
sync.sendStatus("DONE", (int) lastModified);
sync.verifyStatus();
}
public void push(File local, RemoteFile remote) throws IOException, JadbException {
FileInputStream fileStream = new FileInputStream(local);
push(fileStream, local.lastModified(), getMode(local), remote);
fileStream.close();
}
public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("RECV", remote.getPath());
sync.readChunksTo(destination);
}
public void pull(RemoteFile remote, File local) throws IOException, JadbException {
FileOutputStream fileStream = new FileOutputStream(local);
pull(remote, fileStream);
fileStream.close();
}
private void send(Transport transport, String command) throws IOException, JadbException {
transport.send(command);
transport.verifyResponse();
}
@Override
public String toString() {
return "Device: " + serial;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((serial == null) ? 0 : serial.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JadbDevice other = (JadbDevice) obj;
if (serial == null) {
if (other.serial != null)
return false;
} else if (!serial.equals(other.serial))
return false;
return true;
}
}
| Echtzeitsysteme/mindroid | impl/serverApp/src/main/java/se/vidstige/jadb/JadbDevice.java | Java | gpl-3.0 | 7,644 |
/*
* Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0.
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.icgc.dcc.submission.server.repository;
import static org.icgc.dcc.submission.core.model.QUser.user;
import java.util.List;
import org.icgc.dcc.submission.core.model.QUser;
import org.icgc.dcc.submission.core.model.User;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.NonNull;
public class UserRepository extends AbstractRepository<User, QUser> {
@Autowired
public UserRepository(@NonNull Morphia morphia, @NonNull Datastore datastore) {
super(morphia, datastore, user);
}
public List<User> findUsers() {
return list();
}
public User findUserByUsername(@NonNull String username) {
return uniqueResult(entity.username.eq(username));
}
public User saveUser(@NonNull User user) {
save(user);
return user;
}
public User updateUser(@NonNull User user) {
return findAndModify(
createQuery()
.filter("username", user.getUsername()),
createUpdateOperations()
.set("failedAttempts", user.getFailedAttempts()),
false, false);
}
}
| icgc-dcc/dcc-submission | dcc-submission-server/src/main/java/org/icgc/dcc/submission/server/repository/UserRepository.java | Java | gpl-3.0 | 2,841 |
/*
* 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 Code.Domain;
/**
*
* @author Andres Orduz Grimaldo
*/
public class Jornada {
private int id;
private String nombre;
private TipoJornada tipoJornada;
private Anio anio;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public TipoJornada getTipoJornada() {
return tipoJornada;
}
public void setTipoJornada(TipoJornada tipoJornada) {
this.tipoJornada = tipoJornada;
}
public Anio getAnio() {
return anio;
}
public void setAnio(Anio anio) {
this.anio = anio;
}
} | LayneGranados/Colegios | GestionColegios/Codigo/GestionColegiosCliente/src/Code/Domain/Jornada.java | Java | gpl-3.0 | 950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.