repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
CharrizardBot/Charrizard
src/main/java/com/programmingwizzard/charrizard/bot/listeners/ReputationListener.java
4260
package com.programmingwizzard.charrizard.bot.listeners; import com.google.common.eventbus.Subscribe; import com.programmingwizzard.charrizard.bot.Charrizard; import com.programmingwizzard.charrizard.bot.basic.CGuild; import com.programmingwizzard.charrizard.bot.basic.CUser; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.List; /* * @author ProgrammingWizzard * @date 09.02.2017 */ public class ReputationListener { private final Charrizard charrizard; public ReputationListener(Charrizard charrizard) { this.charrizard = charrizard; } @Subscribe public void onTextMessage(MessageReceivedEvent event) { String content = event.getMessage().getContent(); StringBuilder sb = new StringBuilder(); if (content.startsWith("+") || content.endsWith("+")) { CGuild cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); if (cGuild == null) { charrizard.getCGuildManager().createGuild(event.getGuild()); cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); } List<User> mentionedUsers = event.getMessage().getMentionedUsers(); if (mentionedUsers.size() == 0) { return; } CUser authorCUser = cGuild.getUser(event.getAuthor()); if (authorCUser == null) { cGuild.createUser(event.getAuthor()); authorCUser = cGuild.getUser(event.getAuthor()); } if (authorCUser.getReputation() < 0) { event.getChannel().sendMessage(event.getAuthor().getAsMention() + " - your points can not be negative!").queue(); return; } for (User mentionedUser : mentionedUsers) { if (mentionedUser.getId().equals(event.getAuthor().getId())) { continue; } CUser cUser = cGuild.getUser(mentionedUser); if (cUser == null) { cGuild.createUser(mentionedUser); cUser = cGuild.getUser(mentionedUser); } cUser.addReputation(); sb.append(mentionedUser.getName()).append(", "); } String users = sb.toString(); event.getChannel().sendMessage(event.getAuthor().getAsMention() + " - You mentioned the: " + users.substring(0, sb.length() - 2)).queue(); } else if (content.startsWith("-") || content.endsWith("-")) { CGuild cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); if (cGuild == null) { charrizard.getCGuildManager().createGuild(event.getGuild()); cGuild = charrizard.getCGuildManager().getGuild(event.getGuild()); } List<User> mentionedUsers = event.getMessage().getMentionedUsers(); if (mentionedUsers.size() == 0) { return; } CUser authorCUser = cGuild.getUser(event.getAuthor()); if (authorCUser == null) { cGuild.createUser(event.getAuthor()); authorCUser = cGuild.getUser(event.getAuthor()); } if (authorCUser.getReputation() < 0) { event.getChannel().sendMessage(event.getAuthor().getAsMention() + " - your points can not be negative!").queue(); return; } for (User mentionedUser : mentionedUsers) { if (mentionedUser.getId().equals(event.getAuthor().getId())) { continue; } CUser cUser = cGuild.getUser(mentionedUser); if (cUser == null) { cGuild.createUser(mentionedUser); cUser = cGuild.getUser(mentionedUser); } cUser.removeReputation(); sb.append(mentionedUser.getName()).append(", "); } String users = sb.toString(); event.getChannel().sendMessage(event.getAuthor().getAsMention() + " - You mentioned the: " + users.substring(0, sb.length() - 2)).queue(); } } }
mit
razakpm/oopjavacalculator
src/test/java/com/cvtalks/ocr/ImagePreprocessorTest.java
711
package com.cvtalks.ocr; import static org.junit.Assert.*; import java.awt.image.BufferedImage; import org.junit.Test; import boofcv.struct.image.ImageUInt8; public class ImagePreprocessorTest { @Test public void binarizationTest() { BufferedImage image = ImagePreprocessor.loadImg("src/test/resources/img/test4.jpg"); ImageUInt8 gray = ImagePreprocessor.makeGrayscale(image); ImageUInt8 binary = ImagePreprocessor.makeBinary(gray); assertEquals(0, binary.get(0, 0)); assertEquals(1, binary.get(593, 151)); // ShowImages.showWindow(image, "Original"); // ShowImages.showWindow(gray, "Grayscale"); // ShowImages.showWindow(VisualizeBinaryData.renderBinary(binary, null), "Binary"); } }
mit
bekwam/todomvcFX
tests/src/main/java/todomvcfx/UiTest.java
178
package todomvcfx; /** * Marker interface to be used as JUnit category. * This way we can distinguish normal unit tests from TestFX ui tests. */ public interface UiTest { }
mit
lukaspili/Mortar-architect
commons/src/main/java/architect/commons/transition/FadeModalTransition.java
1402
package architect.commons.transition; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.view.View; import architect.ViewTransitionDirection; /** * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ public class FadeModalTransition extends ModalTransition { protected boolean hideExitView; public FadeModalTransition() { } public FadeModalTransition(Config config) { super(config); } /** * @param hideExitView should the transition hide the exit view? */ public FadeModalTransition(boolean hideExitView) { this.hideExitView = hideExitView; } /** * @param hideExitView should the transition hide the exit view? */ public FadeModalTransition(boolean hideExitView, Config config) { super(config); this.hideExitView = hideExitView; } @Override public void transition(View enterView, View exitView, ViewTransitionDirection direction, AnimatorSet set) { super.transition(enterView, exitView, direction, set); if (direction == ViewTransitionDirection.FORWARD) { set.play(ObjectAnimator.ofFloat(enterView, View.ALPHA, 0, 1)); } else { set.play(ObjectAnimator.ofFloat(exitView, View.ALPHA, 1, 0)); } } @Override public boolean hideExitView() { return hideExitView; } }
mit
codylieu/slogo
src/gui/menubar/SaveWorkspaceMenuItem.java
1098
package gui.menubar; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import util.Serializer; import backend.WorldsCollection; public class SaveWorkspaceMenuItem extends JMenuItem { /** * Saves all current user defined variables and commands * which can be loaded later */ SaveWorkspaceMenuItem(){ super("Save Workspace"); addMouseListener(new LaunchNewTabMouseListener()); } class LaunchNewTabMouseListener extends MouseAdapter{ public void mousePressed(MouseEvent e) { String s = (String) JOptionPane.showInputDialog(null, "Name the serialization file: (no extension needed)", "Save Workspace...", JOptionPane.QUESTION_MESSAGE, null, null, "file name"); try { Serializer.serialize("serializedFiles/" + s + ".ser", WorldsCollection.getInstance().getCurrentWorld().getUserCommands()); Serializer.serialize("serializedFiles/" + s + ".ser" + "v", WorldsCollection.getInstance().getCurrentWorld().getVariables()); } catch (Exception e1) { e1.printStackTrace(); } } } }
mit
bjut-2014/internship
src/main/java/cn/internship/dao/CarouselFigureDao.java
466
package cn.internship.dao; import java.util.List; import cn.internship.entity.CarouselFigure; /** * 轮播图持久层接口 * @author MengHan * */ public interface CarouselFigureDao { public void add(CarouselFigure carouselFigure); public void delete(Integer id); public CarouselFigure get(Integer id); public void edit(CarouselFigure carouselFigure); public List<CarouselFigure> getAll(); public List<CarouselFigure> getByNum(int num); }
mit
boq/GreenHam
integration/openperipheral/api/LuaType.java
515
package openperipheral.api; import java.util.Map; public enum LuaType { TABLE(Map.class, "table"), NUMBER(Double.class, "number"), STRING(String.class, "string"), VOID(void.class, "void"), BOOLEAN(Boolean.class, "boolean"), OBJECT(Object.class, "object"); private Class<?> javaType; private String name; LuaType(Class<?> javaType, String name) { this.javaType = javaType; this.name = name; } public Class<?> getJavaType() { return javaType; } public String getName() { return name; } }
mit
Mozu/Mozu.Integrations.Quickbooks
src/main/java/com/mozu/qbintegration/model/qbmodel/allgen/ShipMethodQueryRqType.java
9714
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.09.07 at 08:01:35 PM IST // package com.mozu.qbintegration.model.qbmodel.allgen; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ShipMethodQueryRqType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ShipMethodQueryRqType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}ListQuery"/> * &lt;/sequence> * &lt;attribute name="requestID" type="{}STRTYPE" /> * &lt;attribute name="metaData" default="NoMetaData"> * &lt;simpleType> * &lt;restriction base="{}STRTYPE"> * &lt;enumeration value="NoMetaData"/> * &lt;enumeration value="MetaDataOnly"/> * &lt;enumeration value="MetaDataAndResponseData"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ShipMethodQueryRqType", propOrder = { "listID", "fullName", "maxReturned", "activeStatus", "fromModifiedDate", "toModifiedDate", "nameFilter", "nameRangeFilter", "includeRetElement" }) public class ShipMethodQueryRqType { @XmlElement(name = "ListID") protected List<String> listID; @XmlElement(name = "FullName") protected List<String> fullName; @XmlElement(name = "MaxReturned") protected BigInteger maxReturned; @XmlElement(name = "ActiveStatus", defaultValue = "ActiveOnly") protected String activeStatus; @XmlElement(name = "FromModifiedDate") protected String fromModifiedDate; @XmlElement(name = "ToModifiedDate") protected String toModifiedDate; @XmlElement(name = "NameFilter") protected NameFilter nameFilter; @XmlElement(name = "NameRangeFilter") protected NameRangeFilter nameRangeFilter; @XmlElement(name = "IncludeRetElement") protected List<String> includeRetElement; @XmlAttribute(name = "requestID") protected String requestID; @XmlAttribute(name = "metaData") protected String metaData; /** * Gets the value of the listID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the listID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getListID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getListID() { if (listID == null) { listID = new ArrayList<String>(); } return this.listID; } /** * Gets the value of the fullName property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fullName property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFullName().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getFullName() { if (fullName == null) { fullName = new ArrayList<String>(); } return this.fullName; } /** * Gets the value of the maxReturned property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMaxReturned() { return maxReturned; } /** * Sets the value of the maxReturned property. * * @param value * allowed object is * {@link BigInteger } * */ public void setMaxReturned(BigInteger value) { this.maxReturned = value; } /** * Gets the value of the activeStatus property. * * @return * possible object is * {@link String } * */ public String getActiveStatus() { return activeStatus; } /** * Sets the value of the activeStatus property. * * @param value * allowed object is * {@link String } * */ public void setActiveStatus(String value) { this.activeStatus = value; } /** * Gets the value of the fromModifiedDate property. * * @return * possible object is * {@link String } * */ public String getFromModifiedDate() { return fromModifiedDate; } /** * Sets the value of the fromModifiedDate property. * * @param value * allowed object is * {@link String } * */ public void setFromModifiedDate(String value) { this.fromModifiedDate = value; } /** * Gets the value of the toModifiedDate property. * * @return * possible object is * {@link String } * */ public String getToModifiedDate() { return toModifiedDate; } /** * Sets the value of the toModifiedDate property. * * @param value * allowed object is * {@link String } * */ public void setToModifiedDate(String value) { this.toModifiedDate = value; } /** * Gets the value of the nameFilter property. * * @return * possible object is * {@link NameFilter } * */ public NameFilter getNameFilter() { return nameFilter; } /** * Sets the value of the nameFilter property. * * @param value * allowed object is * {@link NameFilter } * */ public void setNameFilter(NameFilter value) { this.nameFilter = value; } /** * Gets the value of the nameRangeFilter property. * * @return * possible object is * {@link NameRangeFilter } * */ public NameRangeFilter getNameRangeFilter() { return nameRangeFilter; } /** * Sets the value of the nameRangeFilter property. * * @param value * allowed object is * {@link NameRangeFilter } * */ public void setNameRangeFilter(NameRangeFilter value) { this.nameRangeFilter = value; } /** * Gets the value of the includeRetElement property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the includeRetElement property. * * <p> * For example, to add a new item, do as follows: * <pre> * getIncludeRetElement().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getIncludeRetElement() { if (includeRetElement == null) { includeRetElement = new ArrayList<String>(); } return this.includeRetElement; } /** * Gets the value of the requestID property. * * @return * possible object is * {@link String } * */ public String getRequestID() { return requestID; } /** * Sets the value of the requestID property. * * @param value * allowed object is * {@link String } * */ public void setRequestID(String value) { this.requestID = value; } /** * Gets the value of the metaData property. * * @return * possible object is * {@link String } * */ public String getMetaData() { if (metaData == null) { return "NoMetaData"; } else { return metaData; } } /** * Sets the value of the metaData property. * * @param value * allowed object is * {@link String } * */ public void setMetaData(String value) { this.metaData = value; } }
mit
wmluke/pipes
core/src/main/java/net/bunselmeyer/middleware/pipes/persistence/Repository.java
613
package net.bunselmeyer.middleware.pipes.persistence; import org.hibernate.Criteria; import org.hibernate.criterion.Order; import java.util.List; public interface Repository<T> { T read(Integer id); RepositoryResult<T> find(); RepositoryResult<T> find(T example); RepositoryResult<T> find(Criteria criteria); T create(T entity); void delete(T entity); void update(T entity); public static interface RepositoryResult<M> { RepositoryResult<M> limit(int page, int perPage); RepositoryResult<M> orderBy(Order... orders); List<M> list(); } }
mit
ComputationalReflection/weaveJ
Benchmarks/Real Applications/weaveJ/Hotdraw/src/demos/Demo2.java
2292
package demos; import java.awt.Color; import java.util.HashMap; import java.util.List; import java.util.Map; import controller.Controller; import shapesPackage.PointA; import shapesPackage.Shape; import shapesPackage.Shapes; import utilsClass.Demo; public class Demo2 implements Demo { @Override public void run() { // TODO Auto-generated method stub int n = Shapes.getInstance().getPaintConsoleOrCanvas(); Shape s = null; Controller controller = new Controller(); List list=controller.getListShapes(); Map hash = new HashMap(); //insertamos el rectangulo hash.put("shape", new Integer(0)); hash.put("x", new Integer(300)); hash.put("y", new Integer(300)); hash.put("width", new Integer(100)); hash.put("height", new Integer(100)); hash.put("color", Color.blue); controller.createShape(hash); int idRectangle = Shapes.getInstance().getNumberShapes(); hash.clear(); //insertamos el triangulo hash.put("shape", new Integer(2)); hash.put("x", new Integer(100)); hash.put("y", new Integer(100)); hash.put("side", new Integer(50)); hash.put("color", Color.green); controller.createShape(hash); int idTriangle = Shapes.getInstance().getNumberShapes(); hash.clear(); //realizamos operaciones con las figuras for(int i=0;i<500;i++){ //movemos el rectángulo list=controller.getListShapes(); s = Shapes.getInstance().find(idRectangle); PointA p = new PointA(); p.setX(100); p.setY(100); controller.move(s,p); //movemos el triángulo list=controller.getListShapes(); s = Shapes.getInstance().find(idTriangle); p = new PointA(); p.setX(300); p.setY(300); controller.move(s,p); //escalamos list=controller.getListShapes(); s = Shapes.getInstance().find(idTriangle); hash.clear(); hash.put("side", new Integer(50)); controller.scale(s,hash); //movemos el rectángulo list=controller.getListShapes(); s = Shapes.getInstance().find(idRectangle); p = new PointA(); p.setX(400); p.setY(500); controller.move(s,p); //movemos el triángulo list=controller.getListShapes(); s = Shapes.getInstance().find(idTriangle); p = new PointA(); p.setX(100); p.setY(500); controller.move(s,p); } } }
mit
DevOpsDistilled/OpERP
OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/EditCategoryPaneControllerImpl.java
1501
package devopsdistilled.operp.client.items.panes.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.exceptions.EntityNameExistsException; import devopsdistilled.operp.client.exceptions.NullFieldException; import devopsdistilled.operp.client.items.models.CategoryModel; import devopsdistilled.operp.client.items.panes.EditCategoryPane; import devopsdistilled.operp.client.items.panes.controllers.EditCategoryPaneController; import devopsdistilled.operp.client.items.panes.models.EditCategoryPaneModel; import devopsdistilled.operp.server.data.entity.items.Category; public class EditCategoryPaneControllerImpl implements EditCategoryPaneController { @Inject private EditCategoryPane view; @Inject private EditCategoryPaneModel model; @Inject private CategoryModel categoryModel; @Override public void init(Category category) { view.init(); model.setEntity(category); model.registerObserver(view); } @Override public void validate(Category category) throws EntityNameExistsException, NullFieldException { if (category.getCategoryName().equalsIgnoreCase("")) throw new NullFieldException("Category Name can't be empty"); if (!categoryModel.getService().isCategoryNameValidForCategory( category.getCategoryId(), category.getCategoryName())) throw new EntityNameExistsException("Category Name already exists"); } @Override public Category save(Category category) { return categoryModel.saveAndUpdateModel(category); } }
mit
epiphany27/Gitskarios
app/src/main/java/core/Exclude.java
270
package core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Exclude { }
mit
Skrittles/SPMinistocks
src/nitezh/ministock/activities/configure/ConfigureActivity1x2.java
1426
/* The MIT License Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks 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 nitezh.ministock.activities.configure; import android.os.Bundle; public class ConfigureActivity1x2 extends ConfigureActivityBase { @Override public void onCreate(Bundle savedInstanceState) { mWidgetSize = 0; super.onCreate(savedInstanceState); } }
mit
vboctor/ews-java-api
src/main/java/microsoft/exchange/webservices/data/Param.java
732
/************************************************************************** * copyright file="Param.java" company="Microsoft" * Copyright (c) Microsoft Corporation. All rights reserved. * * Defines the Param.java. **************************************************************************/ package microsoft.exchange.webservices.data; /** * The Class Param. * * @param <T> * the generic type */ abstract class Param<T> { /** The param. */ private T param; /** * Gets the param. * * @return the param */ public T getParam() { return param; } /** * Sets the param. * * @param param * the new param */ public void setParam(T param) { this.param = param; } }
mit
Diheng/mindtrails
core/src/main/java/org/mindtrails/domain/BaseStudy.java
9977
package org.mindtrails.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.GenericGenerator; import org.joda.time.DateTime; import org.joda.time.Days; import org.mindtrails.domain.RestExceptions.WaitException; import org.mindtrails.domain.tracking.TaskLog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.*; import java.util.*; /** * You can use this class to get some basic features * rather than implement everything in the Study interface. */ @Data @Entity @Table(name = "study") @DiscriminatorColumn(name="studyType") @EqualsAndHashCode(exclude={"taskLogs"}) public abstract class BaseStudy implements Study { private static final Logger LOG = LoggerFactory.getLogger(BaseStudy.class); private static final Session NOT_STARTED = new Session("NOT_STARTED", "Not Started", 0, 0, new ArrayList<Task>()); private static final Session COMPLETE = new Session("COMPLETE", "Complete", 0, 0, new ArrayList<Task>()); @Id @GenericGenerator(name = "STUDY_GEN", strategy = "org.mindtrails.persistence.MindtrailsIdGenerator", parameters = { @org.hibernate.annotations.Parameter(name = "table_name", value = "ID_GEN"), @org.hibernate.annotations.Parameter(name = "value_column_name", value = "GEN_VAL"), @org.hibernate.annotations.Parameter(name = "segment_column_name", value = "GEN_NAME"), @org.hibernate.annotations.Parameter(name = "segment_value", value = "study") }) @GeneratedValue(strategy = GenerationType.TABLE, generator = "STUDY_GEN") protected long id; protected String currentSession; protected int currentTaskIndex = 0; protected Date lastSessionDate; protected boolean receiveGiftCards; protected String conditioning; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "study") @JsonIgnore @OrderBy("dateCompleted") protected List<TaskLog> taskLogs = new ArrayList<>(); public BaseStudy() {} public BaseStudy(String currentName, int taskIndex, Date lastSessionDate, List<TaskLog> taskLogs, boolean receiveGiftCards) { this.currentSession = currentName; this.currentTaskIndex = taskIndex; this.lastSessionDate = lastSessionDate; this.taskLogs = taskLogs; this.receiveGiftCards = receiveGiftCards; } public boolean isProgress(String formName) {return this.hasTask(formName);} @Override @JsonIgnore public List<Session> getSessions() { List<Session> sessions = getStatelessSessions(); sessions.add(COMPLETE); // Add state to the sessions boolean complete = true; for(Session s : sessions) { if (s.getName().equals(currentSession)) { s.setCurrent(true); complete = false; } s.setComplete(complete); setTaskStates(s.getName(), s.getTasks(), currentTaskIndex); } return sessions; } /** * This should return a full list of sessions that define the study, but * does not need to mark them correctly with regards to being completed, * or inprogress. * @return */ @JsonIgnore public abstract List<Session> getStatelessSessions(); @Override public Session nextGiftSession() { boolean toCurrent = false; for (Session s : getSessions()) { if (toCurrent && s.getGiftAmount() > 0) return s; if (s.isCurrent()) toCurrent = true; } return null; } @Override public boolean isReceiveGiftCards() { return receiveGiftCards; } @Override public void setReceiveGiftCards(boolean value) { receiveGiftCards = value; } /** * @return Number of days since the last completed session. */ public int daysSinceLastSession() { DateTime last; DateTime now; last = new DateTime(lastSessionDate); // Allow 8 hours of slop in the time, so if someone should wait // 1 day, they need to wait at least 16 hours. last = last.minusHours(8); now = new DateTime(); return Days.daysBetween(last, now).getDays(); } @Override public void completeCurrentTask(double timeOnTask) { // Log the completion of the task this.taskLogs.add(new TaskLog(this, timeOnTask)); if (getState().equals(STUDY_STATE.WAIT)){ throw new WaitException(); } // If this is the last task in a session, then we move to the next session. if(currentTaskIndex +1 >= getCurrentSession().getTasks().size()) { this.taskLogs.add(TaskLog.completedSession(this)); completeSession(); } else { // otherwise we just increment the task index. this.currentTaskIndex = currentTaskIndex + 1; } } @Override public Date getLastTaskDate() { if(this.taskLogs == null || this.taskLogs.size() == 0) { return new Date(); } else { return taskLogs.get(taskLogs.size()-1).getDateCompleted(); } } protected void completeSession() { List<Session> sessions = getSessions(); boolean next = false; Session nextSession = getCurrentSession(); for(Session s: sessions) { if(next == true) { nextSession = s; break; } if(s.isCurrent()) next = true; } this.currentTaskIndex = 0; this.currentSession = nextSession.getName(); this.lastSessionDate = new Date(); } @Override public Session getCurrentSession() { List<Session> sessions = getSessions(); for(Session s : getSessions()) { if (s.isCurrent()) { return s; } } // If there is no current session, return the first session. sessions.get(0).setCurrent(true); return sessions.get(0); } @Override public Session getSession(String sessionName) { for(Session s : getSessions()) { if (s.getName().equals(sessionName)) { return s; } } return null; } /** * Returns true if the session is completed, false otherwise. * @param session * @return */ public boolean completed(String session) { Session currentSession = getCurrentSession(); if(session == currentSession.getName()) return false; for(Session s : getSessions()) { String strName = s.getName(); if (strName.equals(session)) return true; if (strName.equals(currentSession.getName())) return false; } // You can't really get here, since we have looped through all // the possible values of session. return false; } /** * This method churns through the list of tasks, setting the "current" and "complete" flags based on the * current task index. It also uses the task logs to determine the completion date. */ protected void setTaskStates(String sessionName, List<Task> tasks, int taskIndex) { int index = 0; for (Task t : tasks) { t.setCurrent(taskIndex == index); t.setComplete(taskIndex > index); for(TaskLog log : taskLogs) { if (log.getSessionName().equals(sessionName) && log.getTaskName().equals(t.getName()) && (log.getTag()== null || log.getTag().equals(t.getTag()))) { t.setDateCompleted(log.getDateCompleted()); t.setComplete(true); t.setTimeOnTask(log.getTimeOnTask()); break; } } index++; } } /** * May return null if there is no previous session. */ @Override @JsonIgnore public Session getLastSession() { List<Session> sessions = getSessions(); Session last = NOT_STARTED; for(Session s: sessions) { if (s.getName().equals(currentSession)) break; last = s; } return last; } @Override public void forceToSession(String sessionName) { this.currentSession = sessionName; this.currentTaskIndex = 0; this.lastSessionDate = null; } @Override public STUDY_STATE getState() { if (currentTaskIndex != 0) return STUDY_STATE.IN_PROGRESS; if (this.currentSession.equals(COMPLETE.getName())) { return STUDY_STATE.ALL_DONE; } if(daysSinceLastSession() < getCurrentSession().getDaysToWait()) { return STUDY_STATE.WAIT; } return STUDY_STATE.READY; } @Override public String toString() { return "BaseStudy{" + "id=" + id + ", currentSession='" + currentSession + '\'' + ", currentTaskIndex=" + currentTaskIndex + ", lastSessionDate=" + lastSessionDate + ", receiveGiftCards=" + receiveGiftCards + ", taskLogs=" + taskLogs + '}'; } @Override public Map<String,Object> getPiPlayerParameters(){ Map<String,Object> params = new HashMap<>(); return params; } /** * We have a one to one relationship to participant, * we can just return the unique id of the Study, and * it is the unique id of the participant. */ @Override public long getParticipant() { return this.id; } @Override public boolean hasTask(String taskName) { List<Session> sessions = getSessions(); for (Session s : sessions) { for (Task t : s.getTasks()) { if (t.getName().equals(taskName)) return true; } } return false; } }
mit
wesabe/grendel
src/main/java/com/wesabe/grendel/auth/Session.java
500
package com.wesabe.grendel.auth; import com.wesabe.grendel.entities.User; import com.wesabe.grendel.openpgp.UnlockedKeySet; /** * A {@link User} and their {@link UnlockedKeySet}. * * @author coda */ public class Session { private final User user; private final UnlockedKeySet keySet; public Session(User user, UnlockedKeySet keySet) { this.user = user; this.keySet = keySet; } public UnlockedKeySet getKeySet() { return keySet; } public User getUser() { return user; } }
mit
jcc333/tempoiq-java
src/test/java/com/tempoiq/DataPointReadTest.java
2914
package com.tempoiq; import java.io.IOException; import java.util.Iterator; import org.apache.http.*; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.*; import static org.junit.Assert.*; public class DataPointReadTest { private static final DateTimeZone timezone = DateTimeZone.UTC; private static final Device device = new Device("device1"); private static final String json1 = "{" + "\"data\":[" + "{\"t\":\"2012-01-01T01:00:00.000Z\",\"data\":{" + "\"device1\":{" + "\"sensor1\":1.23," + "\"sensor2\":1.677}}}]}"; private static final String json2 = "{" + "\"data\":[" + "{\"t\":\"2012-01-01T01:00:00.000Z\",\"data\":{" + "\"device1\":{" + "\"sensor1\":1.23," + "\"sensor2\":1.677}}}],"+ "\"next_page\":{\"next_query\": {" + "\"search\":{" + "\"select\":\"sensors\"," + "\"filters\":{" + "\"devices\":{" + "\"and\":[" + "{\"key\":\"key1\"}" + "]}}}," + "\"read\":{\"start\":\"2012-01-01T01:00:00.001Z\"," + "\"stop\":\"2014-03-01T00:00:00.000Z\"," + "\"limit\":1," + "\"include_selection\":false}" + "}}}"; private static final String json3 = "{" + "\"data\":[" + "{\"t\":\"2012-02-01T01:00:00.000Z\",\"data\":{" + "\"device1\":{" + "\"sensor1\":2.23," + "\"sensor2\":2.677}}}]}"; @Test public void testSimpleRowReads() throws IOException { HttpResponse response = Util.getResponse(200, json1); Client client = Util.getClient(response); DateTime start = new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone); DateTime stop = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone); Selection sel = new Selection(). addSelector(Selector.Type.DEVICES, Selector.key(device.getKey())); Cursor<Row> cursor = client.read(sel, start, stop); assert(cursor.iterator().hasNext()); for (Row row : cursor) { assertEquals(1.23, row.getValue(device.getKey(), "sensor1")); assertEquals(1.677, row.getValue(device.getKey(), "sensor2")); } } @Test public void testSensorStreamReads() throws IOException { HttpResponse response = Util.getResponse(200, json1); Client client = Util.getClient(response); DateTime start = new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone); DateTime stop = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone); Selection sel = new Selection(). addSelector(Selector.Type.DEVICES, Selector.key(device.getKey())); DataPointRowCursor cursor = client.read(sel, start, stop); assert(cursor.iterator().hasNext()); DataPointCursor sensor1 = cursor.pointsForStream(device.getKey(), "sensor1"); assert(sensor1.iterator().hasNext()); for (DataPoint dp : sensor1) { assertEquals(1.23, dp.getValue()); } } }
mit
sunnyrajrathod/sample-code-java
src/main/java/net/authorize/sample/PayPalExpressCheckout/Void.java
4192
package net.authorize.sample.PayPalExpressCheckout; import net.authorize.Environment; import net.authorize.api.contract.v1.ANetApiResponse; import net.authorize.api.contract.v1.CreateTransactionRequest; import net.authorize.api.contract.v1.CreateTransactionResponse; import net.authorize.api.contract.v1.MerchantAuthenticationType; import net.authorize.api.contract.v1.MessageTypeEnum; import net.authorize.api.contract.v1.PayPalType; import net.authorize.api.contract.v1.PaymentType; import net.authorize.api.contract.v1.TransactionRequestType; import net.authorize.api.contract.v1.TransactionResponse; import net.authorize.api.contract.v1.TransactionTypeEnum; import net.authorize.api.controller.CreateTransactionController; import net.authorize.api.controller.base.ApiOperationBase; public class Void { public static ANetApiResponse run(String apiLoginId, String transactionKey, String transactionID) { System.out.println("PayPal Void Transaction"); //Common code to set for all requests ApiOperationBase.setEnvironment(Environment.SANDBOX); MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType(); merchantAuthenticationType.setName(apiLoginId); merchantAuthenticationType.setTransactionKey(transactionKey); ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType); PayPalType payPalType = new PayPalType(); payPalType.setSuccessUrl(""); payPalType.setCancelUrl(""); //standard api call to retrieve response PaymentType paymentType = new PaymentType(); paymentType.setPayPal(payPalType); // Create the payment transaction request TransactionRequestType transactionRequest = new TransactionRequestType(); transactionRequest.setTransactionType(TransactionTypeEnum.VOID_TRANSACTION.value()); transactionRequest.setPayment(paymentType); transactionRequest.setRefTransId(transactionID); // Make the API Request CreateTransactionRequest apiRequest = new CreateTransactionRequest(); apiRequest.setTransactionRequest(transactionRequest); CreateTransactionController controller = new CreateTransactionController(apiRequest); controller.execute(); CreateTransactionResponse response = controller.getApiResponse(); if (response!=null) { // If API Response is ok, go ahead and check the transaction response if (response.getMessages().getResultCode() == MessageTypeEnum.OK) { TransactionResponse result = response.getTransactionResponse(); if (result.getMessages() != null) { System.out.println("Successfully created transaction with Transaction ID: " + result.getTransId()); System.out.println("Response Code: " + result.getResponseCode()); System.out.println("Message Code: " + result.getMessages().getMessage().get(0).getCode()); System.out.println("Description: " + result.getMessages().getMessage().get(0).getDescription()); } else { System.out.println("Failed Transaction."); if (response.getTransactionResponse().getErrors() != null) { System.out.println("Error Code: " + response.getTransactionResponse().getErrors().getError().get(0).getErrorCode()); System.out.println("Error message: " + response.getTransactionResponse().getErrors().getError().get(0).getErrorText()); } } } else { System.out.println("Failed Transaction."); if (response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null) { System.out.println("Error Code: " + response.getTransactionResponse().getErrors().getError().get(0).getErrorCode()); System.out.println("Error message: " + response.getTransactionResponse().getErrors().getError().get(0).getErrorText()); } else { System.out.println("Error Code: " + response.getMessages().getMessage().get(0).getCode()); System.out.println("Error message: " + response.getMessages().getMessage().get(0).getText()); } } } else { System.out.println("Null Response."); } return response; } }
mit
uwol/cobol85parser
src/main/java/io/proleap/cobol/asg/metamodel/identification/impl/ProgramIdParagraphImpl.java
1175
/* * Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.cobol.asg.metamodel.identification.impl; import io.proleap.cobol.CobolParser.ProgramIdParagraphContext; import io.proleap.cobol.asg.metamodel.ProgramUnit; import io.proleap.cobol.asg.metamodel.identification.ProgramIdParagraph; import io.proleap.cobol.asg.metamodel.impl.CobolDivisionElementImpl; public class ProgramIdParagraphImpl extends CobolDivisionElementImpl implements ProgramIdParagraph { protected Attribute attribute; protected final ProgramIdParagraphContext ctx; protected String name; public ProgramIdParagraphImpl(final String name, final ProgramUnit programUnit, final ProgramIdParagraphContext ctx) { super(programUnit, ctx); this.name = name; this.ctx = ctx; } @Override public Attribute getAttribute() { return attribute; } @Override public String getName() { return name; } @Override public void setAttribute(final Attribute attribute) { this.attribute = attribute; } }
mit
AourpallyNikhil/qstore
QStore4S/src/main/java/edu/asu/qstore4s/search/elements/factory/impl/SearchTermPartFactory.java
545
package edu.asu.qstore4s.search.elements.factory.impl; import org.springframework.stereotype.Service; import edu.asu.qstore4s.search.elements.ISearchTermPart; import edu.asu.qstore4s.search.elements.factory.ISearchTermPartFactory; import edu.asu.qstore4s.search.elements.impl.SearchTermPart; @Service public class SearchTermPartFactory implements ISearchTermPartFactory { @Override public ISearchTermPart createSearchTermPart() { ISearchTermPart termPartObject = new SearchTermPart(); return termPartObject; } }
mit
synapticloop/backblaze-b2-java-api
src/main/java/synapticloop/b2/response/B2DeleteFileVersionResponse.java
2264
package synapticloop.b2.response; /* * Copyright (c) 2016 - 2017 Synapticloop. * * All rights reserved. * * This code may contain contributions from other parties which, where * applicable, will be listed in the default build file for the project * ~and/or~ in a file named CONTRIBUTORS.txt in the root of the project. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENSE.txt shipped with * this source code or binaries. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import synapticloop.b2.exception.B2ApiException; public class B2DeleteFileVersionResponse extends BaseB2Response { private static final Logger LOGGER = LoggerFactory.getLogger(B2DeleteFileVersionResponse.class); private final String fileId; private final String fileName; /** * Instantiate a delete file version response with the JSON response as a string from * the API call. This response is then parsed into the relevant fields. * * @param json The response (in JSON format) * * @throws B2ApiException if there was an error parsing the response */ public B2DeleteFileVersionResponse(String json) throws B2ApiException { super(json); this.fileId = this.readString(B2ResponseProperties.KEY_FILE_ID); this.fileName = this.readString(B2ResponseProperties.KEY_FILE_NAME); this.warnOnMissedKeys(); } /** * Get the fileId that uniquely identifies this file * * @return the fileId */ public String getFileId() { return this.fileId; } /** * Get the name of the file as stored in the backblaze bucket * * @return the name of the file as stored in the backblaze bucket */ public String getFileName() { return this.fileName; } @Override protected Logger getLogger() { return LOGGER; } @Override public String toString() { final StringBuilder sb = new StringBuilder("B2DeleteFileVersionResponse{"); sb.append("fileId='").append(fileId).append('\''); sb.append(", fileName='").append(fileName).append('\''); sb.append('}'); return sb.toString(); } }
mit
GraphWalker/graphwalker-project
graphwalker-studio/src/main/java/org/graphwalker/studio/Options.java
1957
package org.graphwalker.studio; /* * #%L * GraphWalker Command Line Interface * %% * Copyright (C) 2005 - 2014 GraphWalker * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.beust.jcommander.Parameter; public class Options { @Parameter(names = {"--help", "-h"}, description = "Prints help text") public boolean help = false; @Parameter(names = {"--version", "-v"}, description = "Prints the version of graphwalker") public boolean version = false; @Parameter(names = {"--websocket-port", "-w"}, description = "Sets the port of the websocket service") public int wsPort = 9999; @Parameter(names = {"--browser-port", "-b"}, description = "Sets the port of the web server service") public int browserPort = 9090; @Parameter(names = {"--debug", "-d"}, description = "Sets the log level: OFF, ERROR, WARN, INFO, DEBUG, TRACE, ALL. Default is OFF") public String debug = "OFF"; }
mit
sharadagarwal/autorest
AutoRest/Generators/Java/Azure.Java.Tests/src/test/java/fixtures/azurespecials/SkipUrlEncodingTests.java
2593
package fixtures.azurespecials; import com.microsoft.rest.ServiceResponse; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class SkipUrlEncodingTests { private static final int OK_STATUS_CODE = 200; private static final int NOT_FOUND_STATUS_CODE = 404; private static String baseUrl = "http://localhost:3000"; private static String unencodedPath = "path1/path2/path3"; private static String unencodedQuery = "value1&q2=value2&q3=value3"; private static SkipUrlEncodingOperations client; @BeforeClass public static void setup() { client = new AutoRestAzureSpecialParametersTestClientImpl(baseUrl, null).getSkipUrlEncodingOperations(); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getMethodPathValid() throws Exception { ServiceResponse<Void> response = client.getMethodPathValid(unencodedPath); // Will throw ServiceException if not 200. //Assert.assertEquals(OK_STATUS_CODE, response.getResponse().code()); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getPathPathValid() throws Exception { ServiceResponse<Void> response = client.getPathPathValid(unencodedPath); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getSwaggerPathValid() throws Exception { ServiceResponse<Void> response = client.getSwaggerPathValid(); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getMethodQueryValid() throws Exception { ServiceResponse<Void> response = client.getMethodQueryValid(unencodedQuery); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getPathQueryValid() throws Exception { ServiceResponse<Void> response = client.getPathQueryValid(unencodedQuery); } @Ignore("wait for this release -- https://github.com/square/retrofit/commit/2ea70568bd057fa9235ae5183cebbde1659af84d") public void getSwaggerQueryValid() throws Exception { ServiceResponse<Void> response = client.getSwaggerQueryValid(); } @Test public void getMethodQueryNull() throws Exception { ServiceResponse<Void> response = client.getMethodQueryNull(null); } }
mit
zulus/Composer-Eclipse-Plugin
com.dubture.composer.ui/src/com/dubture/composer/ui/controller/ITableController.java
180
package com.dubture.composer.ui.controller; import org.eclipse.jface.viewers.ITableLabelProvider; public interface ITableController extends IController, ITableLabelProvider { }
mit
GIScience/openrouteservice-core
openrouteservice/src/main/java/org/heigit/ors/api/responses/centrality/json/JsonCentralityLocation.java
1427
package org.heigit.ors.api.responses.centrality.json; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.vividsolutions.jts.geom.Coordinate; import io.swagger.annotations.ApiModelProperty; import org.heigit.ors.util.FormatUtility; import java.util.Map; public class JsonCentralityLocation { protected static final int COORDINATE_DECIMAL_PLACES = 6; @ApiModelProperty(value = "Id of the corresponding node in the graph", example = "1") @JsonProperty(value = "nodeId") @JsonFormat(shape = JsonFormat.Shape.NUMBER) protected Integer nodeId; @ApiModelProperty(value = "{longitude},{latitude} coordinates of the closest accessible point on the routing graph", example = "[8.678962, 49.40783]") @JsonProperty(value = "coord") @JsonFormat(shape = JsonFormat.Shape.ARRAY) protected Coordinate coord; JsonCentralityLocation(Map.Entry<Integer, Coordinate> location) { this.nodeId = location.getKey(); this.coord = location.getValue(); } public Double[] getCoord() { Double[] coord2D = new Double[2]; coord2D[0] = FormatUtility.roundToDecimals(coord.x, COORDINATE_DECIMAL_PLACES); coord2D[1] = FormatUtility.roundToDecimals(coord.y, COORDINATE_DECIMAL_PLACES); // coord2D[3] = location.z; --> example for third dimension return coord2D; } }
mit
kineticadb/kinetica-api-java
api/src/main/java/com/gpudb/filesystem/upload/MultiPartUploadInfo.java
2936
package com.gpudb.filesystem.upload; import java.util.List; import java.util.Map; /** * This is an internal class and not meant to be used by the end users of the * filesystem API. The consequences of using this class directly in client code * is not guaranteed and maybe undesirable. * This class packages and mimics certain important attributes of a multi-part * upload operation. The attributes of this class are in one-one correspondence * to those specified in the {@link com.gpudb.GPUdb#uploadFiles(List, List, Map)} * endpoint. */ public class MultiPartUploadInfo { /** * This enum specifies the different operations/states that a multi-part * file upload could go through. */ public enum MultiPartOperation { NONE("none"), INIT("init"), UPLOAD_PART("upload_part"), COMPLETE("complete"), CANCEL("cancel"); private final String value; MultiPartOperation(String operation) { this.value = operation; } public String getValue() { return value; } } /** * This uniquely identifies a multi-part upload operation. */ private String uuid; /** * The current value of the operation/state according to the enum * {@link MultiPartOperation} */ private MultiPartOperation partOperation; /** * This identifies the part number for a particular part of the file being * uploaded. */ private int uploadPartNumber; /** * */ private long totalParts; /** * This is the name of the file being uploaded. */ private String fileName; /** * Default constructor */ public MultiPartUploadInfo() { } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public MultiPartOperation getPartOperation() { return partOperation; } public void setPartOperation(MultiPartOperation partOperation) { this.partOperation = partOperation; } public int getUploadPartNumber() { return uploadPartNumber; } public void setUploadPartNumber(int uploadPartNumber) { this.uploadPartNumber = uploadPartNumber; } public long getTotalParts() { return totalParts; } public void setTotalParts(long totalParts) { this.totalParts = totalParts; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } @Override public String toString() { return "MultiPartUploadInfo{" + "uuid='" + uuid + '\'' + ", " + "partOperation=" + partOperation + ", " + "uploadPartNumber=" + uploadPartNumber + ", " + "totalParts=" + totalParts + ", fileName='" + fileName + '\'' + '}'; } }
mit
quartz-powered/server
src/main/java/org/quartzpowered/protocol/data/info/PlayerInfo.java
1810
/** * This file is a component of Quartz Powered, this license makes sure any work * associated with Quartz Powered, must follow the conditions of the license included. * * The MIT License (MIT) * * Copyright (c) 2015 Quartz Powered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.quartzpowered.protocol.data.info; import lombok.Data; import org.quartzpowered.network.session.profile.PlayerProfile; import org.quartzpowered.protocol.data.Gamemode; import org.quartzpowered.protocol.data.chat.component.BaseComponent; @Data public class PlayerInfo { private PlayerProfile profile; private Gamemode gamemode; private int ping; private BaseComponent displayName; public boolean hasDisplayName() { return displayName != null; } }
mit
dianwen/Slogo
src/exceptions/VariableNotFoundException.java
160
package exceptions; public class VariableNotFoundException extends SlogoException { public VariableNotFoundException() { super("Variable Not Found"); } }
mit
v1v/mail-watcher-plugin
src/main/java/org/jenkinsci/plugins/mailwatcher/WatcherJobProperty.java
3094
/* * The MIT License * * Copyright (c) 2012 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.mailwatcher; import hudson.Extension; import hudson.model.JobProperty; import hudson.model.JobPropertyDescriptor; import hudson.model.Job; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; /** * Configure list of email addresses as a property of a Job to be used for * notification purposes. * * @author ogondza */ public class WatcherJobProperty extends JobProperty<Job<?, ?>> { private final String watcherAddresses; @DataBoundConstructor public WatcherJobProperty(final String watcherAddresses) { this.watcherAddresses = watcherAddresses; } public String getWatcherAddresses() { return watcherAddresses; } @Extension public static class DescriptorImpl extends JobPropertyDescriptor { @Override public boolean isApplicable( @SuppressWarnings("rawtypes") Class<? extends Job> jobType ) { return true; } @Override public JobProperty<?> newInstance( final StaplerRequest req, final JSONObject formData ) throws FormException { final JSONObject watcherData = formData.getJSONObject("watcherEnabled"); if (watcherData.isNullObject()) return null; final String addresses = watcherData.getString( "watcherAddresses" ); if (addresses == null || addresses.isEmpty()) return null; return new WatcherJobProperty(addresses); } public FormValidation doCheckWatcherAddresses(@QueryParameter String value) { return MailWatcherMailer.validateMailAddresses(value); } @Override public String getDisplayName() { return "Notify when Job configuration changes"; } } }
mit
CosmicSubspace/NerdyAudio
app/src/main/java/com/cosmicsubspace/nerdyaudio/animation/EasingEquations.java
4571
//Licensed under the MIT License. //Include the license text thingy if you're gonna use this. //Copyright (c) 2016 Chansol Yang package com.cosmicsubspace.nerdyaudio.animation; public class EasingEquations { public final static int LINEAR = 0; public final static int QUADRATIC = 1; public final static int QUADRATIC_IN = 2; public final static int QUADRATIC_OUT = 3; public final static int SINE = 4; public final static int SINE_OUT = 5; public final static int SINE_IN = 6; public final static int EXPONENTIAL = 7; public final static int EXPONENTIAL_OUT = 8; public final static int EXPONENTIAL_IN = 9; public final static int CIRCULAR = 10; public final static int CIRCULAR_OUT = 11; public final static int CIRCULAR_IN = 12; public final static int CUBIC = 13; public final static int CUBIC_OUT = 14; public final static int CUBIC_IN = 15; public final static int QUARTIC = 16; public final static int QUARTIC_OUT = 17; public final static int QUARTIC_IN = 18; public final static int QUINTIC = 19; public final static int QUINTIC_IN = 20; public final static int QUINTIC_OUT = 21; public static int DEFAULT_EASE = QUINTIC_OUT; public void setDefaultEase(int ease) { DEFAULT_EASE = ease; } public static double ease1D(double start, double end, double current, double startVal, double endVal, int mode) { if (current > end) return endVal; if (current < start) return startVal; double t = current - start; double d = end - start; double b = startVal; double c = endVal - startVal; if (mode == LINEAR) return c * t / d + b; else if (mode == QUADRATIC) { t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; } else if (mode == QUADRATIC_IN) { t /= d; return c * t * t + b; } else if (mode == QUADRATIC_OUT) { t /= d; return -c * t * (t - 2) + b; } else if (mode == SINE) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; } else if (mode == SINE_OUT) { return c * Math.sin(t / d * (Math.PI / 2)) + b; } else if (mode == SINE_IN) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; } else if (mode == EXPONENTIAL) { t /= d / 2; if (t < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; t--; return c / 2 * (-Math.pow(2, -10 * t) + 2) + b; } else if (mode == EXPONENTIAL_OUT) { return c * (-Math.pow(2, -10 * t / d) + 1) + b; } else if (mode == EXPONENTIAL_IN) { return c * Math.pow(2, 10 * (t / d - 1)) + b; } else if (mode == CIRCULAR) { t /= d / 2; if (t < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; t -= 2; return c / 2 * (Math.sqrt(1 - t * t) + 1) + b; } else if (mode == CIRCULAR_OUT) { t /= d; t--; return c * Math.sqrt(1 - t * t) + b; } else if (mode == CIRCULAR_IN) { t /= d; return -c * (Math.sqrt(1 - t * t) - 1) + b; } else if (mode == CUBIC) { t /= d / 2; if (t < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; } else if (mode == CUBIC_OUT) { t /= d; t--; return c * (t * t * t + 1) + b; } else if (mode == CUBIC_IN) { t /= d; return c * t * t * t + b; } else if (mode == QUARTIC) { t /= d / 2; if (t < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; } else if (mode == QUARTIC_OUT) { t /= d; t--; return -c * (t * t * t * t - 1) + b; } else if (mode == QUARTIC_IN) { t /= d; return c * t * t * t * t + b; } else if (mode == QUINTIC) { t /= d / 2; if (t < 1) return c / 2 * t * t * t * t * t + b; t -= 2; return c / 2 * (t * t * t * t * t + 2) + b; } else if (mode == QUINTIC_IN) { t /= d; return c * t * t * t * t * t + b; } else if (mode == QUINTIC_OUT) { t /= d; t--; return c * (t * t * t * t * t + 1) + b; } else return startVal; } }
mit
BetterWithMods/BetterWithMods
src/main/java/betterwithmods/module/GlobalConfig.java
1740
package betterwithmods.module; import betterwithmods.client.gui.GuiStatus; import betterwithmods.common.blocks.BlockHemp; public final class GlobalConfig { public static boolean debug; public static int maxPlatformBlocks; public static void initGlobalConfig() { String category = "_global"; ConfigHelper.needsRestart = ConfigHelper.allNeedRestart = true; debug = ConfigHelper.loadPropBool("Debug", category, "Enables debug features", false); maxPlatformBlocks = ConfigHelper.loadPropInt("Max Platform Blocks", category, "Max blocks a platform can have", 128); ConfigHelper.needsRestart = ConfigHelper.allNeedRestart = false; BlockHemp.growthChance = ConfigHelper.loadPropDouble("Growth Chance","Hemp","Hemp has a 1/X chance of growing where X is this value, the following modifiers divide this value", 15D); BlockHemp.fertileModifier = ConfigHelper.loadPropDouble("Fertile Modifier","Hemp","Modifies Hemp Growth Chance when planted on Fertile Farmland", 1.33); BlockHemp.lampModifier = ConfigHelper.loadPropDouble("Light Block Modifier","Hemp","Modifies Hemp Growth Chance when a Light Block is two blocks above the Hemp", 1.5D); BlockHemp.neighborModifier = ConfigHelper.loadPropDouble("Neighbor Modifier","Hemp","Modifies Hemp Growth Chance for each other crop next to it ", 1.1D); } public static void initGlobalClient() { GuiStatus.offsetY = ConfigHelper.loadPropInt("Status Effect Offset Y", "gui", "Y Offset for the Hunger, Injury and Gloom Status effects.", 0); GuiStatus.offsetX = ConfigHelper.loadPropInt("Status Effect Offset X", "gui", "X Offset for the Hunger, Injury and Gloom Status effects.", 0); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/implementation/ConnectionMonitorResultImpl.java
7050
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_07_01.implementation; import com.microsoft.azure.management.network.v2019_07_01.ConnectionMonitorResult; import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; import rx.Observable; import java.util.Map; import com.microsoft.azure.management.network.v2019_07_01.ConnectionMonitorSource; import com.microsoft.azure.management.network.v2019_07_01.ConnectionMonitorDestination; import com.microsoft.azure.management.network.v2019_07_01.ProvisioningState; import org.joda.time.DateTime; import rx.functions.Func1; class ConnectionMonitorResultImpl extends CreatableUpdatableImpl<ConnectionMonitorResult, ConnectionMonitorResultInner, ConnectionMonitorResultImpl> implements ConnectionMonitorResult, ConnectionMonitorResult.Definition, ConnectionMonitorResult.Update { private final NetworkManager manager; private String resourceGroupName; private String networkWatcherName; private String connectionMonitorName; private ConnectionMonitorInner createOrUpdateParameter; ConnectionMonitorResultImpl(String name, NetworkManager manager) { super(name, new ConnectionMonitorResultInner()); this.manager = manager; // Set resource name this.connectionMonitorName = name; // this.createOrUpdateParameter = new ConnectionMonitorInner(); } ConnectionMonitorResultImpl(ConnectionMonitorResultInner inner, NetworkManager manager) { super(inner.name(), inner); this.manager = manager; // Set resource name this.connectionMonitorName = inner.name(); // set resource ancestor and positional variables this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); this.networkWatcherName = IdParsingUtils.getValueFromIdByName(inner.id(), "networkWatchers"); this.connectionMonitorName = IdParsingUtils.getValueFromIdByName(inner.id(), "connectionMonitors"); // this.createOrUpdateParameter = new ConnectionMonitorInner(); } @Override public NetworkManager manager() { return this.manager; } @Override public Observable<ConnectionMonitorResult> createResourceAsync() { ConnectionMonitorsInner client = this.manager().inner().connectionMonitors(); return client.createOrUpdateAsync(this.resourceGroupName, this.networkWatcherName, this.connectionMonitorName, this.createOrUpdateParameter) .map(new Func1<ConnectionMonitorResultInner, ConnectionMonitorResultInner>() { @Override public ConnectionMonitorResultInner call(ConnectionMonitorResultInner resource) { resetCreateUpdateParameters(); return resource; } }) .map(innerToFluentMap(this)); } @Override public Observable<ConnectionMonitorResult> updateResourceAsync() { ConnectionMonitorsInner client = this.manager().inner().connectionMonitors(); return client.createOrUpdateAsync(this.resourceGroupName, this.networkWatcherName, this.connectionMonitorName, this.createOrUpdateParameter) .map(new Func1<ConnectionMonitorResultInner, ConnectionMonitorResultInner>() { @Override public ConnectionMonitorResultInner call(ConnectionMonitorResultInner resource) { resetCreateUpdateParameters(); return resource; } }) .map(innerToFluentMap(this)); } @Override protected Observable<ConnectionMonitorResultInner> getInnerAsync() { ConnectionMonitorsInner client = this.manager().inner().connectionMonitors(); return client.getAsync(this.resourceGroupName, this.networkWatcherName, this.connectionMonitorName); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } private void resetCreateUpdateParameters() { this.createOrUpdateParameter = new ConnectionMonitorInner(); } @Override public Boolean autoStart() { return this.inner().autoStart(); } @Override public ConnectionMonitorDestination destination() { return this.inner().destination(); } @Override public String etag() { return this.inner().etag(); } @Override public String id() { return this.inner().id(); } @Override public String location() { return this.inner().location(); } @Override public Integer monitoringIntervalInSeconds() { return this.inner().monitoringIntervalInSeconds(); } @Override public String monitoringStatus() { return this.inner().monitoringStatus(); } @Override public String name() { return this.inner().name(); } @Override public ProvisioningState provisioningState() { return this.inner().provisioningState(); } @Override public ConnectionMonitorSource source() { return this.inner().source(); } @Override public DateTime startTime() { return this.inner().startTime(); } @Override public Map<String, String> tags() { return this.inner().getTags(); } @Override public String type() { return this.inner().type(); } @Override public ConnectionMonitorResultImpl withExistingNetworkWatcher(String resourceGroupName, String networkWatcherName) { this.resourceGroupName = resourceGroupName; this.networkWatcherName = networkWatcherName; return this; } @Override public ConnectionMonitorResultImpl withDestination(ConnectionMonitorDestination destination) { this.createOrUpdateParameter.withDestination(destination); return this; } @Override public ConnectionMonitorResultImpl withSource(ConnectionMonitorSource source) { this.createOrUpdateParameter.withSource(source); return this; } @Override public ConnectionMonitorResultImpl withAutoStart(Boolean autoStart) { this.createOrUpdateParameter.withAutoStart(autoStart); return this; } @Override public ConnectionMonitorResultImpl withLocation(String location) { this.createOrUpdateParameter.withLocation(location); return this; } @Override public ConnectionMonitorResultImpl withMonitoringIntervalInSeconds(Integer monitoringIntervalInSeconds) { this.createOrUpdateParameter.withMonitoringIntervalInSeconds(monitoringIntervalInSeconds); return this; } @Override public ConnectionMonitorResultImpl withTags(Map<String, String> tags) { this.createOrUpdateParameter.withTags(tags); return this; } }
mit
TylerNakamura/Calendar-Event-File-Generator
Interface.java
8271
import java.util.Scanner; import java.text.DateFormat; public class Interface { public static void main(String [] args) { boolean exitProgram = false; String userInput = ""; Scanner userInputScanner = new Scanner(System.in); Calendar calendar; //if user enters a command argument if (args.length == 1) { //if user enters a valid .ics file if (!isIcsFile(args[0])) { System.out.println("The entered file is not a valid .ics file!"); return; } System.out.println("importing .ics file into calendar object..."); calendar = new Calendar(args[0]); } //if user enters more than 1 argument else if (args.length > 1) { System.out.println("Too many arguments!"); return; } //no command arguments else { System.out.println("No import specified, creating a new .ics file..."); calendar = new Calendar(); } //get user input while(!exitProgram) { //take user input and converts to lower case System.out.print("Command: "); userInput = userInputScanner.nextLine(); userInput = userInput.toLowerCase(); //list all commands if(userInput.equals("commands")) { printAllCommands(); } //add event to calendar else if(userInput.equals("add")) { calendar.addEvent(addEventInterface()); } //adds a sample event - currently just for speed of testing/debugging else if(userInput.equals("addsample")) { //creates an event then fills it with random valid values Vevent sampleEvent = new Vevent(); sampleEvent.setRandomValues(); //add sample event to the calendar calendar.addEvent(sampleEvent); } //print all events currently in the calendar else if(userInput.equals("printallevents")) { System.out.println(); System.out.println("==================================="); calendar.sortCalendar(); calendar.printAllEvents(); System.out.println("==================================="); System.out.println(); } //print the great circle distance between all events currently in the calendar else if(userInput.equals("printgcd")) { System.out.println(); System.out.println("==================================="); calendar.sortCalendar(); calendar.printGreatCircleDistance(); System.out.println("==================================="); System.out.println(); } //exit application else if(userInput.equals("exit") || userInput.equals("quit")) { System.out.println("Exporting data to " + calendar.getFileName()); calendar.exportIcs(); exitProgram = true; } //If their is no known command for user input else { System.out.println("I am not sure what you mean, perhaps type \"Commands\"?"); } } } private static Vevent addEventInterface() { Vevent vevent = new Vevent(); Scanner userInputScanner = new Scanner(System.in); String temp = ""; boolean addGeo = true; boolean addCLASS = true; //User sets event UID do { System.out.println("\nEnter a valid UID (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validUID(temp)); vevent.setUID(temp); //User sets event DTSTAMP do { System.out.println("\nEnter a valid DTSTAMP (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validDTSTAMP(temp)); vevent.setDTSTAMP(temp); //User sets event ORGANIZER do { System.out.println("\nEnter a valid ORGANIZER (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validORGANIZER(temp)); vevent.setORGANIZER(temp); //User sets event DTSTART do { System.out.println("\nEnter a valid DTSTART (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validDTSTART(temp)); vevent.setDTSTART(temp); //User sets event DTEND do { System.out.println("\nEnter a valid DTEND (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validDTEND(temp)); vevent.setDTEND(temp); //User sets event SUMMARY do { System.out.println("\nEnter a valid SUMMARY (or type \"cancel\" to cancel adding an event):\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); if (temp.equals("cancel")) { return null; } } while(!vevent.validSUMMARY(temp)); vevent.setSUMMARY(temp); //User sets event GEO (optional) do { System.out.println("\nEnter a valid GEO"); System.out.println("or type \"cancel\" to cancel adding an event"); System.out.println("or type \"pass\" to skip adding a GEO parameter to this event"); System.out.println("A valid GEO consists of two decimal values seperated by a semi-colon"); System.out.println("Example: 37.386013;-122.08293\n"); temp = userInputScanner.nextLine(); temp = temp.toLowerCase(); //if the user no longer wants to add an event if (temp.equals("cancel")) { return null; } //if the user doesn't want to add a geo to the event if (temp.equals("pass")) { addGeo = false; break; } } while(!vevent.validGEO(temp)); if(addGeo) { vevent.setGEO(temp); } //User sets event CLASS (optional) do { System.out.println("\nEnter a valid CLASS"); System.out.println("or type \"cancel\" to cancel adding an event"); System.out.println("or type \"pass\" to skip adding a CLASS parameter to this event"); System.out.println("A valid CLASS is either PRIVATE, PUBLIC, or CLASSIFIED\n"); temp = userInputScanner.nextLine(); //if the user no longer wants to add an event if (temp.equals("cancel")) { return null; } //if the user doesn't want to add a CLASS to the event if (temp.equals("pass")) { addCLASS = false; break; } } while(!vevent.validCLASS(temp)); //if the user hasn't passed on adding a class, set the class vairable in the vevent if(addCLASS) { vevent.setCLASS(temp); } return vevent; } /* Returns all possible commands that a user could enter */ private static void printAllCommands() { System.out.println(); System.out.println("=============COMMANDS=============="); System.out.println("commands - print all commands"); System.out.println("exit - export then quit"); System.out.println("add - add a custom event"); System.out.println("printallevents - print every event"); System.out.println("printgcd - print great circle distance"); System.out.println("addsample - add a random event"); System.out.println("==================================="); System.out.println(); } /* Returns true if input is .ics file, false if otherwise modified from http://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java */ private static boolean isIcsFile(String fileName) { String extension = ""; int i = fileName.lastIndexOf('.'); boolean myReturn; if (i > 0) { extension = fileName.substring(i+1); } extension = extension.toLowerCase(); if (extension.equals("ics")) { myReturn = true; } else { myReturn = false; } return myReturn; } }
mit
allegrotech-umk/wildsnake
src/test/java/tech/allegro/wildsnake/integration/WildsnakeApplicationTests.java
2281
package tech.allegro.wildsnake.integration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import tech.allegro.wildsnake.integration.Assertion.ShowCaseItemListAssert; import tech.allegro.wildsnake.integration.builders.ProductListFactory; import tech.allegro.wildsnake.product.model.Product; import tech.allegro.wildsnake.product.repository.ProductRepository; import tech.allegro.wildsnake.showcase.model.ShowcaseItem; import tech.allegro.wildsnake.showcase.service.ShowcaseService; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) public class WildsnakeApplicationTests extends WildSnakeIntegrationTest { private static final int NUMBER_OF_SAVED_PRODUCTS = 6; @Autowired ShowcaseService showcaseService; @Autowired ProductRepository realProductRepository; @Test public void should_show_main_page() { // when ResponseEntity<String> entity = template.getForEntity("http://localhost:8080/", String.class); // then assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Under construction"); assertThat(entity.getBody()).contains("price"); } //BDD way @Test public void shouldRetrieveLast3ProductsFromRepository() { List<Product> givenProduct = givenProduct() .buildNumberOfProductsAndSave(NUMBER_OF_SAVED_PRODUCTS); List<ShowcaseItem> result = whenRetrivalFromRepositoryOccurs(); ShowCaseItemListAssert.assertThat(result) .isSuccessful() .hasNumberOfItems(3) .newestOf(givenProduct); } @Before public void setup() { realProductRepository.deleteAll(); } private ProductListFactory givenProduct() { return new ProductListFactory(realProductRepository); } private List<ShowcaseItem> whenRetrivalFromRepositoryOccurs() { return showcaseService.getItems(); } }
mit
safris-src/org
libx4j/xsb/generator/src/main/java/org/libx4j/xsb/generator/processor/plan/element/MinLengthPlan.java
1121
/* Copyright (c) 2008 lib4j * * 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. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.libx4j.xsb.generator.processor.plan.element; import org.libx4j.xsb.compiler.processor.model.element.MinLengthModel; import org.libx4j.xsb.generator.processor.plan.Plan; public final class MinLengthPlan extends Plan<MinLengthModel> { public MinLengthPlan(final MinLengthModel model, final Plan<?> parent) { super(model, parent); } }
mit
gencer/idea-php-symfony2-plugin
tests/fr/adrienbrault/idea/symfony2plugin/tests/templating/translation/TwigTranslationCompletionContributorTest.java
8098
package fr.adrienbrault.idea.symfony2plugin.tests.templating.translation; import com.jetbrains.twig.TwigFileType; import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern; /** * @author Daniel Espendiller <daniel@espendiller.net> * @see fr.adrienbrault.idea.symfony2plugin.templating.TwigTemplateCompletionContributor */ public class TwigTranslationCompletionContributorTest extends TwigTranslationFixturesTestCase { public void testTwigTransCompletion() { assertCompletionContains(TwigFileType.INSTANCE, "{{ 'foo'|trans({}, '<caret>') }}", "messages"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans }}", "yaml_weak.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ 'foo'|trans({}, '<caret>') }}", "foo"); assertCompletionContains(TwigFileType.INSTANCE, "{{ message|trans({'%name%': 'Haehnchen'}, \"<caret>\") }}", "foo"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans({}, 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{'<caret>'|trans({}, 'foo')}}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>' | trans({}, 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>' | trans( {}, 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>' | trans( {}, 'foo' ) }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans([], 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans|desc('Profile') }}", "yaml_weak.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ 'foo'|trans({}, '<caret>')|desc('Profile') }}", "messages"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans({}, 'foo')|desc('Profile') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain \"foo\" %}\n{{ '<caret>'|trans }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain \"foo\" %}\n{{ '<caret>'|transchoice }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|transchoice(3, {}, 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|transchoice(3, [], 'foo') }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ sonata_block_render({\n" + " 'type': 'nice_block',\n" + " 'settings': {\n" + " 'title': '<caret>'|trans,\n" + " 'more_url': path('more_nice_stuff'),\n" + " 'sub_partner_id': app.request.query.get('sub_partner_id')\n" + " }\n" + " })\n" + "}}", "yaml_weak.symfony.great" ); assertCompletionNotContains(TwigFileType.INSTANCE, "{{ 'foo'|trans|desc('<caret>') }}", "messages"); assertCompletionNotContains(TwigFileType.INSTANCE, "{{ sonata_block_render({\n" + " 'type': 'nice_block',\n" + " 'settings': {\n" + " 'title': 'foo'|trans,\n" + " 'sub_partner_id': app.request.query.get('<caret>')\n" + " }\n" + " })\n" + "}}", "yaml_weak.symfony.great" ); } public void testTwigTransChoiceCompletion() { assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|transchoice(5) }}", "yaml_weak.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain \"foo\" %}\n{{ '<caret>'|transchoice(5) }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|transchoice(5, {'%name%': 'Haehnchen'}) }}", "yaml_weak.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain \"foo\" %}\n{{ '<caret>'|transchoice(5, {'%name%': 'Haehnchen'}) }}", "foo.symfony.great"); assertCompletionContains(TwigFileType.INSTANCE, "{{ message|transchoice(5, {'%name%': 'Haehnchen'}, '<caret>') }}", "messages"); } public void testTwigWeakIndexSubIndexesCompletion() { assertCompletionContains(TwigFileType.INSTANCE, "{{ 'foo'|trans({}, '<caret>') }}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{{ '<caret>'|trans({}, 'interchange') }}", "xlf_weak.symfony.great"); } /** * @see TwigPattern#getTransDefaultDomainPattern * @see fr.adrienbrault.idea.symfony2plugin.templating.TwigTemplateCompletionContributor */ public void testTwigTransDefaultDomainDomainCompletion() { assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain '<caret>' %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain \"<caret>\" %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans_default_domain <caret> %}", "interchange"); } /** * @see TwigPattern#getTranslationTokenTagFromPattern */ public void testTranslationTokenTagFromCompletion() { assertCompletionContains(TwigFileType.INSTANCE, "{% trans from \"<caret>\" %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans from \"<caret>\" %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% \t trans from \"<caret>\" %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% transchoice from \"<caret>\" %}", "interchange"); assertCompletionContains(TwigFileType.INSTANCE, "{% trans with {'%name%': 'Fabien'} from \"<caret>\" %}", "interchange"); assertCompletionNotContains(TwigFileType.INSTANCE, "{% foo from \"<caret>\" %}", "interchange"); } public void testTranslationCompletionForEmbedTransDefaultDomainScope() { assertCompletionContains(TwigFileType.INSTANCE, "" + "{% trans_default_domain 'interchange' %}\n" + "{% embed 'foo.html.twig' %}\n" + " {{ '<caret>'|trans }}\n" + "{% endembed %}\n", "yaml_weak.symfony.great" ); assertCompletionContains(TwigFileType.INSTANCE, "" + "{% embed 'foo.html.twig' %}\n" + " {{ '<caret>'|trans }}\n" + "{% endembed %}\n", "yaml_weak.symfony.great" ); assertCompletionContains(TwigFileType.INSTANCE, "" + "{% embed 'foo.html.twig' %}\n" + " {% trans_default_domain 'interchange' %}" + " {{ '<caret>'|trans }}\n" + "{% endembed %}\n", "xlf_weak.symfony.great" ); } public void testTranslationCompletionForEmbedTransDefaultDomainScopeInsideWithParameter() { assertCompletionContains(TwigFileType.INSTANCE, "" + "{% trans_default_domain 'interchange' %}" + "{% embed 'foo.html.twig' with {'foo': '<caret>'|trans } %}\n" + " {% trans_default_domain 'foobar' %}" + "{% endembed %}\n", "xlf_weak.symfony.great" ); } public void testTransDefaultDomainCompletionShouldQuotedStringValue() { assertCompletionResultEquals( TwigFileType.INSTANCE, "{% trans_default_domain interchang<caret> %}", "{% trans_default_domain \"interchange\" %}" ); assertCompletionResultEquals( TwigFileType.INSTANCE, "{% trans_default_domain 'interchang<caret>' %}", "{% trans_default_domain 'interchange' %}" ); assertCompletionResultEquals( TwigFileType.INSTANCE, "{% trans_default_domain \"interchang<caret>\" %}", "{% trans_default_domain \"interchange\" %}" ); } }
mit
lfmendivelso10/AppModernization
source/i2/miso4301_201520/src/subkdm/SimplifiedDecisionMetrics/util/SimplifiedDecisionMetricsSwitch.java
8571
/** */ package subkdm.SimplifiedDecisionMetrics.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import subkdm.SimplifiedDecisionMetrics.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see subkdm.SimplifiedDecisionMetrics.SimplifiedDecisionMetricsPackage * @generated */ public class SimplifiedDecisionMetricsSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static SimplifiedDecisionMetricsPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SimplifiedDecisionMetricsSwitch() { if (modelPackage == null) { modelPackage = SimplifiedDecisionMetricsPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case SimplifiedDecisionMetricsPackage.OBSERVATION: { Observation observation = (Observation)theEObject; T result = caseObservation(observation); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.MEASURE: { Measure measure = (Measure)theEObject; T result = caseMeasure(measure); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.MEASUREMENT: { Measurement measurement = (Measurement)theEObject; T result = caseMeasurement(measurement); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.GRADE: { Grade grade = (Grade)theEObject; T result = caseGrade(grade); if (result == null) result = caseMeasurement(grade); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.DIMENSIONAL_MEASUREMENT: { DimensionalMeasurement dimensionalMeasurement = (DimensionalMeasurement)theEObject; T result = caseDimensionalMeasurement(dimensionalMeasurement); if (result == null) result = caseMeasurement(dimensionalMeasurement); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.SIMPLIFIED_DECISION_METRICS: { SimplifiedDecisionMetrics simplifiedDecisionMetrics = (SimplifiedDecisionMetrics)theEObject; T result = caseSimplifiedDecisionMetrics(simplifiedDecisionMetrics); if (result == null) result = defaultCase(theEObject); return result; } case SimplifiedDecisionMetricsPackage.MOF_ELEMENT: { MofElement mofElement = (MofElement)theEObject; T result = caseMofElement(mofElement); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Observation</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Observation</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseObservation(Observation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Measure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Measure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMeasure(Measure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Measurement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Measurement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMeasurement(Measurement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Grade</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Grade</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseGrade(Grade object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Dimensional Measurement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Dimensional Measurement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDimensionalMeasurement(DimensionalMeasurement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Simplified Decision Metrics</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Simplified Decision Metrics</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSimplifiedDecisionMetrics(SimplifiedDecisionMetrics object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Mof Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Mof Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMofElement(MofElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //SimplifiedDecisionMetricsSwitch
mit
rnicoll/multidoge
src/main/java/org/multibit/viewsystem/swing/StatusBar.java
29154
/** * Copyright 2011 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.viewsystem.swing; /** * L2FProd.com Common Components 7.3 License. * * Copyright 2005-2007 L2FProd.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.dogecoin.core.Block; import org.multibit.controller.Controller; import org.multibit.controller.bitcoin.BitcoinController; import org.multibit.message.Message; import org.multibit.message.MessageListener; import org.multibit.model.core.StatusEnum; import org.multibit.viewsystem.swing.action.MultiBitAction; import org.multibit.viewsystem.swing.view.components.BlinkLabel; import org.multibit.viewsystem.swing.view.components.FontSizer; import org.multibit.viewsystem.swing.view.components.MultiBitButton; import org.multibit.viewsystem.swing.view.panels.HelpContentsPanel; import org.multibit.viewsystem.swing.view.panels.SendBitcoinPanel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.SimpleDateFormat; import java.util.*; import java.util.Timer; /** * StatusBar. <BR> * A status bar is made of multiple zones. A zone can be any JComponent. * <p/> * In MultiBit the StatusBar is responsible for : * <p/> * 1) Online/ Connecting/ Error status label * 2) Status messages - these are cleared after a period of time * 3) Synchronisation progress bar */ public class StatusBar extends JPanel implements MessageListener { private static final Logger log = LoggerFactory.getLogger(StatusBar.class); private static final long serialVersionUID = 7824115980324911080L; private static final int A_SMALL_NUMBER_OF_PIXELS = 100; private static final int A_LARGE_NUMBER_OF_PIXELS = 1000000; private static final int STATUSBAR_HEIGHT = 30; private static final double TOLERANCE = 0.0000001; public static final int ONLINE_LABEL_WIDTH_DELTA = 12; public static final int ONLINE_LABEL_HEIGHT_DELTA = 8; private JLabel onlineLabel; final private MultiBitButton statusLabel; private StatusEnum statusEnum; public static final long TIMER_REPEAT_TIME = 5000; // millisecond public static final int NUMBER_OF_REPEATS = 12; private Timer statusClearTimer; static boolean clearAutomatically = true; private HashMap<String, Component> idToZones; private Border zoneBorder; private final Controller controller; private final BitcoinController bitcoinController; private MultiBitFrame mainFrame; private JProgressBar syncProgressBar; private SimpleDateFormat dateFormatter; /** * Construct a new StatusBar. */ public StatusBar(BitcoinController bitcoinController, MultiBitFrame mainFrame) { this.bitcoinController = bitcoinController; this.controller = this.bitcoinController; this.mainFrame = mainFrame; setLayout(LookAndFeelTweaks.createHorizontalPercentLayout(controller.getLocaliser().getLocale())); idToZones = new HashMap<String, Component>(); setZoneBorder(BorderFactory.createEmptyBorder()); setBackground(ColorAndFontConstants.MID_BACKGROUND_COLOR); setOpaque(true); setBorder(BorderFactory.createMatteBorder(2, 0, 2, 0, ColorAndFontConstants.MID_BACKGROUND_COLOR)); applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); final BitcoinController finalController = this.bitcoinController; dateFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm", controller.getLocaliser().getLocale()); onlineLabel = new JLabel(""); onlineLabel.setFont(FontSizer.INSTANCE.getAdjustedDefaultFont()); onlineLabel.setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); onlineLabel.setOpaque(true); onlineLabel.setHorizontalAlignment(SwingConstants.CENTER); onlineLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); onlineLabel.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent arg0) { int blockHeight = -1; if (finalController.getMultiBitService() != null) { if (finalController.getMultiBitService().getChain() != null) { if (finalController.getMultiBitService().getChain().getChainHead() != null) { blockHeight = finalController.getMultiBitService().getChain().getChainHead().getHeight(); Block blockHeader = finalController.getMultiBitService().getChain().getChainHead().getHeader(); Date blockTime = blockHeader.getTime(); int numberOfPeers = 0; if (finalController.getMultiBitService().getPeerGroup() != null && finalController.getMultiBitService().getPeerGroup().getConnectedPeers() != null) { numberOfPeers = finalController.getMultiBitService().getPeerGroup().getConnectedPeers().size(); } onlineLabel.setToolTipText(HelpContentsPanel.createMultilineTooltipText(new String[]{ finalController.getLocaliser().getString("multiBitFrame.numberOfBlocks", new Object[]{blockHeight}), finalController.getLocaliser().getString("multiBitFrame.blockDate", new Object[]{dateFormatter.format(blockTime)}), finalController.getLocaliser().getString("multiBitFrame.connectedTo", new Object[]{numberOfPeers})})); } } } } }); statusLabel = new MultiBitButton(""); statusLabel.setBackground(ColorAndFontConstants.MID_BACKGROUND_COLOR); statusLabel.setOpaque(true); statusLabel.setBorderPainted(false); statusLabel.setForeground(Color.BLACK); //statusLabel.setBorder(BorderFactory.createLineBorder(Color.CYAN)); statusLabel.setFocusPainted(false); statusLabel.setContentAreaFilled(false); statusLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); // show messages action MultiBitAction showMessagesAction = new MultiBitAction(controller, null, null, "messagesPanel.title", "messagesPanel.mnemonic", org.multibit.viewsystem.View.MESSAGES_VIEW); statusLabel.setAction(showMessagesAction); statusLabel.setHorizontalAlignment(JButton.LEADING); String tooltipText = HelpContentsPanel.createMultilineTooltipText(new String[]{ controller.getLocaliser().getString("multiBitFrame.statusBar.tooltip1"), "\n", controller.getLocaliser().getString("multiBitFrame.statusBar.tooltip2")}); statusLabel.setToolTipText(tooltipText); int onlineWidth = Math.max(Math.max( getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).stringWidth( controller.getLocaliser().getString("multiBitFrame.onlineText")), getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).stringWidth( controller.getLocaliser().getString("multiBitFrame.offlineText"))), getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).stringWidth( controller.getLocaliser().getString("multiBitFrame.errorText")) ) + ONLINE_LABEL_WIDTH_DELTA; int onlineHeight = getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).getHeight() + ONLINE_LABEL_HEIGHT_DELTA; onlineLabel.setPreferredSize(new Dimension(onlineWidth, onlineHeight)); int statusBarHeight = Math.max(STATUSBAR_HEIGHT, onlineHeight); setMaximumSize(new Dimension(A_LARGE_NUMBER_OF_PIXELS, statusBarHeight)); setMaximumSize(new Dimension(A_SMALL_NUMBER_OF_PIXELS, statusBarHeight)); syncProgressBar = new JProgressBar(0, 100); syncProgressBar.setValue(0); syncProgressBar.setStringPainted(false); syncProgressBar.setVisible(false); syncProgressBar.setBackground(ColorAndFontConstants.MID_BACKGROUND_COLOR); syncProgressBar.setOpaque(true); syncProgressBar.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); JPanel filler = new JPanel(); filler.setOpaque(true); filler.setBackground(ColorAndFontConstants.MID_BACKGROUND_COLOR); addZone("online", onlineLabel, "" + onlineWidth, "left"); addZone("progressBar", syncProgressBar, "" + 200, "left"); addZone("network", statusLabel, "*", ""); addZone("filler2", filler, "0", "right"); statusClearTimer = new java.util.Timer(); statusClearTimer.schedule(new StatusClearTask(statusLabel), TIMER_REPEAT_TIME, TIMER_REPEAT_TIME); } /** * initialise the statusbar; */ public void initialise() { updateOnlineStatusText(StatusEnum.CONNECTING); updateStatusLabel("", true); } /** * refresh online status text with existing value */ public void refreshOnlineStatusText() { updateOnlineStatusText(statusEnum); } /** * Update online status text with new value. * * @param finalStatusEnum */ public void updateOnlineStatusText(final StatusEnum finalStatusEnum) { if (EventQueue.isDispatchThread()) { updateOnlineStatusTextOnSwingThread(finalStatusEnum); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateOnlineStatusTextOnSwingThread(finalStatusEnum); } }); } } /** * Update online status text with new value. * * @param finalStatusEnum */ public void updateOnlineStatusTextOnSwingThread(final StatusEnum finalStatusEnum) { this.statusEnum = finalStatusEnum; String onlineStatus = controller.getLocaliser().getString(finalStatusEnum.getLocalisationKey()); if (finalStatusEnum == StatusEnum.ONLINE) { onlineLabel.setForeground(new Color(0, 100, 0)); if (mainFrame != null) { BlinkLabel estimatedBalanceBTCLabel = mainFrame.getEstimatedBalanceBTCLabel(); if (estimatedBalanceBTCLabel != null) { estimatedBalanceBTCLabel.setBlinkEnabled(true); } BlinkLabel estimatedBalanceFiatLabel = mainFrame.getEstimatedBalanceFiatLabel(); if (estimatedBalanceFiatLabel != null) { estimatedBalanceFiatLabel.setBlinkEnabled(true); } } } else { onlineLabel.setForeground(new Color(180, 0, 0)); } onlineLabel.setText(onlineStatus); if (finalStatusEnum == StatusEnum.ERROR) { // Set tooltip to look at Messages view String toolTip = HelpContentsPanel.createMultilineTooltipText(new String[]{ controller.getLocaliser().getString("multiBitFrame.statusBar.error1"), controller.getLocaliser().getString("multiBitFrame.statusBar.error2")}); onlineLabel.setToolTipText(toolTip); } } synchronized private void startSync() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Switch off the Send button SendBitcoinPanel.setEnableSendButton(false); syncProgressBar.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); syncProgressBar.setValue(0); syncProgressBar.setVisible(true); } }); } synchronized private void finishSync() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Switch on the Send button SendBitcoinPanel.setEnableSendButton(true); syncProgressBar.setValue(100); syncProgressBar.setVisible(false); } }); } synchronized private void updateSync(final int percent, final String syncMessage) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { syncProgressBar.setValue(percent); syncProgressBar.setToolTipText(HelpContentsPanel.createTooltipText(syncMessage)); // when a language changes the progress bar needs to be made visible syncProgressBar.setVisible(true); } }); } @Override public void newMessageReceived(final Message newMessage) { if (newMessage == null || !newMessage.isShowInStatusBar()) { return; } if (newMessage.getPercentComplete() == Message.NOT_RELEVANT_PERCENTAGE_COMPLETE) { updateStatusLabel(newMessage.getText(), newMessage.isClearAutomatically()); } else { if (Math.abs(newMessage.getPercentComplete() - 0) < TOLERANCE) { startSync(); } updateSync((int) newMessage.getPercentComplete(), newMessage.getText()); if (Math.abs(newMessage.getPercentComplete() - 100) < TOLERANCE) { finishSync(); } } } private void updateStatusLabel(final String newStatusLabel, Boolean clearAutomatically) { StatusBar.clearAutomatically = clearAutomatically; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (statusLabel != null) { log.debug("StatusBar label = '" + newStatusLabel + "'"); statusLabel.setText(newStatusLabel); } } }); } private void setZoneBorder(Border border) { zoneBorder = border; } /** * Adds a new zone in the StatusBar * * @param id * @param zone * @param constraints one of the constraint support by the * com.l2fprod.common.swing.PercentLayout */ private void addZone(String id, Component zone, String constraints, String tweak) { // is there already a zone with this id? Component previousZone = getZone(id); if (previousZone != null) { remove(previousZone); idToZones.remove(id); } if (zone instanceof JComponent) { JComponent jc = (JComponent) zone; jc.setOpaque(true); //jc.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); if (jc.getBorder() == null || jc.getBorder() instanceof UIResource) { if (jc instanceof JLabel) { if ("left".equals(tweak)) { Border border = new CompoundBorder(BorderFactory.createMatteBorder(0, 3, 0, 2, ColorAndFontConstants.BACKGROUND_COLOR), BorderFactory .createLineBorder(Color.lightGray)); jc.setBorder(border); } else { if ("right".equals(tweak)) { jc.setBorder(new CompoundBorder(zoneBorder, new EmptyBorder(0, 2, 0, 1))); } else { jc.setBorder(new CompoundBorder(zoneBorder, new EmptyBorder(0, 2, 0, 2))); } } ((JLabel) jc).setText(" "); } else { if (!(jc instanceof JPanel)) { jc.setBorder(zoneBorder); } } } } add(zone, constraints); idToZones.put(id, zone); } public Component getZone(String id) { return idToZones.get(id); } } /** * PercentLayout. <BR> * Constraint based layout which allow the space to be splitted using * percentages. The following are allowed when adding components to container: * <ul> * <li>container.add(component); <br> * in this case, the component will be sized to its preferred size * <li>container.add(component, "100"); <br> * in this case, the component will have a width (or height) of 100 * <li>container.add(component, "25%"); <br> * in this case, the component will have a width (or height) of 25 % of the * container width (or height) <br> * <li>container.add(component, "*"); <br> * in this case, the component will take the remaining space. if several * components use the "*" constraint the space will be divided among the * components. * </ul> * * @javabean.class name="PercentLayout" * shortDescription="A layout supports constraints expressed in percent." */ class PercentLayout implements LayoutManager2 { /** * Useful constant to layout the components horizontally (from top to * bottom). */ public final static int HORIZONTAL = 0; /** * Useful constant to layout the components vertically (from left to right). */ public final static int VERTICAL = 1; static class Constraint { protected Object value; private Constraint(Object value) { this.value = value; } } static class NumberConstraint extends Constraint { public NumberConstraint(int d) { this(Integer.valueOf(d)); } public NumberConstraint(Integer d) { super(d); } public int intValue() { return (Integer) value; } } static class PercentConstraint extends Constraint { public PercentConstraint(float d) { super(d); } public float floatValue() { return (Float) value; } } private final static Constraint REMAINING_SPACE = new Constraint("*"); private final static Constraint PREFERRED_SIZE = new Constraint(""); private int orientation; private int gap; private Locale locale; // Consider using HashMap private Hashtable<Component, Constraint> m_ComponentToConstraint; public PercentLayout(int orientation, int gap, Locale locale) { setOrientation(orientation); this.gap = gap; this.locale = locale; m_ComponentToConstraint = new Hashtable<Component, Constraint>(); } public void setGap(int gap) { this.gap = gap; } /** * @javabean.property bound="true" preferred="true" */ public int getGap() { return gap; } public void setOrientation(int orientation) { if (orientation != HORIZONTAL && orientation != VERTICAL) { throw new IllegalArgumentException("Orientation must be one of HORIZONTAL or VERTICAL"); } this.orientation = orientation; } /** * @javabean.property bound="true" preferred="true" */ public int getOrientation() { return orientation; } public void setConstraint(Component component, Object constraints) { if (constraints instanceof Constraint) { m_ComponentToConstraint.put(component, (Constraint) constraints); } else if (constraints instanceof Number) { setConstraint(component, new NumberConstraint(((Number) constraints).intValue())); } else if ("*".equals(constraints)) { setConstraint(component, REMAINING_SPACE); } else if ("".equals(constraints)) { setConstraint(component, PREFERRED_SIZE); } else if (constraints instanceof String) { String s = (String) constraints; if (s.endsWith("%")) { float value = Float.valueOf(s.substring(0, s.length() - 1)) / 100; if (value > 1 || value < 0) { throw new IllegalArgumentException("percent value must be >= 0 and <= 100"); } setConstraint(component, new PercentConstraint(value)); } else { setConstraint(component, new NumberConstraint(Integer.valueOf(s))); } } else if (constraints == null) { // null constraint means preferred size setConstraint(component, PREFERRED_SIZE); } else { throw new IllegalArgumentException("Invalid Constraint"); } } @Override public void addLayoutComponent(Component component, Object constraints) { setConstraint(component, constraints); } /** * 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. */ @Override public float getLayoutAlignmentX(Container target) { return 1.0f / 2.0f; } /** * 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. */ @Override public float getLayoutAlignmentY(Container target) { return 1.0f / 2.0f; } /** * Invalidates the layout, indicating that if the layout manager has cached * information it should be discarded. */ @Override public void invalidateLayout(Container target) { } /** * Adds the specified component with the specified name to the layout. * * @param name the component name * @param comp the component to be added */ @Override public void addLayoutComponent(String name, Component comp) { } /** * Removes the specified component from the layout. * * @param comp the component ot be removed */ @Override public void removeLayoutComponent(Component comp) { m_ComponentToConstraint.remove(comp); } /** * 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 * @see #preferredLayoutSize */ @Override public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } /** * Returns the maximum size of this component. * * @see java.awt.Component#getMinimumSize() * @see java.awt.Component#getPreferredSize() * @see java.awt.LayoutManager */ @Override public Dimension maximumLayoutSize(Container parent) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } @Override public Dimension preferredLayoutSize(Container parent) { Component[] components = parent.getComponents(); Insets insets = parent.getInsets(); int width = 0; int height = 0; Dimension componentPreferredSize; boolean firstVisibleComponent = true; for (int i = 0, c = components.length; i < c; i++) { if (components[i].isVisible()) { componentPreferredSize = components[i].getPreferredSize(); if (orientation == HORIZONTAL) { height = Math.max(height, componentPreferredSize.height); width += componentPreferredSize.width; if (firstVisibleComponent) { firstVisibleComponent = false; } else { width += gap; } } else { height += componentPreferredSize.height; width = Math.max(width, componentPreferredSize.width); if (firstVisibleComponent) { firstVisibleComponent = false; } else { height += gap; } } } } return new Dimension(width + insets.right + insets.left, height + insets.top + insets.bottom); } @Override public void layoutContainer(Container parent) { Insets insets = parent.getInsets(); Dimension d = parent.getSize(); // calculate the available sizes d.width = d.width - insets.left - insets.right; d.height = d.height - insets.top - insets.bottom; // pre-calculate the size of each components Component[] components = parent.getComponents(); int[] sizes = new int[components.length]; // calculate the available size int availableSize = (HORIZONTAL == orientation ? d.width : d.height) - (components.length - 1) * gap; // PENDING(fred): the following code iterates 4 times on the component // array, need to find something more efficient! // give priority to components who want to use their preferred size or // who // have a predefined size for (int i = 0, c = components.length; i < c; i++) { if (components[i].isVisible()) { Constraint constraint = m_ComponentToConstraint.get(components[i]); if (constraint == null || constraint == PREFERRED_SIZE) { sizes[i] = (HORIZONTAL == orientation ? components[i].getPreferredSize().width : components[i] .getPreferredSize().height); availableSize -= sizes[i]; } else if (constraint instanceof NumberConstraint) { sizes[i] = ((NumberConstraint) constraint).intValue(); availableSize -= sizes[i]; } } } // then work with the components who want a percentage of the remaining // space int remainingSize = availableSize; for (int i = 0, c = components.length; i < c; i++) { if (components[i].isVisible()) { Constraint constraint = m_ComponentToConstraint.get(components[i]); if (constraint instanceof PercentConstraint) { sizes[i] = (int) (remainingSize * ((PercentConstraint) constraint).floatValue()); availableSize -= sizes[i]; } } } // finally share the remaining space between the other components ArrayList<Integer> remaining = new ArrayList<Integer>(); for (int i = 0, c = components.length; i < c; i++) { if (components[i].isVisible()) { Constraint constraint = m_ComponentToConstraint.get(components[i]); if (constraint == REMAINING_SPACE) { remaining.add(i); sizes[i] = 0; } } } if (remaining.size() > 0) { int rest = availableSize / remaining.size(); for (Integer aRemaining : remaining) { sizes[aRemaining] = rest; } } // all calculations are done, apply the sizes int currentOffset = (HORIZONTAL == orientation ? insets.left : insets.top); if (!ComponentOrientation.getOrientation(locale).isLeftToRight()) { currentOffset = (HORIZONTAL == orientation ? d.width - insets.right : insets.top); } for (int i = 0, c = components.length; i < c; i++) { if (components[i].isVisible()) { if (HORIZONTAL == orientation) { if (ComponentOrientation.getOrientation(locale).isLeftToRight()) { components[i].setBounds(currentOffset, insets.top, sizes[i], d.height); } else { components[i].setBounds(currentOffset - sizes[i], insets.top, sizes[i], d.height); } } else { components[i].setBounds(insets.left, currentOffset, d.width, sizes[i]); } if (ComponentOrientation.getOrientation(locale).isLeftToRight()) { currentOffset += gap + sizes[i]; } else { currentOffset = currentOffset - gap - sizes[i]; } } } } } class StatusClearTask extends TimerTask { JButton statusLabel; private String previousStatusLabelText = null; private int previousLabelRepeats = 0; StatusClearTask(JButton statusLabel) { this.statusLabel = statusLabel; } @Override public void run() { String currentStatusLabelText = statusLabel.getText(); boolean hasReset = false; if (previousLabelRepeats > StatusBar.NUMBER_OF_REPEATS) { if (currentStatusLabelText != null && !"".equals(currentStatusLabelText) && currentStatusLabelText.equals(previousStatusLabelText)) { if (StatusBar.clearAutomatically) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // clear label statusLabel.setText(""); } }); previousStatusLabelText = ""; previousLabelRepeats = 0; hasReset = true; } } } if (currentStatusLabelText != null && !currentStatusLabelText.equals(previousStatusLabelText)) { // different - reset previousStatusLabelText = currentStatusLabelText; previousLabelRepeats = 0; } else { if (currentStatusLabelText != null && currentStatusLabelText.equals(previousStatusLabelText)) { if (!hasReset) { // label is the same as before previousLabelRepeats++; } } } } } /** * LookAndFeelTweaks */ final class LookAndFeelTweaks { public final static Border PANEL_BORDER = BorderFactory.createMatteBorder(3, 3, 3, 3, ColorAndFontConstants.MID_BACKGROUND_COLOR); /** * Utility class should not have a public constructor */ private LookAndFeelTweaks() { } public static PercentLayout createHorizontalPercentLayout(Locale locale) { return new PercentLayout(PercentLayout.HORIZONTAL, 4, locale); } public static void setBorder(JComponent component) { if (component instanceof JPanel) { component.setBorder(PANEL_BORDER); } } }
mit
meiyi1986/GPJSS
src/ec/app/parity/func/D26.java
1195
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.app.parity.func; import ec.*; import ec.app.parity.*; import ec.gp.*; import ec.util.*; /* * D26.java * * Created: Wed Nov 3 18:26:38 1999 * By: Sean Luke */ /** * @author Sean Luke * @version 1.0 */ public class D26 extends GPNode { public String toString() { return "D26"; } /* public void checkConstraints(final EvolutionState state, final int tree, final GPIndividual typicalIndividual, final Parameter individualBase) { super.checkConstraints(state,tree,typicalIndividual,individualBase); if (children.length!=0) state.output.error("Incorrect number of children for node " + toStringForError() + " at " + individualBase); } */ public int expectedChildren() { return 0; } public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { ((ParityData)input).x = ((((Parity)problem).bits >>> 26 ) & 1); } }
mit
navalev/azure-sdk-for-java
sdk/sql/mgmt-v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/DisasterRecoveryConfigurationRole.java
1704
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.sql.v2014_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for DisasterRecoveryConfigurationRole. */ public final class DisasterRecoveryConfigurationRole extends ExpandableStringEnum<DisasterRecoveryConfigurationRole> { /** Static value None for DisasterRecoveryConfigurationRole. */ public static final DisasterRecoveryConfigurationRole NONE = fromString("None"); /** Static value Primary for DisasterRecoveryConfigurationRole. */ public static final DisasterRecoveryConfigurationRole PRIMARY = fromString("Primary"); /** Static value Secondary for DisasterRecoveryConfigurationRole. */ public static final DisasterRecoveryConfigurationRole SECONDARY = fromString("Secondary"); /** * Creates or finds a DisasterRecoveryConfigurationRole from its string representation. * @param name a name to look for * @return the corresponding DisasterRecoveryConfigurationRole */ @JsonCreator public static DisasterRecoveryConfigurationRole fromString(String name) { return fromString(name, DisasterRecoveryConfigurationRole.class); } /** * @return known DisasterRecoveryConfigurationRole values */ public static Collection<DisasterRecoveryConfigurationRole> values() { return values(DisasterRecoveryConfigurationRole.class); } }
mit
samarjit/mywapama
designer/src/test/server/de/hpi/petrinet/verification/PetriNetSoundnessCheckerTest.java
2058
package de.hpi.petrinet.verification; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import de.hpi.petrinet.AbstractPetriNetTest; import de.hpi.petrinet.PetriNet; public class PetriNetSoundnessCheckerTest extends AbstractPetriNetTest{ @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testIsRelaxedSound(){ /** * A not relaxed sound petri net */ PetriNet net = this.openPetriNetFromFile("verification/notRelaxedSoundPetrinet.xml"); PetriNetSoundnessChecker checker = new PetriNetSoundnessChecker(net); checker.calculateRG(); assertFalse(checker.isRelaxedSound()); assertEquals(1, checker.getNotParticipatingTransitions().size()); assertEquals("t3", checker.getNotParticipatingTransitions().iterator().next().getId()); /** * A relaxed sound petri net */ PetriNet net2 = this.openPetriNetFromFile("verification/relaxedSoundPetrinet.xml"); PetriNetSoundnessChecker checker2 = new PetriNetSoundnessChecker(net2); checker2.calculateRG(); assertTrue(checker2.isRelaxedSound()); /** * A not relaxed sound petri net (when there are 2 tokens in final place, this isn't a final state) */ PetriNet net3 = this.openPetriNetFromFile("verification/notRelaxedSound2.xml"); PetriNetSoundnessChecker checker3 = new PetriNetSoundnessChecker(net3); checker3.calculateRG(); assertFalse(checker3.isRelaxedSound()); assertFalse(checker3.isSound()); assertFalse(checker3.isWeakSound()); assertEquals(2, checker3.getNotParticipatingTransitions().size()); // Should have no deadlocks assertEquals(0, checker3.getDeadLockMarkings().size()); } }
mit
cjbi/wetech-cms
wetech-core/src/test/java/tech/wetech/cms/dao/ChannelAndTopicTest.java
1852
package tech.wetech.cms.dao; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.inject.Inject; import org.dbunit.DatabaseUnitException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.orm.hibernate4.SessionHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.support.TransactionSynchronizationManager; import tech.wetech.cms.model.Channel; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/beans.xml") public class ChannelAndTopicTest { @Inject private SessionFactory sessionFactory; @Inject private IChannelDao channelDao; @Before public void setUp() throws SQLException, IOException, DatabaseUnitException { //此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu Session s = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s)); } @Test public void testTopNav() { List<Channel> cs = channelDao.listTopNavChannel(); for(Channel c:cs) { System.out.println(c.getId()+","+c.getName()+","+c.getCustomLink()+","+c.getCustomLinkUrl()); } } @After public void tearDown() throws DatabaseUnitException, SQLException, IOException { SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); Session s = holder.getSession(); s.flush(); TransactionSynchronizationManager.unbindResource(sessionFactory); } }
mit
helloyingying/CircularFloatingActionMenu
library/src/main/java/com/oguzdev/circularfloatingactionmenu/library/SubActionButton.java
5167
/* * Copyright 2014 Oguz Bilgener */ package com.oguzdev.circularfloatingactionmenu.library; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; /** * A simple button implementation with a similar look an feel to{@link FloatingActionButton}. */ public class SubActionButton extends FrameLayout { public static final int THEME_LIGHT = 0; public static final int THEME_DARK = 1; public static final int THEME_LIGHTER = 2; public static final int THEME_DARKER = 3; public SubActionButton(Activity activity, FrameLayout.LayoutParams layoutParams, int theme, Drawable backgroundDrawable, View contentView, FrameLayout.LayoutParams contentParams) { super(activity); setLayoutParams(layoutParams); // If no custom backgroundDrawable is specified, use the background drawable of the theme. if(backgroundDrawable == null) { if(theme == THEME_LIGHT) { backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_sub_action_selector); } else if(theme == THEME_DARK) { backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_sub_action_dark_selector); } else if(theme == THEME_LIGHTER) { backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_action_selector); } else if(theme == THEME_DARKER) { backgroundDrawable = activity.getResources().getDrawable(R.drawable.button_action_dark_selector); } else { throw new RuntimeException("Unknown SubActionButton theme: " + theme); } } else { backgroundDrawable = backgroundDrawable.mutate().getConstantState().newDrawable(); } setBackgroundResource(backgroundDrawable); if(contentView != null) { setContentView(contentView, contentParams); } setClickable(true); } /** * Sets a content view with custom LayoutParams that will be displayed inside this SubActionButton. * @param contentView * @param params */ public void setContentView(View contentView, FrameLayout.LayoutParams params) { if(params == null) { params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER); final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin); params.setMargins(margin, margin, margin, margin); } contentView.setClickable(false); this.addView(contentView, params); } /** * Sets a content view with default LayoutParams * @param contentView */ public void setContentView(View contentView) { setContentView(contentView, null); } private void setBackgroundResource(Drawable drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } else { setBackgroundDrawable(drawable); } } /** * A builder for {@link SubActionButton} in conventional Java Builder format */ public static class Builder { private Activity activity; private FrameLayout.LayoutParams layoutParams; private int theme; private Drawable backgroundDrawable; private View contentView; private FrameLayout.LayoutParams contentParams; public Builder(Activity activity) { this.activity = activity; // Default SubActionButton settings int size = activity.getResources().getDimensionPixelSize(R.dimen.sub_action_button_size); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(size, size, Gravity.TOP | Gravity.LEFT); setLayoutParams(params); setTheme(SubActionButton.THEME_LIGHT); } public Builder setLayoutParams(FrameLayout.LayoutParams params) { this.layoutParams = params; return this; } public Builder setTheme(int theme) { this.theme = theme; return this; } public Builder setBackgroundDrawable(Drawable backgroundDrawable) { this.backgroundDrawable = backgroundDrawable; return this; } public Builder setContentView(View contentView) { this.contentView = contentView; return this; } public Builder setContentView(View contentView, FrameLayout.LayoutParams contentParams) { this.contentView = contentView; this.contentParams = contentParams; return this; } public SubActionButton build() { return new SubActionButton(activity, layoutParams, theme, backgroundDrawable, contentView, contentParams); } } }
mit
aspose-cells/Aspose.Cells-for-Cloud
SDKs/Aspose.Cells-Cloud-SDK-for-Java/src/main/java/com/aspose/client/auth/Authentication.java
425
package com.aspose.client.auth; import com.aspose.client.Pair; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-08-09T13:55:38.644+05:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List<Pair> queryParams, Map<String, String> headerParams); }
mit
SSSSQD/Transwarp-Data-Hub-Collection-Project
keywordSearch/src/main/java/io/transwarp/keywordsearch/SampleCode.java
206
package io.transwarp.keywordsearch; public class SampleCode { // 主函数 public static void main(String... args) { Manager manager = new Manager(); manager.go(); } }
mit
accelazh/FileRecord
src/org/accela/file/record/impl/test/TestPlainRecordPool.java
693
package org.accela.file.record.impl.test; import java.io.IOException; import org.accela.file.record.RecordPool; public class TestPlainRecordPool extends TestRecordPool { public TestPlainRecordPool() { super(false, false); } @Override protected RecordPool createRecordPool(int slotSize, long poolSize) throws IOException { return new PlainRecordPoolFactory().create(slotSize, poolSize); } public static void main(String[] args) throws Exception { TestPlainRecordPool t=new TestPlainRecordPool(); t.setUp(); long startTime=System.nanoTime(); t.testPerformance(); System.out.println(System.nanoTime()-startTime); t.tearDown(); } }
mit
wwah/AndroidBasicLibs
common/src/main/java/cn/wwah/common/net/convert/GsonConverterFactory.java
1656
package cn.wwah.common.net.convert; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit; /** * @Description: GSON转换工厂 * @author: jeasinlee * @date: 16/12/31 12:19. */ public class GsonConverterFactory extends Converter.Factory { private final Gson gson; private GsonConverterFactory(Gson gson) { if (gson == null) throw new NullPointerException("gson == null"); this.gson = gson; } public static GsonConverterFactory create() { return create(new Gson()); } public static GsonConverterFactory create(Gson gson) { return new GsonConverterFactory(gson); } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (type != null && type.equals(String.class)) { return new JsonResponseBodyConverter<>(); } TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type != null ? type : null)); return new GsonResponseBodyConverter<>(gson, adapter); } @Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); return new GsonRequestBodyConverter<>(gson, adapter); } }
mit
MeasureAuthoringTool/MeasureAuthoringTool_LatestSprint
mat/src/main/java/mat/model/clause/CQLLibraryExport.java
1296
package mat.model.clause; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="CQL_LIBRARY_EXPORT") public class CQLLibraryExport { @Id @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy = "uuid") private String id; @OneToOne @JoinColumn(name = "CQL_LIBRARY_ID") private CQLLibrary cqlLibrary; @Column(name="CQL") private String cql; @Column(name="ELM") private String elm; @Column(name="JSON") private String json; public String getId() { return id; } public void setId(String id) { this.id = id; } public CQLLibrary getCqlLibrary() { return cqlLibrary; } public void setCqlLibrary(CQLLibrary cqlLibrary) { this.cqlLibrary = cqlLibrary; } public String getCql() { return cql; } public void setCql(String cql) { this.cql = cql; } public String getElm() { return elm; } public void setElm(String elm) { this.elm = elm; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } }
cc0-1.0
paulianttila/openhab2
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/handler/MiIoGenericHandler.java
2216
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.miio.internal.handler; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService; import org.openhab.binding.miio.internal.cloud.CloudConnector; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link MiIoGenericHandler} is responsible for handling commands for devices that are not yet defined. * Once the device has been determined, the proper handler is loaded. * * @author Marcel Verpaalen - Initial contribution */ @NonNullByDefault public class MiIoGenericHandler extends MiIoAbstractHandler { private final Logger logger = LoggerFactory.getLogger(MiIoGenericHandler.class); public MiIoGenericHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService, CloudConnector cloudConnector) { super(thing, miIoDatabaseWatchService, cloudConnector); } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (command == RefreshType.REFRESH) { logger.debug("Refreshing {}", channelUID); updateData(); return; } if (handleCommandsChannels(channelUID, command)) { return; } } @Override protected synchronized void updateData() { if (skipUpdate()) { return; } logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID()); try { refreshNetwork(); } catch (Exception e) { logger.debug("Error while updating '{}'", getThing().getUID().toString(), e); } } }
epl-1.0
ibh-systems/packagedrone
bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformationParser.java
9247
/******************************************************************************* * Copyright (c) 2014, 2016 IBH SYSTEMS GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBH SYSTEMS GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.packagedrone.repo.utils.osgi.bundle; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.packagedrone.repo.utils.osgi.ParserHelper; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.BundleRequirement; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.CapabilityValue; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageExport; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageImport; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.ProvideCapability; import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.RequireCapability; import org.eclipse.packagedrone.utils.AttributedValue; import org.eclipse.packagedrone.utils.Headers; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.osgi.framework.VersionRange; public class BundleInformationParser { private final ZipFile file; private final Manifest manifest; public BundleInformationParser ( final ZipFile file ) { this.file = file; this.manifest = null; } public BundleInformationParser ( final ZipFile file, final Manifest manifest ) { this.file = file; this.manifest = manifest; } @SuppressWarnings ( "deprecation" ) public BundleInformation parse () throws IOException { final BundleInformation result = new BundleInformation (); Manifest m = null; if ( this.manifest != null ) { m = this.manifest; } else if ( this.file != null ) { m = getManifest ( this.file ); } if ( m == null ) { return null; } final Attributes ma = m.getMainAttributes (); final AttributedValue id = Headers.parse ( ma.getValue ( Constants.BUNDLE_SYMBOLICNAME ) ); final AttributedValue version = Headers.parse ( ma.getValue ( Constants.BUNDLE_VERSION ) ); if ( id == null || version == null ) { return null; } result.setId ( id.getValue () ); result.setSingleton ( Boolean.parseBoolean ( id.getAttributes ().get ( "singleton" ) ) ); try { result.setVersion ( new Version ( version.getValue () ) ); } catch ( final Exception e ) { throw new IllegalArgumentException ( String.format ( "Illegal OSGi version: %s", version.getValue () ) ); } result.setName ( ma.getValue ( Constants.BUNDLE_NAME ) ); result.setVendor ( ma.getValue ( Constants.BUNDLE_VENDOR ) ); result.setDocUrl ( ma.getValue ( Constants.BUNDLE_DOCURL ) ); result.setLicense ( makeLicense ( ma.getValue ( Constants.BUNDLE_LICENSE ) ) ); result.setDescription ( ma.getValue ( Constants.BUNDLE_DESCRIPTION ) ); result.setEclipseBundleShape ( ma.getValue ( "Eclipse-BundleShape" ) ); result.setRequiredExecutionEnvironments ( Headers.parseStringList ( ma.getValue ( Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT ) ) ); processImportPackage ( result, ma ); processExportPackage ( result, ma ); processImportBundle ( result, ma ); processCapabilities ( result, ma ); attachLocalization ( result, ma ); return result; } private String makeLicense ( final String value ) { final AttributedValue license = Headers.parse ( value ); if ( license == null ) { return null; } return license.getValue (); } private void processImportBundle ( final BundleInformation result, final Attributes ma ) { for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.REQUIRE_BUNDLE ) ) ) ) { final String name = av.getValue (); final String vs = av.getAttributes ().get ( "bundle-version" ); VersionRange vr = null; if ( vs != null ) { vr = new VersionRange ( vs ); } final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) ); final boolean reexport = "reexport".equals ( av.getAttributes ().get ( "visibility" ) ); result.getBundleRequirements ().add ( new BundleRequirement ( name, vr, optional, reexport ) ); } } private void processImportPackage ( final BundleInformation result, final Attributes ma ) { for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.IMPORT_PACKAGE ) ) ) ) { final String name = av.getValue (); final String vs = av.getAttributes ().get ( "version" ); VersionRange vr = null; if ( vs != null ) { vr = new VersionRange ( vs ); } final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) ); result.getPackageImports ().add ( new PackageImport ( name, vr, optional ) ); } } private void processExportPackage ( final BundleInformation result, final Attributes ma ) { for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.EXPORT_PACKAGE ) ) ) ) { final String name = av.getValue (); final String vs = av.getAttributes ().get ( "version" ); Version v = null; if ( vs != null ) { v = new Version ( vs ); } final String uses = av.getAttributes ().get ( "uses" ); result.getPackageExports ().add ( new PackageExport ( name, v, uses ) ); } } private void processCapabilities ( final BundleInformation result, final Attributes ma ) { for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.PROVIDE_CAPABILITY ) ) ) ) { final String namespace = av.getValue (); final Map<String, CapabilityValue> values = new HashMap<> (); for ( final Map.Entry<String, String> entry : av.getAttributes ().entrySet () ) { final String keyType = entry.getKey (); final String value = entry.getValue (); final String[] key = keyType.split ( ":", 2 ); if ( key.length == 1 ) { values.put ( key[0], new CapabilityValue ( "String", value ) ); } else { values.put ( key[0], new CapabilityValue ( key[1], value ) ); } } final ProvideCapability pc = new ProvideCapability ( namespace, values ); result.getProvidedCapabilities ().add ( pc ); } for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.REQUIRE_CAPABILITY ) ) ) ) { final String namespace = av.getValue (); final String filter = av.getAttributes ().get ( "filter" ); final String effective = av.getAttributes ().get ( "effective" ); final RequireCapability rc = new RequireCapability ( namespace, filter, effective ); result.getRequiredCapabilities ().add ( rc ); } } private <T> Collection<T> emptyNull ( final Collection<T> list ) { if ( list == null ) { return Collections.emptyList (); } return list; } private void attachLocalization ( final BundleInformation result, final Attributes ma ) throws IOException { String loc = ma.getValue ( Constants.BUNDLE_LOCALIZATION ); if ( loc == null ) { loc = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } else { result.setBundleLocalization ( loc ); } result.setLocalization ( ParserHelper.loadLocalization ( this.file, loc ) ); } public static Manifest getManifest ( final ZipFile file ) throws IOException { final ZipEntry m = file.getEntry ( JarFile.MANIFEST_NAME ); if ( m == null ) { return null; } try ( InputStream is = file.getInputStream ( m ) ) { return new Manifest ( is ); } } }
epl-1.0
Orjuwan-alwadeai/mondo-hawk
plugins/org.hawk.bpmn/src/org/hawk/bpmn/BPMNAttribute.java
2373
/******************************************************************************* * Copyright (c) 2011-2015 The University of York. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Konstantinos Barmpis - initial API and implementation ******************************************************************************/ package org.hawk.bpmn; import java.util.HashSet; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.hawk.core.model.*; public class BPMNAttribute extends BPMNObject implements IHawkAttribute { private EAttribute emfattribute; public BPMNAttribute(EAttribute att) { super(att); emfattribute = att; } // public EAttribute getEmfattribute() { // return emfattribute; // } public boolean isDerived() { return emfattribute.isDerived(); } public String getName() { return emfattribute.getName(); } public HashSet<IHawkAnnotation> getAnnotations() { HashSet<IHawkAnnotation> ann = new HashSet<IHawkAnnotation>(); for (EAnnotation e : emfattribute.getEAnnotations()) { IHawkAnnotation a = new BPMNAnnotation(e); ann.add(a); } return ann; } // @Override // public EStructuralFeature getEMFattribute() { // // return emfattribute; // } @Override public boolean isMany() { return emfattribute.isMany(); } @Override public boolean isUnique() { return emfattribute.isUnique(); } @Override public boolean isOrdered() { return emfattribute.isOrdered(); } @Override public IHawkClassifier getType() { EClassifier type = emfattribute.getEType(); if (type instanceof EClass) return new BPMNClass((EClass) emfattribute.getEType()); else if (type instanceof EDataType) return new BPMNDataType((EDataType) emfattribute.getEType()); else { // System.err.println("attr: "+emfattribute.getEType()); return null; } } @Override public int hashCode() { return emfattribute.hashCode(); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.wssecurity/src/com/ibm/ws/wssecurity/cxf/interceptor/UsernameTokenInterceptor.java
14153
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.wssecurity.cxf.interceptor; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.security.auth.callback.CallbackHandler; import javax.xml.namespace.QName; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.common.classloader.ClassLoaderUtils; import org.apache.cxf.common.util.StringUtils; import org.apache.cxf.message.MessageUtils; import org.apache.cxf.ws.policy.AssertionInfo; import org.apache.cxf.ws.policy.AssertionInfoMap; import org.apache.cxf.ws.security.SecurityConstants; import org.apache.cxf.ws.security.policy.SP12Constants; import org.apache.cxf.ws.security.policy.model.UsernameToken; import org.apache.cxf.ws.security.wss4j.WSS4JTokenConverter; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSDocInfo; import org.apache.ws.security.WSPasswordCallback; import org.apache.ws.security.WSSConfig; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.WSUsernameTokenPrincipal; import org.apache.ws.security.cache.ReplayCache; import org.apache.ws.security.handler.RequestData; import org.apache.ws.security.message.WSSecUsernameToken; import org.apache.ws.security.processor.UsernameTokenProcessor; import org.apache.ws.security.validate.Validator; import org.w3c.dom.Element; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.websphere.ras.annotation.Sensitive; import com.ibm.ws.wssecurity.cxf.validator.Utils; import com.ibm.ws.wssecurity.internal.WSSecurityConstants; public class UsernameTokenInterceptor extends org.apache.cxf.ws.security.wss4j.UsernameTokenInterceptor { protected static final TraceComponent tc = Tr.register(UsernameTokenInterceptor.class, WSSecurityConstants.TR_GROUP, WSSecurityConstants.TR_RESOURCE_BUNDLE); @Override protected WSUsernameTokenPrincipal getPrincipal(@Sensitive Element tokenElement, @Sensitive final SoapMessage message) throws WSSecurityException { final ReplayCache replayCache = Utils.getReplayCache(message, SecurityConstants.ENABLE_NONCE_CACHE, SecurityConstants.NONCE_CACHE_INSTANCE); boolean bspCompliant = isWsiBSPCompliant(message); boolean utWithCallbacks = MessageUtils.getContextualBoolean(message, SecurityConstants.VALIDATE_TOKEN, true); if (utWithCallbacks) { UsernameTokenProcessor p = new UsernameTokenProcessor(); WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument()); RequestData data = new RequestData() { @Override public CallbackHandler getCallbackHandler() { return getCallback(message); } @Override public Validator getValidator(QName qName) throws WSSecurityException { Object validator = message.getContextualProperty(SecurityConstants.USERNAME_TOKEN_VALIDATOR); if (validator == null) { return super.getValidator(qName); } return (Validator) validator; } }; data.setWssConfig(WSSConfig.getNewInstance()); data.setNonceReplayCache(replayCache); data.setMsgContext(message); translateSettingsFromMsgContext(data, message); // This EMULATES CXF HTTPS behavior, but "MAY or MAY NOT be exactly CXF HTTPS behavior" List<WSSecurityEngineResult> results = p.handleToken(tokenElement, data, wsDocInfo); checkTokens(message, results); return (WSUsernameTokenPrincipal) results.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL); } else { WSUsernameTokenPrincipal principal = parseTokenAndCreatePrincipal(tokenElement, bspCompliant); WSS4JTokenConverter.convertToken(message, principal); return principal; } } private CallbackHandler getCallback(@Sensitive SoapMessage message) { //Then try to get the password from the given callback handler Object o = message.getContextualProperty(SecurityConstants.CALLBACK_HANDLER); CallbackHandler handler = null; if (o instanceof CallbackHandler) { handler = (CallbackHandler) o; } else if (o instanceof String) { try { handler = (CallbackHandler) ClassLoaderUtils .loadClass((String) o, this.getClass()).newInstance(); } catch (Exception e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Caught exception while getCallback handler :" + e); } handler = null; } } return handler; } @Override protected WSSecUsernameToken addUsernameToken(@Sensitive SoapMessage message, @Sensitive UsernameToken token) { String userName = (String) message.getContextualProperty(SecurityConstants.USERNAME); WSSConfig wssConfig = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName()); if (wssConfig == null) { wssConfig = WSSConfig.getNewInstance(); } if (!StringUtils.isEmpty(userName)) { // If NoPassword property is set we don't need to set the password if (token.isNoPassword()) { WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); utBuilder.setUserInfo(userName, null); utBuilder.setPasswordType(null); if (token.isRequireCreated() && !token.isHashPassword()) { utBuilder.addCreated(); } if (token.isRequireNonce() && !token.isHashPassword()) { utBuilder.addNonce(); } return utBuilder; } String password = (String) message.getContextualProperty(SecurityConstants.PASSWORD); if (StringUtils.isEmpty(password)) { password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN, message); } if (!StringUtils.isEmpty(password)) { //If the password is available then build the token WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig); if (token.isHashPassword()) { utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST); } else { utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT); } utBuilder.setUserInfo(userName, password); if (token.isRequireCreated() && !token.isHashPassword()) { utBuilder.addCreated(); } if (token.isRequireNonce() && !token.isHashPassword()) { utBuilder.addNonce(); } return utBuilder; } else { policyNotAsserted(token, "No username available", message); } } else { policyNotAsserted(token, "No username available", message); } return null; } /** * All UsernameTokens must conform to the policy */ public boolean checkTokens(@Sensitive SoapMessage message, List<WSSecurityEngineResult> utResults) throws WSSecurityException { AssertionInfoMap aim = message.get(AssertionInfoMap.class); Collection<AssertionInfo> ais = aim.getAssertionInfo(SP12Constants.USERNAME_TOKEN); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "ais in checkTokens is '" + ais + "'"); } UsernameToken usernameTokenPolicy = null; //for (AssertionInfo ai : ais) { // TBD // tok = (UsernameToken) ai.getAssertion(); // //} Object[] aiArray = ais.toArray(); AssertionInfo ai = null; if (aiArray.length > 0) { ai = (AssertionInfo) aiArray[0]; usernameTokenPolicy = (UsernameToken) ai.getAssertion(); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "ai in checkTokens is '" + ai + "'"); Tr.debug(tc, "usernameTokenPolicy is '" + usernameTokenPolicy + "'"); } boolean bOk = true; Set<String> msgs = new LinkedHashSet<String>(); for (WSSecurityEngineResult result : utResults) { org.apache.ws.security.message.token.UsernameToken usernameToken = (org.apache.ws.security.message.token.UsernameToken) result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "usernameToken is '" + usernameToken + "'"); } if (usernameTokenPolicy.isHashPassword() != usernameToken.isHashed()) { String strErr = "Password hashing policy not enforced"; //ai.setNotAsserted(strErr); msgs.add(strErr); bOk = false; } if (usernameTokenPolicy.isNoPassword() && usernameToken.getPassword() != null) { String strErr = "Username Token NoPassword policy not enforced"; //ai.setNotAsserted(strErr); msgs.add(strErr); bOk = false; } if (usernameTokenPolicy.isRequireCreated() && (usernameToken.getCreated() == null || usernameToken.isHashed())) { String strErr = "Username Token Created policy not enforced"; //ai.setNotAsserted(strErr); msgs.add(strErr); bOk = false; } if (usernameTokenPolicy.isRequireNonce() && (usernameToken.getNonce() == null || usernameToken.isHashed())) { String strErr = "Username Token Nonce policy not enforced"; //ai.setNotAsserted(strErr); msgs.add(strErr); bOk = false; } } if (!bOk) { throw new WSSecurityException(msgs.toString()); } return true; } void translateSettingsFromMsgContext(RequestData reqData, @Sensitive SoapMessage message) { // This emulates the code from doReceiverAction() in org.apache.ws.security.WSHandler WSSConfig wssConfig = reqData.getWssConfig(); if (wssConfig == null) { wssConfig = WSSConfig.getNewInstance(); } //boolean enableSigConf = decodeEnableSignatureConfirmation(reqData); //wssConfig.setEnableSignatureConfirmation( // enableSigConf || ((doAction & WSConstants.SC) != 0) //); //wssConfig.setTimeStampStrict(decodeTimestampStrict(reqData)); //if (decodePasswordTypeStrict(reqData)) { // String passwordType = decodePasswordType(reqData); // wssConfig.setRequiredPasswordType(passwordType); //} // wssConfig.setTimeStampTTL(decodeTimeToLive(reqData, message)); wssConfig.setUtTTL(decodeTimeToLive(reqData, message)); // wssConfig.setTimeStampFutureTTL(decodeFutureTimeToLive(reqData, message)); wssConfig.setUtFutureTTL(decodeFutureTimeToLive(reqData, message)); //wssConfig.setHandleCustomPasswordTypes(decodeCustomPasswordTypes(reqData)); //wssConfig.setPasswordsAreEncoded(decodeUseEncodedPasswords(reqData)); reqData.setWssConfig(wssConfig); } public int decodeTimeToLive(RequestData reqData, @Sensitive SoapMessage message) { String ttl = (String) message.getContextualProperty(SecurityConstants.TIMESTAMP_TTL); //System.out.println("gkuo:ttl string in decode is:" + ttl); int ttlI = 0; if (ttl != null) { try { ttlI = Integer.parseInt(ttl); } catch (NumberFormatException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "ttl string is malformat '" + ttl + "'" + e.getMessage()); } ttlI = reqData.getTimeToLive(); } } if (ttlI <= 0) { ttlI = reqData.getTimeToLive(); } return ttlI; } protected int decodeFutureTimeToLive(RequestData reqData, @Sensitive SoapMessage message) { String ttl = (String) message.getContextualProperty(SecurityConstants.TIMESTAMP_FUTURE_TTL); //System.out.println("gkuo:ttl string in decode is:" + ttl); int defaultFutureTimeToLive = 60; if (ttl != null) { try { int ttlI = Integer.parseInt(ttl); if (ttlI < 0) { return defaultFutureTimeToLive; } return ttlI; } catch (NumberFormatException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "future ttl string is malformat '" + ttl + "'" + e.getMessage()); } return defaultFutureTimeToLive; } } return defaultFutureTimeToLive; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/processor/MPLockedMessageEnumeration.java
3747
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.sib.processor; import com.ibm.websphere.sib.exception.SIIncorrectCallException; import com.ibm.websphere.sib.exception.SIResourceException; import com.ibm.wsspi.sib.core.LockedMessageEnumeration; import com.ibm.wsspi.sib.core.SIBusMessage; import com.ibm.wsspi.sib.core.exception.SIConnectionDroppedException; import com.ibm.wsspi.sib.core.exception.SIConnectionLostException; import com.ibm.wsspi.sib.core.exception.SIConnectionUnavailableException; import com.ibm.wsspi.sib.core.exception.SIMessageNotLockedException; import com.ibm.wsspi.sib.core.exception.SISessionDroppedException; import com.ibm.wsspi.sib.core.exception.SISessionUnavailableException; /** * @author gatfora * * Extensions to the LockedMessageEnumeration class */ public interface MPLockedMessageEnumeration extends LockedMessageEnumeration { /** Unlocks the message currently pointed to by the LockedMessageEnumeration's cursor, making it available for redelivery to the same or other consumers. <p> It should be noted that any invocation of unlockCurrent can cause messages to be delivered out of sequence (just as with a transaction rollback). When a message is unlocked, its redeliveryCount is incremented only if the redeliveryCountUnchanged flag is set to false. <p> SIMessageNotLockedException is thrown if the current item is not locked, for example before the first call, to {@link #nextLocked}, or if it has been removed already with {@link #deleteCurrent}. @param redeliveryCountUnchanged A value of false will maintain the original unlockCurrent behaviour. A value of true will not increment the redelivery count. @throws com.ibm.wsspi.sib.core.exception.SISessionUnavailableException @throws com.ibm.wsspi.sib.core.exception.SISessionDroppedException @throws com.ibm.wsspi.sib.core.exception.SIConnectionUnavailableException @throws com.ibm.wsspi.sib.core.exception.SIConnectionDroppedException @throws com.ibm.websphere.sib.exception.SIResourceException @throws com.ibm.wsspi.sib.core.exception.SIConnectionLostException @throws com.ibm.websphere.sib.exception.SIIncorrectCallException @throws com.ibm.websphere.sib.exception.SIMessageNotLockedException */ public void unlockCurrent(boolean redeliveryCountUnchanged) throws SISessionUnavailableException, SISessionDroppedException, SIConnectionUnavailableException, SIConnectionDroppedException, SIResourceException, SIConnectionLostException, SIIncorrectCallException, SIMessageNotLockedException; /** * Enables the user of the call to see the next message in the enumeration without * moving the cursor to the messages position. This means that calls to deleteCurrent * deleteSeen will not remove the *peeked* at message. * * Null will be returned if there is no next message. * * @return * @throws SISessionUnavailableException * @throws SIResourceException * @throws SIIncorrectCallException */ public SIBusMessage peek() throws SISessionUnavailableException, SIResourceException, SIIncorrectCallException; }
epl-1.0
jcryptool/crypto
org.jcryptool.visual.zeroknowledge/src/org/jcryptool/visual/zeroknowledge/ui/PrimeGenerator.java
7368
// -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2021 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.visual.zeroknowledge.ui; import java.math.BigInteger; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.jcryptool.visual.zeroknowledge.ModNCalculator; /** * Graphische Benutzeroberfläche zur Erstellung der Primzahlen p und q. Man kann p und q direkt * eingeben oder vom Programm generieren lassen. * * @author Mareike Paul * @version 1.0.0 */ public class PrimeGenerator { private PrimeGenerator object; private Label error; private Button gen; private Group group; private Text pPrime; private Text qPrime; private Text textN; /** * Konstruktor für die Group, die für die Erstellung von zwei Primzahlen zuständig ist * * @param shamir Objekt, das das Modell zu dieser View enthält * @param parent Parent zu der graphische n Oberfläche */ public PrimeGenerator(final ModNCalculator shamir, Composite parent) { object = this; group = new Group(parent, SWT.NONE); group.setText(Messages.PrimeGenerator_0); group.setLayout(new GridLayout(3, false)); group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); group.setVisible(true); // Eingabefeld für die Primzahl p Label labelP = new Label(group, SWT.NONE); labelP.setText(Messages.PrimeGenerator_1); labelP.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); pPrime = new Text(group, SWT.BORDER); pPrime.setTextLimit(10); pPrime.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); pPrime.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { // Reset the plugin if the user changes a prime. shamir.resetNotSecret(); // Test if input is a number, a prime and positive. try { BigInteger input = new BigInteger(pPrime.getText()); if (input.isProbablePrime(100)) { if (input.compareTo(BigInteger.ZERO) == 1) { shamir.setP(input); removeException(); return; } else { setException(Messages.PrimeGeneratorListener_7); } } else { setException(Messages.PrimeGeneratorListener_5); } } catch (NumberFormatException ex) { setException(Messages.PrimeGeneratorListener_3); } // If the user entered shit set N to "-" textN.setText("-"); shamir.setP(BigInteger.ZERO); } }); // Button zum Generieren der Parameter gen = new Button(group, SWT.PUSH); gen.setText(Messages.PrimeGenerator_2); gen.addSelectionListener( /** * Selection-Listener, der auf Events vom "Generieren"-Button achtet */ new SelectionAdapter() { /** * öffnet einen Dialog zum Generieren der Primzahlen p und q */ @Override public void widgetSelected(SelectionEvent arg0) { new Generator(object, shamir, group.getShell()); } }); gen.setToolTipText(Messages.PrimeGenerator_3); gen.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); // Eingabefeld fuer die Primzahl q Label labelQ = new Label(group, SWT.NONE); labelQ.setText(Messages.PrimeGenerator_4); labelQ.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); qPrime = new Text(group, SWT.BORDER); qPrime.setTextLimit(10); qPrime.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); qPrime.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { // Reset the plugin if the user changes a prime. shamir.resetNotSecret(); // Test if input is a number, a prime and positive. try { BigInteger input = new BigInteger(qPrime.getText()); if (input.isProbablePrime(100)) { if (input.compareTo(BigInteger.ZERO) == 1) { shamir.setQ(input); removeException(); return; } else { setException(Messages.PrimeGeneratorListener_8); } } else { setException(Messages.PrimeGeneratorListener_6); } } catch (NumberFormatException ex) { setException(Messages.PrimeGeneratorListener_4); } // If the user entered shit set N to "-" textN.setText("-"); shamir.setQ(BigInteger.ZERO); } }); // Label zum Anzeigen von Fehlern error = new Label(group, SWT.NONE); error.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_RED)); error.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); error.setVisible(false); Label labelN = new Label(group, SWT.NONE); labelN.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); labelN.setText("n :"); textN = new Text(group, SWT.BORDER); textN.setEditable(false); textN.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); textN.setText("-"); // Dummy Label for Layout new Label(group, SWT.NONE); } /** * Methode zum Erhalten des Group-Objektes, das die graphischen Komponenten enthält * * @return Group-Objekt einer Instanz dieser Klasse */ public Group getGroup() { return group; } /** * Methode zum Erhalten des formatierten Textfeldes, das die Primzahl p enthält * * @return das formatierte Textfeld, das die Primzahl p enthält */ public Text getP() { return pPrime; } /** * Methode zum Erhalten des formatierten Textfeldes, das die Primzahl q enthält * * @return das formatierte Textfeld, das die Primzahl q enthält */ public Text getQ() { return qPrime; } /** * "löscht" die Nachricht */ public void removeException() { error.setVisible(false); } /** * Zeigt eine Nachricht an, tendenziell eine Fehlermeldung bei falscher Benutzereingabe * * @param message */ public void setException(String message) { error.setText(message); error.setVisible(true); } public void setN(String n) { textN.setText(n); } public void setP(String p) { pPrime.setText(p); } public void setQ(String q) { qPrime.setText(q); } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.netatmo/src/test/java/org/openhab/binding/netatmo/internal/presence/NAPresenceCameraHandlerTest.java
22589
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.netatmo.internal.presence; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.Optional; import org.eclipse.jdt.annotation.NonNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.openhab.binding.netatmo.internal.NetatmoBindingConstants; import org.openhab.core.i18n.TimeZoneProvider; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.StringType; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.internal.ThingImpl; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; import io.swagger.client.model.NAWelcomeCamera; /** * @author Sven Strohschein - Initial contribution */ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.WARN) public class NAPresenceCameraHandlerTest { private static final String DUMMY_VPN_URL = "https://dummytestvpnaddress.net/restricted/10.255.89.96/9826069dc689e8327ac3ed2ced4ff089/MTU5MTgzMzYwMDrQ7eHHhG0_OJ4TgmPhGlnK7QQ5pZ,,"; private static final String DUMMY_LOCAL_URL = "http://192.168.178.76/9826069dc689e8327ac3ed2ced4ff089"; private static final Optional<String> DUMMY_PING_RESPONSE = createPingResponseContent(DUMMY_LOCAL_URL); private @Mock RequestExecutor requestExecutorMock; private @Mock TimeZoneProvider timeZoneProviderMock; private Thing presenceCameraThing; private NAWelcomeCamera presenceCamera; private ChannelUID cameraStatusChannelUID; private ChannelUID floodlightChannelUID; private ChannelUID floodlightAutoModeChannelUID; private NAPresenceCameraHandlerAccessible handler; @BeforeEach public void before() { presenceCameraThing = new ThingImpl(new ThingTypeUID("netatmo", "NOC"), "1"); presenceCamera = new NAWelcomeCamera(); cameraStatusChannelUID = new ChannelUID(presenceCameraThing.getUID(), NetatmoBindingConstants.CHANNEL_CAMERA_STATUS); floodlightChannelUID = new ChannelUID(presenceCameraThing.getUID(), NetatmoBindingConstants.CHANNEL_CAMERA_FLOODLIGHT); floodlightAutoModeChannelUID = new ChannelUID(presenceCameraThing.getUID(), NetatmoBindingConstants.CHANNEL_CAMERA_FLOODLIGHT_AUTO_MODE); handler = new NAPresenceCameraHandlerAccessible(presenceCameraThing, presenceCamera); } @Test public void testHandleCommandSwitchSurveillanceOn() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(cameraStatusChannelUID, OnOffType.ON); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch on verify(requestExecutorMock).executeGETRequest(DUMMY_LOCAL_URL + "/command/changestatus?status=on"); } @Test public void testHandleCommandSwitchSurveillanceOff() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(cameraStatusChannelUID, OnOffType.OFF); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch off verify(requestExecutorMock).executeGETRequest(DUMMY_LOCAL_URL + "/command/changestatus?status=off"); } @Test public void testHandleCommandSwitchSurveillanceUnknownCommand() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(cameraStatusChannelUID, RefreshType.REFRESH); verify(requestExecutorMock, never()).executeGETRequest(any()); // nothing should get executed on a refresh // command } @Test public void testHandleCommandSwitchSurveillanceWithoutVPN() { handler.handleCommand(cameraStatusChannelUID, OnOffType.ON); verify(requestExecutorMock, never()).executeGETRequest(any()); // nothing should get executed when no VPN // address is set } @Test public void testHandleCommandSwitchFloodlightOn() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch on verify(requestExecutorMock) .executeGETRequest(DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22on%22%7D"); } @Test public void testHandleCommandSwitchFloodlightOff() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.OFF); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch off verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22off%22%7D"); } @Test public void testHandleCommandSwitchFloodlightOffWithAutoModeOn() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.AUTO); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); handler.handleCommand(floodlightChannelUID, OnOffType.OFF); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch off verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22auto%22%7D"); } @Test public void testHandleCommandSwitchFloodlightOnAddressChanged() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); // 1.) execute ping + 2.) execute switch on verify(requestExecutorMock, times(2)).executeGETRequest(any()); verify(requestExecutorMock) .executeGETRequest(DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22on%22%7D"); handler.handleCommand(floodlightChannelUID, OnOffType.OFF); // 1.) execute ping + 2.) execute switch on + 3.) execute switch off verify(requestExecutorMock, times(3)).executeGETRequest(any()); verify(requestExecutorMock) .executeGETRequest(DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22on%22%7D"); verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22off%22%7D"); final String newDummyVPNURL = DUMMY_VPN_URL + "2"; final String newDummyLocalURL = DUMMY_LOCAL_URL + "2"; final Optional<String> newDummyPingResponse = createPingResponseContent(newDummyLocalURL); when(requestExecutorMock.executeGETRequest(newDummyVPNURL + "/command/ping")).thenReturn(newDummyPingResponse); presenceCamera.setVpnUrl(newDummyVPNURL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); // 1.) execute ping + 2.) execute switch on + 3.) execute switch off + 4.) execute ping + 5.) execute switch on verify(requestExecutorMock, times(5)).executeGETRequest(any()); verify(requestExecutorMock) .executeGETRequest(DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22on%22%7D"); verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22off%22%7D"); verify(requestExecutorMock).executeGETRequest( newDummyLocalURL + "/command/floodlight_set_config?config=%7B%22mode%22:%22on%22%7D"); } @Test public void testHandleCommandSwitchFloodlightUnknownCommand() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, RefreshType.REFRESH); verify(requestExecutorMock, never()).executeGETRequest(any()); // nothing should get executed on a refresh // command } @Test public void testHandleCommandSwitchFloodlightAutoModeOn() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightAutoModeChannelUID, OnOffType.ON); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch // auto-mode on verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22auto%22%7D"); } @Test public void testHandleCommandSwitchFloodlightAutoModeOff() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(DUMMY_PING_RESPONSE); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightAutoModeChannelUID, OnOffType.OFF); verify(requestExecutorMock, times(2)).executeGETRequest(any()); // 1.) execute ping + 2.) execute switch off verify(requestExecutorMock).executeGETRequest( DUMMY_LOCAL_URL + "/command/floodlight_set_config?config=%7B%22mode%22:%22off%22%7D"); } @Test public void testHandleCommandSwitchFloodlightAutoModeUnknownCommand() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightAutoModeChannelUID, RefreshType.REFRESH); verify(requestExecutorMock, never()).executeGETRequest(any()); // nothing should get executed on a refresh // command } /** * The request "fails" because there is no response content of the ping command. */ @Test public void testHandleCommandRequestFailed() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, times(1)).executeGETRequest(any()); // 1.) execute ping } @Test public void testHandleCommandWithoutVPN() { handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, never()).executeGETRequest(any()); // no executions because the VPN URL is still // unknown } @Test public void testHandleCommandPingFailedNULLResponse() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(Optional.of("")); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, times(1)).executeGETRequest(any()); // 1.) execute ping } @Test public void testHandleCommandPingFailedEmptyResponse() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")).thenReturn(Optional.of("")); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, times(1)).executeGETRequest(any()); // 1.) execute ping } @Test public void testHandleCommandPingFailedWrongResponse() { when(requestExecutorMock.executeGETRequest(DUMMY_VPN_URL + "/command/ping")) .thenReturn(Optional.of("{ \"message\": \"error\" }")); presenceCamera.setVpnUrl(DUMMY_VPN_URL); handler.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, times(1)).executeGETRequest(any()); // 1.) execute ping } @Test public void testHandleCommandModuleNULL() { NAPresenceCameraHandler handlerWithoutModule = new NAPresenceCameraHandler(presenceCameraThing, timeZoneProviderMock); handlerWithoutModule.handleCommand(floodlightChannelUID, OnOffType.ON); verify(requestExecutorMock, never()).executeGETRequest(any()); // no executions because the thing isn't // initialized } @Test public void testGetNAThingPropertyCommonChannel() { assertEquals(OnOffType.OFF, handler.getNAThingProperty(NetatmoBindingConstants.CHANNEL_CAMERA_STATUS)); } @Test public void testGetNAThingPropertyFloodlightOn() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.ON); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightOff() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.OFF); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightAuto() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.AUTO); // When the floodlight is set to auto-mode it is currently off. assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightWithoutLightModeState() { assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightModuleNULL() { NAPresenceCameraHandler handlerWithoutModule = new NAPresenceCameraHandler(presenceCameraThing, timeZoneProviderMock); assertEquals(UnDefType.UNDEF, handlerWithoutModule.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightAutoModeFloodlightAuto() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.AUTO); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightAutoModeFloodlightOn() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.ON); // When the floodlight is initially on (on starting the binding), there is no information about if the auto-mode // was set before. Therefore the auto-mode is detected as deactivated / off. assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightAutoModeFloodlightOff() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.ON); // When the floodlight is initially off (on starting the binding), the auto-mode isn't set. assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightScenarioWithAutoMode() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.AUTO); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); // The auto-mode was initially set, after that the floodlight was switched on by the user. // In this case the binding should still know that the auto-mode is/was set. presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.ON); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightChannelUID.getId())); // After that the user switched off the floodlight. // In this case the binding should still know that the auto-mode is/was set. presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.OFF); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightScenarioWithoutAutoMode() { presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.OFF); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); // The auto-mode wasn't set, after that the floodlight was switched on by the user. // In this case the binding should still know that the auto-mode isn't/wasn't set. presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.ON); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.ON, handler.getNAThingProperty(floodlightChannelUID.getId())); // After that the user switched off the floodlight. // In this case the binding should still know that the auto-mode isn't/wasn't set. presenceCamera.setLightModeStatus(NAWelcomeCamera.LightModeStatusEnum.OFF); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightAutoModeChannelUID.getId())); assertEquals(OnOffType.OFF, handler.getNAThingProperty(floodlightChannelUID.getId())); } @Test public void testGetNAThingPropertyFloodlightAutoModeModuleNULL() { NAPresenceCameraHandler handlerWithoutModule = new NAPresenceCameraHandler(presenceCameraThing, timeZoneProviderMock); assertEquals(UnDefType.UNDEF, handlerWithoutModule.getNAThingProperty(floodlightAutoModeChannelUID.getId())); } @Test public void testGetStreamURL() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); Optional<String> streamURL = handler.getStreamURL("dummyVideoId"); assertTrue(streamURL.isPresent()); assertEquals(DUMMY_VPN_URL + "/vod/dummyVideoId/index.m3u8", streamURL.get()); } @Test public void testGetStreamURLLocal() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); presenceCamera.setIsLocal(true); Optional<String> streamURL = handler.getStreamURL("dummyVideoId"); assertTrue(streamURL.isPresent()); assertEquals(DUMMY_VPN_URL + "/vod/dummyVideoId/index_local.m3u8", streamURL.get()); } @Test public void testGetStreamURLNotLocal() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); presenceCamera.setIsLocal(false); Optional<String> streamURL = handler.getStreamURL("dummyVideoId"); assertTrue(streamURL.isPresent()); assertEquals(DUMMY_VPN_URL + "/vod/dummyVideoId/index.m3u8", streamURL.get()); } @Test public void testGetStreamURLWithoutVPN() { Optional<String> streamURL = handler.getStreamURL("dummyVideoId"); assertFalse(streamURL.isPresent()); } @Test public void testGetLivePictureURLState() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); State livePictureURLState = handler.getLivePictureURLState(); assertEquals(new StringType(DUMMY_VPN_URL + "/live/snapshot_720.jpg"), livePictureURLState); } @Test public void testGetLivePictureURLStateWithoutVPN() { State livePictureURLState = handler.getLivePictureURLState(); assertEquals(UnDefType.UNDEF, livePictureURLState); } @Test public void testGetLiveStreamState() { presenceCamera.setVpnUrl(DUMMY_VPN_URL); State liveStreamState = handler.getLiveStreamState(); assertEquals(new StringType(DUMMY_VPN_URL + "/live/index.m3u8"), liveStreamState); } @Test public void testGetLiveStreamStateWithoutVPN() { State liveStreamState = handler.getLiveStreamState(); assertEquals(UnDefType.UNDEF, liveStreamState); } private static Optional<String> createPingResponseContent(final String localURL) { return Optional.of("{\"local_url\":\"" + localURL + "\",\"product_name\":\"Welcome Netatmo\"}"); } private interface RequestExecutor { Optional<String> executeGETRequest(String url); } private class NAPresenceCameraHandlerAccessible extends NAPresenceCameraHandler { private NAPresenceCameraHandlerAccessible(Thing thing, NAWelcomeCamera presenceCamera) { super(thing, timeZoneProviderMock); setModule(presenceCamera); } @Override protected @NonNull Optional<@NonNull String> executeGETRequest(@NonNull String url) { return requestExecutorMock.executeGETRequest(url); } @Override protected @NonNull State getLivePictureURLState() { return super.getLivePictureURLState(); } @Override protected @NonNull State getLiveStreamState() { return super.getLiveStreamState(); } } }
epl-1.0
sguan-actuate/birt
data/org.eclipse.birt.data.tests/test/org/eclipse/birt/data/engine/regre/db/ConnectionTest.java
2589
/******************************************************************************* * Copyright (c) 2004,2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.regre.db; import org.eclipse.birt.data.engine.api.APITestCase; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import testutil.ConfigText; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ abstract public class ConnectionTest extends APITestCase { /* * @see junit.framework.TestCase#setUp() */ @Before public void connectionSetUp() throws Exception { System.setProperty( "DTETest.otherDB", "true" ); } /* * (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ @After public void connectionTearDown() throws Exception { System.setProperty( "DTETest.otherDB","false"); } /* * @see org.eclipse.birt.data.engine.api.APITestCase#getDataSourceInfo() */ protected DataSourceInfo getDataSourceInfo( ) { return new DataSourceInfo( ConfigText.getString( "Regre.ConnectTest.TableName" ), null, null ); } /* * An Empyt ReportQueryDefn */ @Test public void testConnection( ) throws Exception { IBaseExpression[] expressions = new IBaseExpression[]{ new ScriptExpression( "dataSetRow.CLIENTID", 0 ), new ScriptExpression( "dataSetRow.CITY", 0 ), new ScriptExpression( "dataSetRow.COUNTRY", 0 ), new ScriptExpression( "dataSetRow.EMAIL", 0 ) }; createAndRunQuery( expressions ); } private void createAndRunQuery( IBaseExpression[] expressions ) throws Exception { String[] names = new String[]{ "_CLIENTID", "_CITY", "_COUNTRY", "_EMAIL" }; QueryDefinition queryDefn = newReportQuery( ); if ( expressions != null ) for ( int i = 0; i < expressions.length; i++ ) queryDefn.addResultSetExpression( names[i], expressions[i] ); outputQueryResult( executeQuery( queryDefn ), names ); } }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/compiler/UILeaf.java
20781
/* * 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.myfaces.view.facelets.compiler; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.component.ContextCallback; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.UniqueIdVendor; import javax.faces.component.visit.VisitCallback; import javax.faces.component.visit.VisitContext; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import javax.faces.event.AbortProcessingException; import javax.faces.event.ComponentSystemEvent; import javax.faces.event.FacesEvent; import javax.faces.event.FacesListener; import javax.faces.render.Renderer; import javax.faces.view.Location; import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.myfaces.view.facelets.tag.jsf.ComponentSupport; import com.ibm.websphere.ras.annotation.Trivial; @Trivial class UILeaf extends UIComponent implements Map<String, Object> { //-------------- START TAKEN FROM UIComponentBase ---------------- private static final String _STRING_BUILDER_KEY = "javax.faces.component.UIComponentBase.SHARED_STRING_BUILDER"; private String _clientId = null; private String _id = null; public String getClientId(FacesContext context) { if (context == null) { throw new NullPointerException("context"); } if (_clientId != null) { return _clientId; } //boolean idWasNull = false; String id = getId(); if (id == null) { // Although this is an error prone side effect, we automatically create a new id // just to be compatible to the RI // The documentation of UniqueIdVendor says that this interface should be implemented by // components that also implements NamingContainer. The only component that does not implement // NamingContainer but UniqueIdVendor is UIViewRoot. Anyway we just can't be 100% sure about this // fact, so it is better to scan for the closest UniqueIdVendor. If it is not found use // viewRoot.createUniqueId, otherwise use UniqueIdVendor.createUniqueId(context,seed). UniqueIdVendor parentUniqueIdVendor = _ComponentUtils.findParentUniqueIdVendor(this); if (parentUniqueIdVendor == null) { UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot != null) { id = viewRoot.createUniqueId(); } else { // The RI throws a NPE String location = getComponentLocation(this); throw new FacesException("Cannot create clientId. No id is assigned for component" + " to create an id and UIViewRoot is not defined: " + getPathToComponent(this) + (location != null ? " created from: " + location : "")); } } else { id = parentUniqueIdVendor.createUniqueId(context, null); } setId(id); // We remember that the id was null and log a warning down below // idWasNull = true; } UIComponent namingContainer = _ComponentUtils.findParentNamingContainer(this, false); if (namingContainer != null) { String containerClientId = namingContainer.getContainerClientId(context); if (containerClientId != null) { StringBuilder bld = _getSharedStringBuilder(context); _clientId = bld.append(containerClientId).append( context.getNamingContainerSeparatorChar()).append(id).toString(); } else { _clientId = id; } } else { _clientId = id; } Renderer renderer = getRenderer(context); if (renderer != null) { _clientId = renderer.convertClientId(context, _clientId); } // -=Leonardo Uribe=- In jsf 1.1 and 1.2 this warning has sense, but in jsf 2.0 it is common to have // components without any explicit id (UIViewParameter components and UIOuput resource components) instances. // So, this warning is becoming obsolete in this new context and should be removed. //if (idWasNull && log.isLoggable(Level.WARNING)) //{ // log.warning("WARNING: Component " + _clientId // + " just got an automatic id, because there was no id assigned yet. " // + "If this component was created dynamically (i.e. not by a JSP tag) you should assign it an " // + "explicit static id or assign it the id you get from " // + "the createUniqueId from the current UIViewRoot " // + "component right after creation! Path to Component: " + getPathToComponent(this)); //} return _clientId; } public String getId() { return _id; } @Override public void setId(String id) { // UILeaf instance are just a wrapper for html markup. It never has // an user defined id. The validation check here is just useless, // because facelets algorithm ensures that. //isIdValid(id); _id = id; _clientId = null; } /* private void isIdValid(String string) { // is there any component identifier ? if (string == null) { return; } // Component identifiers must obey the following syntax restrictions: // 1. Must not be a zero-length String. if (string.length() == 0) { throw new IllegalArgumentException("component identifier must not be a zero-length String"); } // If new id is the same as old it must be valid if (string.equals(_id)) { return; } // 2. First character must be a letter or an underscore ('_'). if (!Character.isLetter(string.charAt(0)) && string.charAt(0) != '_') { throw new IllegalArgumentException("component identifier's first character must be a letter " + "or an underscore ('_')! But it is \"" + string.charAt(0) + "\""); } for (int i = 1; i < string.length(); i++) { char c = string.charAt(i); // 3. Subsequent characters must be a letter, a digit, an underscore ('_'), or a dash ('-'). if (!Character.isLetterOrDigit(c) && c != '-' && c != '_') { throw new IllegalArgumentException("Subsequent characters of component identifier must be a letter, " + "a digit, an underscore ('_'), or a dash ('-')! " + "But component identifier contains \"" + c + "\""); } } }*/ private String getComponentLocation(UIComponent component) { Location location = (Location) component.getAttributes() .get(UIComponent.VIEW_LOCATION_KEY); if (location != null) { return location.toString(); } return null; } private String getPathToComponent(UIComponent component) { StringBuffer buf = new StringBuffer(); if (component == null) { buf.append("{Component-Path : "); buf.append("[null]}"); return buf.toString(); } getPathToComponent(component, buf); buf.insert(0, "{Component-Path : "); buf.append("}"); return buf.toString(); } private void getPathToComponent(UIComponent component, StringBuffer buf) { if (component == null) { return; } StringBuffer intBuf = new StringBuffer(); intBuf.append("[Class: "); intBuf.append(component.getClass().getName()); if (component instanceof UIViewRoot) { intBuf.append(",ViewId: "); intBuf.append(((UIViewRoot) component).getViewId()); } else { intBuf.append(",Id: "); intBuf.append(component.getId()); } intBuf.append("]"); buf.insert(0, intBuf.toString()); getPathToComponent(component.getParent(), buf); } static StringBuilder _getSharedStringBuilder(FacesContext facesContext) { Map<Object, Object> attributes = facesContext.getAttributes(); StringBuilder sb = (StringBuilder) attributes.get(_STRING_BUILDER_KEY); if (sb == null) { sb = new StringBuilder(); attributes.put(_STRING_BUILDER_KEY, sb); } else { // clear out the stringBuilder by setting the length to 0 sb.setLength(0); } return sb; } //-------------- END TAKEN FROM UICOMPONENTBASE ------------------ private static Map<String, UIComponent> facets = new HashMap<String, UIComponent>() { @Override public void putAll(Map<? extends String, ? extends UIComponent> map) { // do nothing } @Override public UIComponent put(String name, UIComponent value) { return null; } }; private UIComponent parent; //private _ComponentAttributesMap attributesMap; @Override public Map<String, Object> getAttributes() { // Since all components extending UILeaf are only transient references // to text or instructions, we can do the following simplifications: // 1. Don't use reflection to retrieve properties, because it will never // be done // 2. Since the only key that will be saved here is MARK_ID, we can create // a small map of size 2. In practice, this will prevent create a lot of // maps, like the ones used on state helper return this; } @Override public void clearInitialState() { //this component is transient, so it can be marked, because it does not have state! } @Override public boolean initialStateMarked() { //this component is transient, so it can be marked, because it does not have state! return false; } @Override public void markInitialState() { //this component is transient, so no need to do anything } @Override public void processEvent(ComponentSystemEvent event) throws AbortProcessingException { //Do nothing, because UILeaf will not need to handle "binding" property } @Override @SuppressWarnings("deprecation") public ValueBinding getValueBinding(String binding) { return null; } @Override @SuppressWarnings("deprecation") public void setValueBinding(String name, ValueBinding binding) { // do nothing } @Override public ValueExpression getValueExpression(String name) { return null; } @Override public void setValueExpression(String name, ValueExpression arg1) { // do nothing } public String getFamily() { return "facelets.LiteralText"; } @Override public UIComponent getParent() { return this.parent; } @Override public void setParent(UIComponent parent) { this.parent = parent; } @Override public boolean isRendered() { return true; } @Override public void setRendered(boolean rendered) { // do nothing } @Override public String getRendererType() { return null; } @Override public void setRendererType(String rendererType) { // do nothing } @Override public boolean getRendersChildren() { return true; } @Override public List<UIComponent> getChildren() { List<UIComponent> children = Collections.emptyList(); return children; } @Override public int getChildCount() { return 0; } @Override public UIComponent findComponent(String id) { return null; } @Override public Map<String, UIComponent> getFacets() { return facets; } @Override public int getFacetCount() { return 0; } @Override public UIComponent getFacet(String name) { return null; } @SuppressWarnings("unchecked") @Override public Iterator<UIComponent> getFacetsAndChildren() { // Performance: Collections.emptyList() is Singleton, // but .iterator() creates new instance of AbstractList$Itr every invocation, because // emptyList() extends AbstractList. Therefore we cannot use Collections.emptyList() here. return EmptyIterator.INSTANCE; } @Override public void broadcast(FacesEvent event) throws AbortProcessingException { // do nothing } @Override public void decode(FacesContext faces) { // do nothing } @Override public void encodeBegin(FacesContext faces) throws IOException { // do nothing } @Override public void encodeChildren(FacesContext faces) throws IOException { // do nothing } @Override public void encodeEnd(FacesContext faces) throws IOException { // do nothing } @Override public void encodeAll(FacesContext faces) throws IOException { this.encodeBegin(faces); } @Override protected void addFacesListener(FacesListener faces) { // do nothing } @Override protected FacesListener[] getFacesListeners(Class faces) { return null; } @Override protected void removeFacesListener(FacesListener faces) { // do nothing } @Override public void queueEvent(FacesEvent event) { // do nothing } @Override public void processRestoreState(FacesContext faces, Object state) { // do nothing } @Override public void processDecodes(FacesContext faces) { // do nothing } @Override public void processValidators(FacesContext faces) { // do nothing } @Override public void processUpdates(FacesContext faces) { // do nothing } @Override public Object processSaveState(FacesContext faces) { return null; } @Override protected FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } @Override protected Renderer getRenderer(FacesContext faces) { return null; } public Object saveState(FacesContext faces) { return null; } public void restoreState(FacesContext faces, Object state) { // do nothing } public boolean isTransient() { return true; } public void setTransient(boolean tranzient) { // do nothing } @Override public boolean invokeOnComponent(FacesContext context, String clientId, ContextCallback callback) throws FacesException { //this component will never be a target for a callback, so always return false. return false; } @Override public boolean visitTree(VisitContext context, VisitCallback callback) { // the visiting is complete and it shouldn't affect the visiting of the other // children of the parent component, therefore return false return false; } //-------------- START ATTRIBUTE MAP IMPLEMENTATION ---------------- private Map<String, Object> _attributes = null; private String _markCreated = null; public void setMarkCreated(String markCreated) { _markCreated = markCreated; } public int size() { return _attributes == null ? 0 : _attributes.size(); } public void clear() { if (_attributes != null) { _attributes.clear(); _markCreated = null; } } public boolean isEmpty() { if (_markCreated == null) { return _attributes == null ? false : _attributes.isEmpty(); } else { return false; } } public boolean containsKey(Object key) { checkKey(key); if (ComponentSupport.MARK_CREATED.equals(key)) { return _markCreated != null; } else { return (_attributes == null ? false :_attributes.containsKey(key)); } } public boolean containsValue(Object value) { if (_markCreated != null && _markCreated.equals(value)) { return true; } return (_attributes == null) ? false : _attributes.containsValue(value); } public Collection<Object> values() { return getUnderlyingMap().values(); } public void putAll(Map<? extends String, ? extends Object> t) { for (Map.Entry<? extends String, ? extends Object> entry : t.entrySet()) { put(entry.getKey(), entry.getValue()); } } public Set<Entry<String, Object>> entrySet() { return getUnderlyingMap().entrySet(); } public Set<String> keySet() { return getUnderlyingMap().keySet(); } public Object get(Object key) { checkKey(key); if ("rendered".equals(key)) { return true; } if ("transient".equals(key)) { return true; } if (ComponentSupport.MARK_CREATED.equals(key)) { return _markCreated; } return (_attributes == null) ? null : _attributes.get(key); } public Object remove(Object key) { checkKey(key); if (ComponentSupport.MARK_CREATED.equals(key)) { _markCreated = null; } return (_attributes == null) ? null : _attributes.remove(key); } public Object put(String key, Object value) { checkKey(key); if (ComponentSupport.MARK_CREATED.equals(key)) { String old = _markCreated; _markCreated = (String) value; return old; } return getUnderlyingMap().put(key, value); } private void checkKey(Object key) { if (key == null) { throw new NullPointerException("key"); } if (!(key instanceof String)) { throw new ClassCastException("key is not a String"); } } Map<String, Object> getUnderlyingMap() { if (_attributes == null) { _attributes = new HashMap<String, Object>(2,1); } return _attributes; } @Override public Map<String, Object> getPassThroughAttributes(boolean create) { if (create) { // Just return an empty map, because UILeaf cannot contain // passthrough attributes. return Collections.emptyMap(); } else { return null; } } }
epl-1.0
forge/docker-addon
src/main/java/org/jboss/forge/addon/docker/resource/DockerFileResource.java
1792
package org.jboss.forge.addon.docker.resource; import org.jboss.forge.addon.docker.linter.DockerfileLintResult; import org.jboss.forge.addon.resource.FileResource; import org.jboss.forge.addon.resource.Resource; import org.jboss.shrinkwrap.descriptor.api.docker.DockerDescriptor; /** * A {@link Resource} that represents a Dockerfile. * * @author <a href="mailto:devanshu911@gmail.com">Devanshu Singh</a> */ public interface DockerFileResource extends FileResource<DockerFileResource> { /** * Return the {@link DockerfileLintResult} ,lint the underlying Dockerfile against a set of preset base rules. * * @return The result of validation containing errors, warnings and info. */ DockerfileLintResult lint(); /** * Return the {@link DockerfileLintResult} ,lint the underlying Dockerfile against the given rule file. * * @param ruleFile The {@link Resource} which is the abstraction for YAML rule file used to lint against. * @return The result of validation containing errors, warnings and info. */ DockerfileLintResult lint(Resource<?> ruleFile); /** * Return the {@link DockerDescriptor} representing the underlying Dockerfile. * * @return The {@link DockerDescriptor} (ShrinkWrap Descriptors implementation for Dockerfiles) corresponding to this * {@link DockerFileResource}. */ DockerDescriptor getDockerDescriptor(); /** * Sets the content of this {@link DockerFileResource} to the passed {@link DockerDescriptor}. * * @param descriptor The {@link DockerDescriptor} (ShrinkWrap Descriptors implementation for Dockerfiles). * @return this {@link DockerFileResource} with contents of the descriptor. */ DockerFileResource setContents(DockerDescriptor descriptor); }
epl-1.0
jesusc/bento
tests/bento.sirius.tests/src-gen/bento/sirius/tests/boxes/impl/BoxesPackageImpl.java
8219
/** */ package bento.sirius.tests.boxes.impl; import bento.sirius.tests.boxes.Arrow; import bento.sirius.tests.boxes.BoxNode; import bento.sirius.tests.boxes.BoxesFactory; import bento.sirius.tests.boxes.BoxesPackage; import bento.sirius.tests.boxes.Model; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class BoxesPackageImpl extends EPackageImpl implements BoxesPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass modelEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass boxNodeEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass arrowEClass = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see bento.sirius.tests.boxes.BoxesPackage#eNS_URI * @see #init() * @generated */ private BoxesPackageImpl() { super(eNS_URI, BoxesFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link BoxesPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static BoxesPackage init() { if (isInited) return (BoxesPackage)EPackage.Registry.INSTANCE.getEPackage(BoxesPackage.eNS_URI); // Obtain or create and register package Object registeredBoxesPackage = EPackage.Registry.INSTANCE.get(eNS_URI); BoxesPackageImpl theBoxesPackage = registeredBoxesPackage instanceof BoxesPackageImpl ? (BoxesPackageImpl)registeredBoxesPackage : new BoxesPackageImpl(); isInited = true; // Create package meta-data objects theBoxesPackage.createPackageContents(); // Initialize created meta-data theBoxesPackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theBoxesPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(BoxesPackage.eNS_URI, theBoxesPackage); return theBoxesPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getModel() { return modelEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getModel_Boxes() { return (EReference)modelEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getModel_Arrows() { return (EReference)modelEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getBoxNode() { return boxNodeEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getBoxNode_Label() { return (EAttribute)boxNodeEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getArrow() { return arrowEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getArrow_Label() { return (EAttribute)arrowEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getArrow_Src() { return (EReference)arrowEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getArrow_Tgt() { return (EReference)arrowEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public BoxesFactory getBoxesFactory() { return (BoxesFactory)getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features modelEClass = createEClass(MODEL); createEReference(modelEClass, MODEL__BOXES); createEReference(modelEClass, MODEL__ARROWS); boxNodeEClass = createEClass(BOX_NODE); createEAttribute(boxNodeEClass, BOX_NODE__LABEL); arrowEClass = createEClass(ARROW); createEAttribute(arrowEClass, ARROW__LABEL); createEReference(arrowEClass, ARROW__SRC); createEReference(arrowEClass, ARROW__TGT); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes // Initialize classes, features, and operations; add parameters initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getModel_Boxes(), this.getBoxNode(), null, "boxes", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getModel_Arrows(), this.getArrow(), null, "arrows", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(boxNodeEClass, BoxNode.class, "BoxNode", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getBoxNode_Label(), ecorePackage.getEString(), "label", null, 1, 1, BoxNode.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(arrowEClass, Arrow.class, "Arrow", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getArrow_Label(), ecorePackage.getEString(), "label", null, 1, 1, Arrow.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getArrow_Src(), this.getBoxNode(), null, "src", null, 1, 1, Arrow.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getArrow_Tgt(), this.getBoxNode(), null, "tgt", null, 1, 1, Arrow.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Create resource createResource(eNS_URI); } } //BoxesPackageImpl
epl-1.0
ControlSystemStudio/cs-studio
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/PolymorphicCollection.java
3717
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.joined.relation; import java.util.Arrays; import javax.persistence.EntityManager; import org.hibernate.envers.test.AbstractEntityTest; import org.hibernate.envers.test.tools.TestTools; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.hibernate.ejb.Ejb3Configuration; /** * @author Adam Warski (adam at warski dot org) */ public class PolymorphicCollection extends AbstractEntityTest { private Integer ed_id1; private Integer c_id; private Integer p_id; public void configure(Ejb3Configuration cfg) { cfg.addAnnotatedClass(ChildIngEntity.class); cfg.addAnnotatedClass(ParentIngEntity.class); cfg.addAnnotatedClass(ReferencedEntity.class); } @BeforeClass(dependsOnMethods = "init") public void initData() { EntityManager em = getEntityManager(); ed_id1 = 1; p_id = 10; c_id = 100; // Rev 1 em.getTransaction().begin(); ReferencedEntity re = new ReferencedEntity(ed_id1); em.persist(re); em.getTransaction().commit(); // Rev 2 em.getTransaction().begin(); re = em.find(ReferencedEntity.class, ed_id1); ParentIngEntity pie = new ParentIngEntity(p_id,"x"); pie.setReferenced(re); em.persist(pie); p_id = pie.getId(); em.getTransaction().commit(); // Rev 3 em.getTransaction().begin(); re = em.find(ReferencedEntity.class, ed_id1); ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); cie.setReferenced(re); em.persist(cie); c_id = cie.getId(); em.getTransaction().commit(); } @Test public void testRevisionsCounts() { assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, ed_id1)); assert Arrays.asList(2).equals(getAuditReader().getRevisions(ParentIngEntity.class, p_id)); assert Arrays.asList(3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); } @Test public void testHistoryOfReferencedCollection() { assert getAuditReader().find(ReferencedEntity.class, ed_id1, 1).getReferencing().size() == 0; assert getAuditReader().find(ReferencedEntity.class, ed_id1, 2).getReferencing().equals( TestTools.makeSet(new ParentIngEntity(p_id, "x"))); assert getAuditReader().find(ReferencedEntity.class, ed_id1, 3).getReferencing().equals( TestTools.makeSet(new ParentIngEntity(p_id, "x"), new ChildIngEntity(c_id, "y", 1l))); } }
epl-1.0
elelpublic/wikitext-all
src/org.eclipse.mylyn.wikitext.core/src/org/eclipse/mylyn/wikitext/core/parser/markup/DefaultIdGenerationStrategy.java
1108
/******************************************************************************* * Copyright (c) 2007, 2009 David Green and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Green - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.wikitext.core.parser.markup; /** * A default ID generation strategy which removes all non-alphanumeric characters from the heading text to produce an * id. * * @author David Green * @since 1.0 */ public class DefaultIdGenerationStrategy extends IdGenerationStrategy { @Override public String generateId(String headingText) { String anchor = headingText.replaceAll("[^a-zA-Z0-9.]", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (anchor.length() > 0 && Character.isDigit(anchor.charAt(0))) { anchor = 'a' + anchor; } return anchor; } }
epl-1.0
fp7-netide/Engine
odl-shim/openflowjava-extension/src/test/java/org/opendaylight/netide/openflowjava/protocol/impl/serialization/factories/BarrierReplyMessageFactoryTest.java
1911
/* * Copyright (c) 2015 NetIDE Consortium and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netide.openflowjava.protocol.impl.serialization.factories; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; import org.junit.Before; import org.junit.Test; import org.opendaylight.netide.openflowjava.protocol.impl.serialization.NetIdeSerializerRegistryImpl; import org.opendaylight.netide.openflowjava.protocol.impl.util.BufferHelper; import org.opendaylight.openflowjava.protocol.api.extensibility.SerializerRegistry; import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutputBuilder; /** * @author giuseppex.petralia@intel.com * */ public class BarrierReplyMessageFactoryTest { BarrierOutput message; private static final byte MESSAGE_TYPE = 21; @Before public void startUp() throws Exception { BarrierOutputBuilder builder = new BarrierOutputBuilder(); BufferHelper.setupHeader(builder, EncodeConstants.OF13_VERSION_ID); message = builder.build(); } @Test public void testSerialize() { BarrierReplyMessageFactory serializer = new BarrierReplyMessageFactory(); SerializerRegistry registry = new NetIdeSerializerRegistryImpl(); registry.init(); ByteBuf serializedBuffer = UnpooledByteBufAllocator.DEFAULT.buffer(); serializer.serialize(message, serializedBuffer); BufferHelper.checkHeaderV13(serializedBuffer, MESSAGE_TYPE, 8); } }
epl-1.0
cbaerikebc/kapua
service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntity.java
1071
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Kapua named entity definition. * * @since 1.0 * */ @XmlType(propOrder = {"name" }) public interface KapuaNamedEntity extends KapuaUpdatableEntity { /** * Get the entity name * * @return */ @XmlElement(name="name") public String getName(); /** * Set the entity name * * @param name */ public void setName(String name); }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/AIBrowseCursor.java
10235
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.sib.processor.impl; import com.ibm.websphere.ras.TraceComponent; import com.ibm.ejs.ras.TraceNLS; import com.ibm.ejs.util.am.Alarm; import com.ibm.ejs.util.am.AlarmListener; import com.ibm.websphere.sib.exception.SIResourceException; import com.ibm.ws.ffdc.FFDCFilter; import com.ibm.ws.sib.mfp.JsMessage; import com.ibm.ws.sib.msgstore.Filter; import com.ibm.ws.sib.processor.SIMPConstants; import com.ibm.ws.sib.processor.impl.interfaces.BrowseCursor; import com.ibm.ws.sib.processor.impl.store.items.MessageItem; import com.ibm.ws.sib.processor.utils.am.MPAlarmManager; import com.ibm.ws.sib.utils.ras.SibTr; /** * */ public class AIBrowseCursor implements BrowseCursor, AlarmListener { // NLS for component private static final TraceNLS nls = TraceNLS.getTraceNLS(SIMPConstants.RESOURCE_BUNDLE); // Standard debug/trace private static final TraceComponent tc = SibTr.register( AIBrowseCursor.class, SIMPConstants.MP_TRACE_GROUP, SIMPConstants.RESOURCE_BUNDLE); private AnycastInputHandler parent; private long browseId; private Filter filter; // Contains the value of the sequence number for the current BrowseGet, to be correlated with the // BrowseData received in response private long seqNum; private MessageItem nextItem; private boolean browseClosed; private boolean browseFailed; private int failureReason; private Alarm keepAliveAlarmHandle; private MPAlarmManager am; /** * The constructor * @param parent The encapsulating AnycastInputHandler, which creates and calls methods on this */ public AIBrowseCursor( AnycastInputHandler parent, Filter filter, long browseId, MPAlarmManager am) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "AIBrowseCursor", new Object[] { parent, filter, new Long(browseId), am }); this.am = am; this.parent = parent; this.filter = filter; this.browseId = browseId; // The sequence number will be incremented before a BrowseGet is sent // This way the current value of seqNum will also be the value to be expected in a response this.seqNum = -1; this.nextItem = null; this.browseClosed = false; this.browseFailed = false; this.failureReason = SIMPConstants.BROWSE_OK; keepAliveAlarmHandle = am.create(parent.getMessageProcessor().getCustomProperties().get_browse_liveness_timeout(), this); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "AIBrowseCursor", this); } ////////////////////////////////////////////////////////////// // NonLockingCursor methods ////////////////////////////////////////////////////////////// public void finished() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "finished"); synchronized (this) { parent.sendBrowseStatus(SIMPConstants.BROWSE_CLOSE, browseId); if (keepAliveAlarmHandle != null) { keepAliveAlarmHandle.cancel(); keepAliveAlarmHandle = null; } parent.removeBrowseCursor(browseId); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "finished"); } public JsMessage next() throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "next"); MessageItem item = null; // Serialize invocation of next. synchronized (this) { if (!browseClosed && !browseFailed) { // cancel the existing liveness alarm keepAliveAlarmHandle.cancel(); seqNum++; Filter nextFilter = ((seqNum == 0) ? this.filter : null); parent.sendBrowseGet(browseId, seqNum, nextFilter); try { wait(parent.getMessageProcessor().getCustomProperties().get_browse_get_timeout()); } catch (InterruptedException e) { // May not need to FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.AIBrowseCursor.next", "1:179:1.25", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "next", item); return null; } } // if this.nextItem is null, then the wait ended because of a timeout, browse close or browse failure if (this.nextItem == null) { keepAliveAlarmHandle = null; if (browseClosed) { item = null; } else if (browseFailed) { // log error SIResourceException e = new SIResourceException( nls.getFormattedMessage( "BROWSE_FAILED_CWSIP0533", new Object[] { parent.getDestName(), failureReasonToString(failureReason) }, null)); FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.AIBrowseCursor.next", "1:215:1.25", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "next", e); throw e; } else { // log error SIResourceException e = new SIResourceException( nls.getFormattedMessage( "BROWSE_TIMEOUT_CWSIP0532", new Object[] {parent.getDestName()}, null)); FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.AIBrowseCursor.next", "1:236:1.25", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "next", e); throw e; } } else { item = this.nextItem; this.nextItem = null; // create a new liveness alarm keepAliveAlarmHandle = am.create(parent.getMessageProcessor().getCustomProperties().get_browse_liveness_timeout(), this); } } JsMessage returnMessage = null; if(item!=null) { returnMessage = item.getMessage(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "next", returnMessage); return returnMessage; } ////////////////////////////////////////////////////////////// // AlarmListener methods ////////////////////////////////////////////////////////////// public void alarm(Object handle) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "alarm", handle); synchronized (this) { keepAliveAlarmHandle = am.create(parent.getMessageProcessor().getCustomProperties().get_browse_liveness_timeout(), this); parent.sendBrowseStatus(SIMPConstants.BROWSE_ALIVE, browseId); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "alarm"); } ////////////////////////////////////////////////////////////// // Methods invoked by AnycastInputHandler ////////////////////////////////////////////////////////////// public synchronized void put(MessageItem message) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "put", message); JsMessage jsMsg = message.getMessage(); long msgSeqNum = jsMsg.getGuaranteedRemoteBrowseSequenceNumber(); if (msgSeqNum != seqNum) { this.nextItem = null; this.browseFailed = true; this.failureReason = SIMPConstants.BROWSE_OUT_OF_ORDER; } else { this.nextItem = message; } // wake up thread waiting for response notify(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "put"); } public synchronized void endBrowse() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "endBrowse"); this.browseClosed = true; // wake up thread waiting for response notify(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "endBrowse"); } public synchronized void browseFailed(int reason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "browseFailed"); this.browseFailed = true; this.failureReason = reason; // wake up thread waiting for response notify(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "browseFailed"); } ////////////////////////////////////////////////////////////// // Private Methods ////////////////////////////////////////////////////////////// private String failureReasonToString(int failureReason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "failureReasonToString", new Integer(failureReason)); String frString = ""; switch (failureReason) { case SIMPConstants.BROWSE_STORE_EXCEPTION: frString = "browse store exception"; break; case SIMPConstants.BROWSE_OUT_OF_ORDER: frString = "browse out of order"; break; case SIMPConstants.BROWSE_BAD_FILTER: frString = "browse bad filter"; break; default: frString = ""; break; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "failureReasonToString", frString); return frString; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.websphere.javaee.management.j2ee.1.1/src/javax/management/j2ee/statistics/BoundedRangeStatistic.java
846
/******************************************************************************* * Copyright (c) 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package javax.management.j2ee.statistics; /** * The BoundedRangeStatistic interface extends the RangeStatistic and * BoundaryStatistic interfaces and provides standard measurements of a range that * has fixed limits. */ public interface BoundedRangeStatistic extends RangeStatistic, BoundaryStatistic { }
epl-1.0
openhab/openhab
bundles/binding/org.openhab.binding.gc100ir/src/main/java/org/openhab/binding/gc100ir/util/GC100ItemBean.java
1241
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.gc100ir.util; /** * Stores GC100 item's properties. * * @author Parikshit Thakur & Team * @since 1.9.0 * */ public class GC100ItemBean { String gc100Instance; int module; int connector; String code; public String getGC100Instance() { return gc100Instance; } public void setGC100Instance(String gc100Instance) { this.gc100Instance = gc100Instance; } public int getModule() { return module; } public void setModule(int module) { this.module = module; } public int getConnector() { return connector; } public void setConnector(int connector) { this.connector = connector; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.cdi.beansxml_fat/fat/src/com/ibm/ws/cdi/beansxml/fat/apps/classexclusion/fallbackbeans/FallbackForExcludedPackageBean.java
953
/******************************************************************************* * Copyright (c) 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.cdi.beansxml.fat.apps.classexclusion.fallbackbeans; import javax.enterprise.context.RequestScoped; import com.ibm.ws.cdi.beansxml.fat.apps.classexclusion.interfaces.IExcludedPackageBean; @RequestScoped public class FallbackForExcludedPackageBean implements IExcludedPackageBean { @Override public String getOutput() { return "ExcludedPackageBean was correctly rejected"; } }
epl-1.0
neubatengog/kura
kura/org.eclipse.kura.web/src/main/java/org/eclipse/kura/web/shared/model/GwtSnapshot.java
1676
/** * Copyright (c) 2011, 2014 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech */ package org.eclipse.kura.web.shared.model; import java.io.Serializable; import java.util.Date; import org.eclipse.kura.web.client.util.DateUtils; import org.eclipse.kura.web.client.util.MessageUtils; import com.extjs.gxt.ui.client.data.BaseModel; public class GwtSnapshot extends BaseModel implements Serializable { private static final long serialVersionUID = 204571826084819719L; public GwtSnapshot() {} @Override @SuppressWarnings({"unchecked"}) public <X> X get(String property) { if ("createdOnFormatted".equals(property)) { if (((Date) get("createdOn")).getTime() == 0) { return (X) (MessageUtils.get("snapSeeded")); } return (X) (DateUtils.formatDateTime((Date) get("createdOn"))); } else if ("snapshotId".equals(property)) { return (X) new Long(((Date) get("createdOn")).getTime()); } else { return super.get(property); } } public Date getCreatedOn() { return (Date) get("createdOn"); } public long getSnapshotId() { return ((Date) get("createdOn")).getTime(); } public String getCreatedOnFormatted() { return DateUtils.formatDateTime((Date) get("createdOn")); } public void setCreatedOn(Date createdOn) { set("createdOn", createdOn); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxb_fat/publish/servers/com.ibm.ws.jaxb.tools.TestServer/temp/schemagenSourceDir/PurchaseOrderType.java
4427
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:17 AM(foreman)- // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.02.07 at 02:15:17 PM CST // package po; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for PurchaseOrderType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PurchaseOrderType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="shipTo" type="{}ShippingAddress"/> * &lt;element name="billTo" type="{}ShippingAddress"/> * &lt;element ref="{}comment" minOccurs="0"/> * &lt;element name="items" type="{}Items"/> * &lt;/sequence> * &lt;attribute name="orderDate" type="{http://www.w3.org/2001/XMLSchema}date" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PurchaseOrderType", propOrder = { "shipTo", "billTo", "comment", "items" }) public class PurchaseOrderType { @XmlElement(required = true) protected ShippingAddress shipTo; @XmlElement(required = true) protected ShippingAddress billTo; protected String comment; @XmlElement(required = true) protected Items items; @XmlAttribute(name = "orderDate") @XmlSchemaType(name = "date") protected XMLGregorianCalendar orderDate; /** * Gets the value of the shipTo property. * * @return * possible object is * {@link ShippingAddress } * */ public ShippingAddress getShipTo() { return shipTo; } /** * Sets the value of the shipTo property. * * @param value * allowed object is * {@link ShippingAddress } * */ public void setShipTo(ShippingAddress value) { this.shipTo = value; } /** * Gets the value of the billTo property. * * @return * possible object is * {@link ShippingAddress } * */ public ShippingAddress getBillTo() { return billTo; } /** * Sets the value of the billTo property. * * @param value * allowed object is * {@link ShippingAddress } * */ public void setBillTo(ShippingAddress value) { this.billTo = value; } /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) { this.comment = value; } /** * Gets the value of the items property. * * @return * possible object is * {@link Items } * */ public Items getItems() { return items; } /** * Sets the value of the items property. * * @param value * allowed object is * {@link Items } * */ public void setItems(Items value) { this.items = value; } /** * Gets the value of the orderDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getOrderDate() { return orderDate; } /** * Sets the value of the orderDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setOrderDate(XMLGregorianCalendar value) { this.orderDate = value; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.tests.spec21.txsynchronization_fat/fat/src/com/ibm/ws/jpa/tests/spec21/txsynchronization/TestTXSynchronization.java
12526
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jpa.tests.spec21.txsynchronization; import java.util.HashSet; import java.util.Set; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.ibm.websphere.simplicity.ShrinkHelper; import com.ibm.websphere.simplicity.config.Application; import com.ibm.websphere.simplicity.config.ServerConfiguration; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMEXSpecificRunnerTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMEXSpecificSyncTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMEXSpecificUnsyncTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMTCMEXSpecificEJBSLTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMTCMTSSpecificEJBSLTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMTSSpecificEJBSFTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationCMTSSpecificEJBSLTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationEJBSFExSyncTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationEJBSFExUnsyncTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationEJBSFTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.ejb.TxSynchronizationEJBSLTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.web.TxSynchronizationCMTSSpecificWebTestServlet; import com.ibm.ws.jpa.fvt.txsync.tests.web.TxSynchronizationWebTestServlet; import componenttest.annotation.Server; import componenttest.annotation.TestServlet; import componenttest.annotation.TestServlets; import componenttest.custom.junit.runner.FATRunner; import componenttest.topology.impl.LibertyServer; import componenttest.topology.utils.PrivHelper; @RunWith(FATRunner.class) //@Mode(TestMode.FULL) public class TestTXSynchronization extends JPAFATServletClient { private final static String RESOURCE_ROOT = "test-applications/TxSynchronization/"; private final static Set<String> dropSet = new HashSet<String>(); private final static Set<String> createSet = new HashSet<String>(); private static long timestart = 0; static { dropSet.add("JPA21_TXSYNC_DROP_${dbvendor}.ddl"); createSet.add("JPA21_TXSYNC_CREATE_${dbvendor}.ddl"); } @Server("JPAServerTxSynchronization") @TestServlets({ @TestServlet(servlet = TxSynchronizationWebTestServlet.class, path = "TxSynchronization" + "/" + "TxSynchronizationWebTestServlet"), @TestServlet(servlet = TxSynchronizationCMTSSpecificWebTestServlet.class, path = "TxSynchronization" + "/" + "TxSynchronizationCMTSSpecificWebTestServlet"), @TestServlet(servlet = TxSynchronizationEJBSLTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationEJBSLTestServlet"), @TestServlet(servlet = TxSynchronizationCMTSSpecificEJBSLTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMTSSpecificEJBSLTestServlet"), @TestServlet(servlet = TxSynchronizationEJBSFTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationEJBSFTestServlet"), @TestServlet(servlet = TxSynchronizationCMTSSpecificEJBSFTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMTSSpecificEJBSFTestServlet"), @TestServlet(servlet = TxSynchronizationEJBSFExSyncTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationEJBSFExSyncTestServlet"), @TestServlet(servlet = TxSynchronizationEJBSFExUnsyncTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationEJBSFExUnsyncTestServlet"), @TestServlet(servlet = TxSynchronizationCMEXSpecificSyncTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMEXSpecificSyncTestServlet"), @TestServlet(servlet = TxSynchronizationCMEXSpecificUnsyncTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMEXSpecificUnsyncTestServlet"), @TestServlet(servlet = TxSynchronizationCMEXSpecificRunnerTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMEXSpecificRunnerTestServlet"), @TestServlet(servlet = TxSynchronizationCMTCMTSSpecificEJBSLTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMTCMTSSpecificEJBSLTestServlet"), @TestServlet(servlet = TxSynchronizationCMTCMEXSpecificEJBSLTestServlet.class, path = "TxSynchronizationEJB" + "/" + "TxSynchronizationCMTCMEXSpecificEJBSLTestServlet"), }) public static LibertyServer server; @BeforeClass public static void setUp() throws Exception { PrivHelper.generateCustomPolicy(server, FATSuite.JAXB_PERMS); bannerStart(TestTXSynchronization.class); timestart = System.currentTimeMillis(); int appStartTimeout = server.getAppStartTimeout(); if (appStartTimeout < (120 * 1000)) { server.setAppStartTimeout(120 * 1000); } int configUpdateTimeout = server.getConfigUpdateTimeout(); if (configUpdateTimeout < (120 * 1000)) { server.setConfigUpdateTimeout(120 * 1000); } server.startServer(); setupDatabaseApplication(server, RESOURCE_ROOT + "ddl/"); final Set<String> ddlSet = new HashSet<String>(); System.out.println("TestTXSynchronization Setting up database tables..."); ddlSet.clear(); for (String ddlName : dropSet) { ddlSet.add(ddlName.replace("${dbvendor}", getDbVendor().name())); } executeDDL(server, ddlSet, true); ddlSet.clear(); for (String ddlName : createSet) { ddlSet.add(ddlName.replace("${dbvendor}", getDbVendor().name())); } executeDDL(server, ddlSet, false); setupTestApplication(); } private static void setupTestApplication() throws Exception { // jpaentities.jar final JavaArchive entityJar = ShrinkWrap.create(JavaArchive.class, "jpaentities.jar"); entityJar.addPackage("com.ibm.ws.jpa.commonentities.jpa10.simple"); ShrinkHelper.addDirectory(entityJar, RESOURCE_ROOT + "apps/TxSynchronization.ear/lib/jpaentities.jar"); // testlogic.jar final JavaArchive testLogicJar = ShrinkWrap.create(JavaArchive.class, "testlogic.jar"); testLogicJar.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.testlogic"); testLogicJar.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.testlogic.cm"); // TxSynchronization.war WebArchive webApp = ShrinkWrap.create(WebArchive.class, "TxSynchronization.war"); webApp.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.tests.web"); ShrinkHelper.addDirectory(webApp, RESOURCE_ROOT + "apps/TxSynchronization.ear/TxSynchronization.war"); // TxSynchronizationEJB.war WebArchive ejbwebApp = ShrinkWrap.create(WebArchive.class, "TxSynchronizationEJB.war"); ejbwebApp.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.tests.ejb"); ShrinkHelper.addDirectory(ejbwebApp, RESOURCE_ROOT + "apps/TxSynchronization.ear/TxSynchronizationEJB.war"); // TxSynchronizationEJB JavaArchive txsyncEjb = ShrinkWrap.create(JavaArchive.class, "TxSynchronizationEJB.jar"); txsyncEjb.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.ejb"); txsyncEjb.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.ejblocal"); ShrinkHelper.addDirectory(txsyncEjb, RESOURCE_ROOT + "apps/TxSynchronization.ear/TxSynchronizationEJB.jar"); // TxSynchronizationBuddyEJB JavaArchive buddyEjb = ShrinkWrap.create(JavaArchive.class, "TxSynchronizationBuddyEJB.jar"); buddyEjb.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.buddy.ejb"); buddyEjb.addPackages(true, "com.ibm.ws.jpa.fvt.txsync.buddy.ejblocal"); ShrinkHelper.addDirectory(buddyEjb, RESOURCE_ROOT + "apps/TxSynchronization.ear/TxSynchronizationBuddyEJB.jar"); final JavaArchive testApiJar = buildTestAPIJar(); final EnterpriseArchive app = ShrinkWrap.create(EnterpriseArchive.class, "TxSynchronization.ear"); app.addAsModule(webApp); app.addAsModule(ejbwebApp); app.addAsModule(txsyncEjb); app.addAsModule(buddyEjb); app.addAsLibrary(entityJar); app.addAsLibrary(testApiJar); app.addAsLibrary(testLogicJar); ShrinkHelper.addDirectory(app, RESOURCE_ROOT + "apps/TxSynchronization.ear", new org.jboss.shrinkwrap.api.Filter<ArchivePath>() { @Override public boolean include(ArchivePath arg0) { if (arg0.get().startsWith("/META-INF/")) { return true; } return false; } }); ShrinkHelper.exportToServer(server, "apps", app); Application appRecord = new Application(); appRecord.setLocation("TxSynchronization.ear"); appRecord.setName("TxSynchronization"); // ConfigElementList<ClassloaderElement> cel = appRecord.getClassloaders(); // ClassloaderElement loader = new ClassloaderElement(); // loader.setApiTypeVisibility("+third-party"); //// loader.getCommonLibraryRefs().add("HibernateLib"); // cel.add(loader); server.setMarkToEndOfLog(); ServerConfiguration sc = server.getServerConfiguration(); sc.getApplications().add(appRecord); server.updateServerConfiguration(sc); server.saveServerConfiguration(); HashSet<String> appNamesSet = new HashSet<String>(); appNamesSet.add("TxSynchronization"); server.waitForConfigUpdateInLogUsingMark(appNamesSet, ""); } @AfterClass public static void tearDown() throws Exception { try { // Clean up database try { final Set<String> ddlSet = new HashSet<String>(); for (String ddlName : dropSet) { ddlSet.add(ddlName.replace("${dbvendor}", getDbVendor().name())); } executeDDL(server, ddlSet, true); } catch (Throwable t) { t.printStackTrace(); } server.stopServer("CWWJP9991W", // From Eclipselink drop-and-create tables option "WTRN0074E: Exception caught from before_completion synchronization operation", // RuntimeException test, expected "CWWJP0046E: An UNSYNCHRONIZED JPA persistence context cannot be propagated into a SYNCHRONIZED EntityManager", "CNTR0020E", "CWWJP0045E", "WLTC0017E", "CNTR0019E", "CWWKG0032W"); } finally { try { ServerConfiguration sc = server.getServerConfiguration(); sc.getApplications().clear(); server.updateServerConfiguration(sc); server.saveServerConfiguration(); server.deleteFileFromLibertyServerRoot("apps/" + "TxSynchronization.ear"); server.deleteFileFromLibertyServerRoot("apps/DatabaseManagement.war"); } catch (Throwable t) { t.printStackTrace(); } bannerEnd(TestTXSynchronization.class, timestart); } } }
epl-1.0
sudaraka94/che
plugins/plugin-languageserver/che-plugin-languageserver-ide/src/main/java/org/eclipse/che/plugin/languageserver/ide/editor/codeassist/LanguageServerCodeAssistProcessor.java
5930
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.plugin.languageserver.ide.editor.codeassist; import static com.google.common.collect.Lists.newArrayList; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import java.util.ArrayList; import java.util.List; import org.eclipse.che.api.languageserver.shared.model.ExtendedCompletionItem; import org.eclipse.che.ide.api.editor.codeassist.CodeAssistCallback; import org.eclipse.che.ide.api.editor.codeassist.CodeAssistProcessor; import org.eclipse.che.ide.api.editor.codeassist.CompletionProposal; import org.eclipse.che.ide.api.editor.texteditor.TextEditor; import org.eclipse.che.ide.filters.FuzzyMatches; import org.eclipse.che.ide.filters.Match; import org.eclipse.che.plugin.languageserver.ide.LanguageServerResources; import org.eclipse.che.plugin.languageserver.ide.service.TextDocumentServiceClient; import org.eclipse.che.plugin.languageserver.ide.util.DtoBuildHelper; import org.eclipse.lsp4j.CompletionItem; import org.eclipse.lsp4j.ServerCapabilities; import org.eclipse.lsp4j.TextDocumentIdentifier; import org.eclipse.lsp4j.TextDocumentPositionParams; /** Implement code assist with LS */ public class LanguageServerCodeAssistProcessor implements CodeAssistProcessor { private final DtoBuildHelper dtoBuildHelper; private final LanguageServerResources resources; private final CompletionImageProvider imageProvider; private final ServerCapabilities serverCapabilities; private final TextDocumentServiceClient documentServiceClient; private final FuzzyMatches fuzzyMatches; private final LatestCompletionResult latestCompletionResult; private String lastErrorMessage; @Inject public LanguageServerCodeAssistProcessor( TextDocumentServiceClient documentServiceClient, DtoBuildHelper dtoBuildHelper, LanguageServerResources resources, CompletionImageProvider imageProvider, @Assisted ServerCapabilities serverCapabilities, FuzzyMatches fuzzyMatches) { this.documentServiceClient = documentServiceClient; this.dtoBuildHelper = dtoBuildHelper; this.resources = resources; this.imageProvider = imageProvider; this.serverCapabilities = serverCapabilities; this.fuzzyMatches = fuzzyMatches; this.latestCompletionResult = new LatestCompletionResult(); } @Override public void computeCompletionProposals( TextEditor editor, final int offset, final boolean triggered, final CodeAssistCallback callback) { this.lastErrorMessage = null; TextDocumentPositionParams documentPosition = dtoBuildHelper.createTDPP(editor.getDocument(), offset); final TextDocumentIdentifier documentId = documentPosition.getTextDocument(); String currentLine = editor.getDocument().getLineContent(documentPosition.getPosition().getLine()); final String currentWord = getCurrentWord(currentLine, documentPosition.getPosition().getCharacter()); if (!triggered && latestCompletionResult.isGoodFor(documentId, offset, currentWord)) { // no need to send new completion request computeProposals(currentWord, offset - latestCompletionResult.getOffset(), callback); } else { documentServiceClient .completion(documentPosition) .then( list -> { latestCompletionResult.update(documentId, offset, currentWord, list); computeProposals(currentWord, 0, callback); }) .catchError( error -> { lastErrorMessage = error.getMessage(); }); } } @Override public String getErrorMessage() { return lastErrorMessage; } private String getCurrentWord(String text, int offset) { int i = offset - 1; while (i >= 0 && isWordChar(text.charAt(i))) { i--; } return text.substring(i + 1, offset); } private boolean isWordChar(char c) { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= '\u007f' && c <= '\u00ff' || c == '$' || c == '_' || c == '-'; } private List<Match> filter(String word, CompletionItem item) { return filter(word, item.getLabel(), item.getFilterText()); } private List<Match> filter(String word, String label, String filterText) { if (filterText == null || filterText.isEmpty()) { filterText = label; } // check if the word matches the filterText if (fuzzyMatches.fuzzyMatch(word, filterText) != null) { // return the highlights based on the label List<Match> highlights = fuzzyMatches.fuzzyMatch(word, label); // return empty list of highlights if nothing matches the label return (highlights == null) ? new ArrayList<>() : highlights; } return null; } private void computeProposals(String currentWord, int offset, CodeAssistCallback callback) { List<CompletionProposal> proposals = newArrayList(); for (ExtendedCompletionItem item : latestCompletionResult.getCompletionList().getItems()) { List<Match> highlights = filter(currentWord, item.getItem()); if (highlights != null) { proposals.add( new CompletionItemBasedCompletionProposal( item, currentWord, documentServiceClient, resources, imageProvider.getIcon(item.getItem().getKind()), serverCapabilities, highlights, offset)); } } callback.proposalComputed(proposals); } }
epl-1.0
kfishster/JGraphT_Jenkins
jgrapht-core/src/main/java/org/jgrapht/experimental/UniformRandomGraphGenerator.java
2889
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ /* ------------------- * UniformRandomGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id$ * * Changes * ------- * 13-Sep-2004 : Initial revision (MB); * */ // package org.jgrapht.generate; package org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; import org.jgrapht.generate.*; /** * UniformRandomGraphGenerator generates a <a * href="http://mathworld.wolfram.com/RandomGraph.html">uniform random graph</a> * of any size. A uniform random graph contains edges chosen independently * uniformly at random from the set of all possible edges. * * @author Michael Behrisch * @since Sep 13, 2004 */ public class UniformRandomGraphGenerator implements GraphGenerator { private final int numEdges; private final int numVertices; /** * Construct a new UniformRandomGraphGenerator. * * @param numVertices number of vertices to be generated * @param numEdges number of edges to be generated * * @throws IllegalArgumentException */ public UniformRandomGraphGenerator(int numVertices, int numEdges) { if (numVertices < 0) { throw new IllegalArgumentException("must be non-negative"); } if ((numEdges < 0) || (numEdges > (numVertices * (numVertices - 1) / 2))) { throw new IllegalArgumentException("illegal number of edges"); } this.numVertices = numVertices; this.numEdges = numEdges; } /** * @see GraphGenerator#generateGraph */ @Override public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { Object [] vertices = RandomGraphHelper.addVertices( target, vertexFactory, numVertices); RandomGraphHelper.addEdges( target, Arrays.asList(vertices), Arrays.asList(vertices), numEdges); } } // End UniformRandomGraphGenerator.java
epl-1.0
clinique/openhab2
bundles/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/handler/SqueezeBoxServerHandler.java
41965
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.squeezebox.internal.handler; import static org.openhab.binding.squeezebox.internal.SqueezeBoxBindingConstants.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.Socket; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.UnDefType; import org.openhab.binding.squeezebox.internal.config.SqueezeBoxServerConfig; import org.openhab.binding.squeezebox.internal.model.Favorite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles connection and event handling to a SqueezeBox Server. * * @author Markus Wolters - Initial contribution * @author Ben Jones - ? * @author Dan Cunningham - OH2 port * @author Daniel Walters - Fix player discovery when player name contains spaces * @author Mark Hilbush - Improve reconnect logic. Improve player status updates. * @author Mark Hilbush - Implement AudioSink and notifications * @author Mark Hilbush - Added duration channel * @author Mark Hilbush - Added login/password authentication for LMS * @author Philippe Siem - Improve refresh of cover art url,remote title, artist, album, genre, year. * @author Patrik Gfeller - Support for mixer volume message added * @author Mark Hilbush - Get favorites from LMS; update channel and send to players */ public class SqueezeBoxServerHandler extends BaseBridgeHandler { private final Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class); public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections .singleton(SQUEEZEBOXSERVER_THING_TYPE); // time in seconds to try to reconnect private static final int RECONNECT_TIME = 60; // utf8 charset name private static final String UTF8_NAME = StandardCharsets.UTF_8.name(); // the value by which the volume is changed by each INCREASE or // DECREASE-Event private static final int VOLUME_CHANGE_SIZE = 5; private static final String NEW_LINE = System.getProperty("line.separator"); private static final String CHANNEL_CONFIG_QUOTE_LIST = "quoteList"; private List<SqueezeBoxPlayerEventListener> squeezeBoxPlayerListeners = Collections .synchronizedList(new ArrayList<SqueezeBoxPlayerEventListener>()); private Map<String, SqueezeBoxPlayer> players = Collections .synchronizedMap(new HashMap<String, SqueezeBoxPlayer>()); // client socket and listener thread private Socket clientSocket; private SqueezeServerListener listener; private Future<?> reconnectFuture; private String host; private int cliport; private int webport; private String userId; private String password; public SqueezeBoxServerHandler(Bridge bridge) { super(bridge); } @Override public void initialize() { logger.debug("initializing server handler for thing {}", getThing().getUID()); scheduler.submit(this::connect); } @Override public void dispose() { logger.debug("disposing server handler for thing {}", getThing().getUID()); cancelReconnect(); disconnect(); } @Override public void handleCommand(ChannelUID channelUID, Command command) { } /** * Checks if we have a connection to the Server * * @return */ public synchronized boolean isConnected() { if (clientSocket == null) { return false; } // NOTE: isConnected() returns true once a connection is made and will // always return true even after the socket is closed // http://stackoverflow.com/questions/10163358/ return clientSocket.isConnected() && !clientSocket.isClosed(); } public void mute(String mac) { setVolume(mac, 0); } public void unMute(String mac, int unmuteVolume) { setVolume(mac, unmuteVolume); } public void powerOn(String mac) { sendCommand(mac + " power 1"); } public void powerOff(String mac) { sendCommand(mac + " power 0"); } public void syncPlayer(String mac, String player2mac) { sendCommand(mac + " sync " + player2mac); } public void unSyncPlayer(String mac) { sendCommand(mac + " sync -"); } public void play(String mac) { sendCommand(mac + " play"); } public void playUrl(String mac, String url) { sendCommand(mac + " playlist play " + url); } public void pause(String mac) { sendCommand(mac + " pause 1"); } public void unPause(String mac) { sendCommand(mac + " pause 0"); } public void stop(String mac) { sendCommand(mac + " stop"); } public void prev(String mac) { sendCommand(mac + " playlist index -1"); } public void next(String mac) { sendCommand(mac + " playlist index +1"); } public void clearPlaylist(String mac) { sendCommand(mac + " playlist clear"); } public void deletePlaylistItem(String mac, int playlistIndex) { sendCommand(mac + " playlist delete " + playlistIndex); } public void playPlaylistItem(String mac, int playlistIndex) { sendCommand(mac + " playlist index " + playlistIndex); } public void addPlaylistItem(String mac, String url) { addPlaylistItem(mac, url, null); } public void addPlaylistItem(String mac, String url, String title) { StringBuilder playlistCommand = new StringBuilder(); playlistCommand.append(mac).append(" playlist add ").append(url); if (title != null) { playlistCommand.append(" ").append(title); } sendCommand(playlistCommand.toString()); } public void setPlayingTime(String mac, int time) { sendCommand(mac + " time " + time); } public void setRepeatMode(String mac, int repeatMode) { sendCommand(mac + " playlist repeat " + repeatMode); } public void setShuffleMode(String mac, int shuffleMode) { sendCommand(mac + " playlist shuffle " + shuffleMode); } public void volumeUp(String mac, int currentVolume) { setVolume(mac, currentVolume + VOLUME_CHANGE_SIZE); } public void volumeDown(String mac, int currentVolume) { setVolume(mac, currentVolume - VOLUME_CHANGE_SIZE); } public void setVolume(String mac, int volume) { int newVolume = volume; newVolume = Math.min(100, newVolume); newVolume = Math.max(0, newVolume); sendCommand(mac + " mixer volume " + String.valueOf(newVolume)); } public void showString(String mac, String line) { showString(mac, line, 5); } public void showString(String mac, String line, int duration) { sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration)); } public void showStringHuge(String mac, String line) { showStringHuge(mac, line, 5); } public void showStringHuge(String mac, String line, int duration) { sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration)); } public void showStrings(String mac, String line1, String line2) { showStrings(mac, line1, line2, 5); } public void showStrings(String mac, String line1, String line2, int duration) { sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration)); } public void playFavorite(String mac, String favorite) { sendCommand(mac + " favorites playlist play item_id:" + favorite); } /** * Send a generic command to a given player * * @param playerId * @param command */ public void playerCommand(String mac, String command) { sendCommand(mac + " " + command); } /** * Ask for player list */ public void requestPlayers() { sendCommand("players 0"); } /** * Ask for favorites list */ public void requestFavorites() { sendCommand("favorites items 0 100"); } /** * Login to server */ public void login() { if (StringUtils.isEmpty(userId)) { return; } logger.debug("Logging into Squeeze Server using userId={}", userId); sendCommand("login " + userId + " " + password); } /** * Send a command to the Squeeze Server. */ private synchronized void sendCommand(String command) { if (getThing().getStatus() != ThingStatus.ONLINE) { return; } if (!isConnected()) { logger.debug("no connection to squeeze server when trying to send command, returning..."); return; } logger.debug("Sending command: {}", sanitizeCommand(command)); try (Writer osw = new OutputStreamWriter(clientSocket.getOutputStream()); BufferedWriter writer = new BufferedWriter(osw)) { writer.write(command + NEW_LINE); writer.flush(); } catch (IOException e) { logger.error("Error while sending command to Squeeze Server ({}) ", sanitizeCommand(command), e); } } /* * Remove password from login command to prevent it from being logged */ String sanitizeCommand(String command) { String sanitizedCommand = command; if (command.startsWith("login")) { sanitizedCommand = command.replace(password, "**********"); } return sanitizedCommand; } /** * Connects to a SqueezeBox Server */ private void connect() { logger.trace("attempting to get a connection to the server"); disconnect(); SqueezeBoxServerConfig config = getConfigAs(SqueezeBoxServerConfig.class); this.host = config.ipAddress; this.cliport = config.cliport; this.webport = config.webport; this.userId = config.userId; this.password = config.password; if (StringUtils.isEmpty(this.host)) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "host is not set"); return; } try { clientSocket = new Socket(host, cliport); } catch (IOException e) { logger.debug("unable to open socket to server: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage()); scheduleReconnect(); return; } try { listener = new SqueezeServerListener(); listener.start(); logger.debug("listener connection started to server {}:{}", host, cliport); } catch (IllegalThreadStateException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } // Mark the server ONLINE. bridgeStatusChanged will cause the players to come ONLINE updateStatus(ThingStatus.ONLINE); } /** * Disconnects from a SqueezeBox Server */ private void disconnect() { try { if (listener != null) { listener.terminate(); } if (clientSocket != null) { clientSocket.close(); } } catch (Exception e) { logger.trace("Error attempting to disconnect from Squeeze Server", e); return; } finally { clientSocket = null; listener = null; } players.clear(); logger.trace("Squeeze Server connection stopped."); } private class SqueezeServerListener extends Thread { private boolean terminate = false; public SqueezeServerListener() { super("Squeeze Server Listener"); } public void terminate() { logger.debug("setting squeeze server listener terminate flag"); this.terminate = true; } @Override public void run() { BufferedReader reader = null; boolean endOfStream = false; try { reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); login(); updateStatus(ThingStatus.ONLINE); requestPlayers(); requestFavorites(); sendCommand("listen 1"); String message = null; while (!terminate && (message = reader.readLine()) != null) { // Message is very long and frequent; only show when running at trace level logging logger.trace("Message received: {}", message); // Fix for some third-party apps that are sending "subscribe playlist" if (message.startsWith("listen 1") || message.startsWith("subscribe playlist")) { continue; } if (message.startsWith("players 0")) { handlePlayersList(message); } else if (message.startsWith("favorites")) { handleFavorites(message); } else { handlePlayerUpdate(message); } } if (message == null) { endOfStream = true; } } catch (IOException e) { if (!terminate) { logger.warn("failed to read line from squeeze server socket: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); scheduleReconnect(); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } reader = null; } } // check for end of stream from readLine if (endOfStream && !terminate) { logger.info("end of stream received from socket during readLine"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "end of stream on socket read"); scheduleReconnect(); } logger.debug("Squeeze Server listener exiting."); } private String decode(String raw) { try { return URLDecoder.decode(raw, UTF8_NAME); } catch (UnsupportedEncodingException e) { logger.debug("Failed to decode '{}' ", raw, e); return null; } } private String encode(String raw) { try { return URLEncoder.encode(raw, UTF8_NAME); } catch (UnsupportedEncodingException e) { logger.debug("Failed to encode '{}' ", raw, e); return null; } } private void handlePlayersList(String message) { // Split out players String[] playersList = message.split("playerindex\\S*\\s"); for (String playerParams : playersList) { // For each player, split out parameters and decode parameter String[] parameterList = playerParams.split("\\s"); for (int i = 0; i < parameterList.length; i++) { parameterList[i] = decode(parameterList[i]); } // parse out the MAC address first String macAddress = null; for (String parameter : parameterList) { if (parameter.contains("playerid")) { macAddress = parameter.substring(parameter.indexOf(":") + 1); break; } } // if none found then ignore this set of params if (macAddress == null) { continue; } final SqueezeBoxPlayer player = new SqueezeBoxPlayer(); player.setMacAddress(macAddress); // populate the player state for (String parameter : parameterList) { if (parameter.contains("ip")) { player.setIpAddr(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("uuid")) { player.setUuid(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("name")) { player.setName(parameter.substring(parameter.indexOf(":") + 1)); } else if (parameter.contains("model")) { player.setModel(parameter.substring(parameter.indexOf(":") + 1)); } } // Save player if we haven't seen it yet if (!players.containsKey(macAddress)) { players.put(macAddress, player); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.playerAdded(player); } }); // tell the server we want to subscribe to player updates sendCommand(player.getMacAddress() + " status - 1 subscribe:10 tags:yagJlNKjc"); } } } private void handlePlayerUpdate(String message) { String[] messageParts = message.split("\\s"); if (messageParts.length < 2) { logger.warn("Invalid message - expecting at least 2 parts. Ignoring."); return; } final String mac = decode(messageParts[0]); // get the message type String messageType = messageParts[1]; switch (messageType) { case "status": handleStatusMessage(mac, messageParts); break; case "playlist": handlePlaylistMessage(mac, messageParts); break; case "prefset": handlePrefsetMessage(mac, messageParts); break; case "mixer": handleMixerMessage(mac, messageParts); break; case "ir": final String ircode = messageParts[2]; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.irCodeChangeEvent(mac, ircode); } }); break; default: logger.trace("Unhandled player update message type '{}'.", messageType); } } private void handleMixerMessage(String mac, String[] messageParts) { if (messageParts.length < 4) { return; } String action = messageParts[2]; switch (action) { case "volume": String volumeStringValue = decode(messageParts[3]); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { try { int volume = Integer.parseInt(volumeStringValue); // Check if we received a relative volume change, or an absolute // volume value. if (volumeStringValue.contains("+") || (volumeStringValue.contains("-"))) { listener.relativeVolumeChangeEvent(mac, volume); } else { listener.absoluteVolumeChangeEvent(mac, volume); } } catch (NumberFormatException e) { logger.warn("Unable to parse volume [{}] received from mixer message.", volumeStringValue, e); } } }); break; default: logger.trace("Unhandled mixer message type '{}'", Arrays.toString(messageParts)); } } private void handleStatusMessage(final String mac, String[] messageParts) { String remoteTitle = "", artist = "", album = "", genre = "", year = ""; boolean coverart = false; String coverid = null; String artworkUrl = null; for (String messagePart : messageParts) { // Parameter Power if (messagePart.startsWith("power%3A")) { final boolean power = "1".matches(messagePart.substring("power%3A".length())); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.powerChangeEvent(mac, power); } }); } // Parameter Volume else if (messagePart.startsWith("mixer%20volume%3A")) { String value = messagePart.substring("mixer%20volume%3A".length()); final int volume = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.absoluteVolumeChangeEvent(mac, volume); } }); } // Parameter Mode else if (messagePart.startsWith("mode%3A")) { final String mode = messagePart.substring("mode%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.modeChangeEvent(mac, mode); } }); } // Parameter Playing Time else if (messagePart.startsWith("time%3A")) { String value = messagePart.substring("time%3A".length()); final int time = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlayingTimeEvent(mac, time); } }); } // Parameter duration else if (messagePart.startsWith("duration%3A")) { String value = messagePart.substring("duration%3A".length()); final int duration = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.durationEvent(mac, duration); } }); } // Parameter Playing Playlist Index else if (messagePart.startsWith("playlist_cur_index%3A")) { String value = messagePart.substring("playlist_cur_index%3A".length()); final int index = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistIndexEvent(mac, index); } }); } // Parameter Playlist Number Tracks else if (messagePart.startsWith("playlist_tracks%3A")) { String value = messagePart.substring("playlist_tracks%3A".length()); final int track = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.numberPlaylistTracksEvent(mac, track); } }); } // Parameter Playlist Repeat Mode else if (messagePart.startsWith("playlist%20repeat%3A")) { String value = messagePart.substring("playlist%20repeat%3A".length()); final int repeat = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistRepeatEvent(mac, repeat); } }); } // Parameter Playlist Shuffle Mode else if (messagePart.startsWith("playlist%20shuffle%3A")) { String value = messagePart.substring("playlist%20shuffle%3A".length()); final int shuffle = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.currentPlaylistShuffleEvent(mac, shuffle); } }); } // Parameter Title else if (messagePart.startsWith("title%3A")) { final String value = messagePart.substring("title%3A".length()); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.titleChangeEvent(mac, decode(value)); } }); } // Parameter Remote Title (radio) else if (messagePart.startsWith("remote_title%3A")) { remoteTitle = messagePart.substring("remote_title%3A".length()); } // Parameter Artist else if (messagePart.startsWith("artist%3A")) { artist = messagePart.substring("artist%3A".length()); } // Parameter Album else if (messagePart.startsWith("album%3A")) { album = messagePart.substring("album%3A".length()); } // Parameter Genre else if (messagePart.startsWith("genre%3A")) { genre = messagePart.substring("genre%3A".length()); } // Parameter Year else if (messagePart.startsWith("year%3A")) { year = messagePart.substring("year%3A".length()); } // Parameter artwork_url contains url to cover art else if (messagePart.startsWith("artwork_url%3A")) { artworkUrl = messagePart.substring("artwork_url%3A".length()); } // When coverart is "1" coverid will contain a unique coverart id else if (messagePart.startsWith("coverart%3A")) { coverart = "1".matches(messagePart.substring("coverart%3A".length())); } // Id for covert art (only valid when coverart is "1") else if (messagePart.startsWith("coverid%3A")) { coverid = messagePart.substring("coverid%3A".length()); } else { // Added to be able to see additional status message types logger.trace("Unhandled status message type '{}'", messagePart); } } final String finalUrl = constructCoverArtUrl(mac, coverart, coverid, artworkUrl); final String finalRemoteTitle = remoteTitle; final String finalArtist = artist; final String finalAlbum = album; final String finalGenre = genre; final String finalYear = year; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.coverArtChangeEvent(mac, finalUrl); listener.remoteTitleChangeEvent(mac, decode(finalRemoteTitle)); listener.artistChangeEvent(mac, decode(finalArtist)); listener.albumChangeEvent(mac, decode(finalAlbum)); listener.genreChangeEvent(mac, decode(finalGenre)); listener.yearChangeEvent(mac, decode(finalYear)); } }); } private String constructCoverArtUrl(String mac, boolean coverart, String coverid, String artwork_url) { String hostAndPort; if (StringUtils.isNotEmpty(userId)) { hostAndPort = "http://" + encode(userId) + ":" + encode(password) + "@" + host + ":" + webport; } else { hostAndPort = "http://" + host + ":" + webport; } // Default to using the convenience artwork URL (should be rare) String url = hostAndPort + "/music/current/cover.jpg?player=" + encode(mac); // If additional artwork info provided, use that instead if (coverart) { if (coverid != null) { // Typically is used to access cover art of local music files url = hostAndPort + "/music/" + coverid + "/cover.jpg"; } } else if (artwork_url != null) { if (artwork_url.startsWith("http")) { // Typically indicates that cover art is not local to LMS url = decode(artwork_url); } else if (artwork_url.startsWith("%2F")) { // Typically used for default coverart for plugins (e.g. Pandora, etc.) url = hostAndPort + decode(artwork_url); } else { // Another variation of default coverart for plugins (e.g. Pandora, etc.) url = hostAndPort + "/" + decode(artwork_url); } } return url; } private void handlePlaylistMessage(final String mac, String[] messageParts) { if (messageParts.length < 3) { return; } String action = messageParts[2]; String mode; if (action.equals("newsong")) { mode = "play"; // Set the track duration to 0 updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.durationEvent(mac, 0); } }); } else if (action.equals("pause")) { if (messageParts.length < 4) { return; } mode = messageParts[3].equals("0") ? "play" : "pause"; } else if (action.equals("stop")) { mode = "stop"; } else { // Added so that actions (such as delete, index, jump, open) are not treated as "play" logger.trace("Unhandled playlist message type '{}'", Arrays.toString(messageParts)); return; } final String value = mode; updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.modeChangeEvent(mac, value); } }); } private void handlePrefsetMessage(final String mac, String[] messageParts) { if (messageParts.length < 5) { return; } // server prefsets if (messageParts[2].equals("server")) { String function = messageParts[3]; String value = messageParts[4]; if (function.equals("power")) { final boolean power = value.equals("1"); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.powerChangeEvent(mac, power); } }); } else if (function.equals("volume")) { final int volume = (int) Double.parseDouble(value); updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.absoluteVolumeChangeEvent(mac, volume); } }); } } } private void handleFavorites(String message) { logger.trace("Handle favorites message: {}", message); String[] messageParts = message.split("\\s"); if (messageParts.length == 2 && "changed".equals(messageParts[1])) { // LMS informing us that favorites have changed; request an update to the favorites list requestFavorites(); return; } if (messageParts.length < 7) { logger.trace("No favorites in message."); return; } List<Favorite> favorites = new ArrayList<>(); Favorite f = null; for (String part : messageParts) { // Favorite ID (in form xxxxxxxxx.n) if (part.startsWith("id%3A")) { String id = part.substring("id%3A".length()); f = new Favorite(id); favorites.add(f); } // Favorite name else if (part.startsWith("name%3A")) { String name = decode(part.substring("name%3A".length())); if (f != null) { f.name = name; } } // When "1", favorite is a submenu with additional favorites else if (part.startsWith("hasitems%3A")) { boolean hasitems = "1".matches(part.substring("hasitems%3A".length())); if (f != null) { if (hasitems) { // Skip subfolders favorites.remove(f); f = null; } } } } updatePlayersFavoritesList(favorites); updateChannelFavoritesList(favorites); } private void updatePlayersFavoritesList(List<Favorite> favorites) { updatePlayer(new PlayerUpdateEvent() { @Override public void updateListener(SqueezeBoxPlayerEventListener listener) { listener.updateFavoritesListEvent(favorites); } }); } private void updateChannelFavoritesList(List<Favorite> favorites) { final Channel channel = getThing().getChannel(CHANNEL_FAVORITES_LIST); if (channel == null) { logger.debug("Channel {} doesn't exist. Delete & add thing to get channel.", CHANNEL_FAVORITES_LIST); return; } // Get channel config parameter indicating whether name should be wrapped with double quotes Boolean includeQuotes = Boolean.FALSE; if (channel.getConfiguration().containsKey(CHANNEL_CONFIG_QUOTE_LIST)) { includeQuotes = (Boolean) channel.getConfiguration().get(CHANNEL_CONFIG_QUOTE_LIST); } String quote = includeQuotes.booleanValue() ? "\"" : ""; StringBuilder sb = new StringBuilder(); for (Favorite favorite : favorites) { sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replaceAll(",", "")) .append(quote).append(","); } if (sb.length() == 0) { updateState(CHANNEL_FAVORITES_LIST, UnDefType.NULL); } else { // Drop the last comma sb.setLength(sb.length() - 1); String favoritesList = sb.toString(); logger.trace("Updating favorites channel for {} to state {}", getThing().getUID(), favoritesList); updateState(CHANNEL_FAVORITES_LIST, new StringType(favoritesList)); } } } /** * Interface to allow us to pass function call-backs to SqueezeBox Player * Event Listeners * * @author Dan Cunningham * */ interface PlayerUpdateEvent { void updateListener(SqueezeBoxPlayerEventListener listener); } /** * Update Listeners and child Squeeze Player Things * * @param event */ private void updatePlayer(PlayerUpdateEvent event) { // update listeners like disco services synchronized (squeezeBoxPlayerListeners) { for (SqueezeBoxPlayerEventListener listener : squeezeBoxPlayerListeners) { event.updateListener(listener); } } // update our children Bridge bridge = getThing(); List<Thing> things = bridge.getThings(); for (Thing thing : things) { ThingHandler handler = thing.getHandler(); if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) { event.updateListener((SqueezeBoxPlayerEventListener) handler); } } } /** * Adds a listener for player events * * @param squeezeBoxPlayerListener * @return */ public boolean registerSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) { logger.trace("Registering player listener"); return squeezeBoxPlayerListeners.add(squeezeBoxPlayerListener); } /** * Removes a listener from player events * * @param squeezeBoxPlayerListener * @return */ public boolean unregisterSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) { logger.trace("Unregistering player listener"); return squeezeBoxPlayerListeners.remove(squeezeBoxPlayerListener); } /** * Removed a player from our known list of players, will populate again if * player is seen * * @param mac */ public void removePlayerCache(String mac) { players.remove(mac); } /** * Schedule the server to try and reconnect */ private void scheduleReconnect() { logger.debug("scheduling squeeze server reconnect in {} seconds", RECONNECT_TIME); cancelReconnect(); reconnectFuture = scheduler.schedule(this::connect, RECONNECT_TIME, TimeUnit.SECONDS); } /** * Clears our reconnect job if exists */ private void cancelReconnect() { if (reconnectFuture != null) { reconnectFuture.cancel(true); } } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.el.3.0_fat/test-applications/TestEL3.0.war/src/com/ibm/ws/el30/fat/servlets/TestVariousLambdaExpression.java
9384
/******************************************************************************* * Copyright (c) 2015, 2018 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.el30.fat.servlets; import static org.junit.Assert.assertTrue; import javax.el.ELException; import javax.el.ELProcessor; import javax.el.LambdaExpression; import javax.servlet.annotation.WebServlet; import org.junit.Test; import com.ibm.ws.el30.fat.beans.Employee; import componenttest.app.FATServlet; /** * Servlet implementation class TestVariousLambdaExpression */ @WebServlet("/TestVariousLambdaExpression") public class TestVariousLambdaExpression extends FATServlet { private static final long serialVersionUID = 1L; private ELProcessor elp = new ELProcessor(); public TestVariousLambdaExpression() { super(); } @Test public void testLambdaParam() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("(x->x+1)"); int result = Integer.valueOf(expression.invoke("2").toString()); assertTrue("The expression did not evaluate to 3 : " + result, result == 3); } @Test public void testRejectExtraLambdaParam() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("x->x+1"); int result = Integer.valueOf(expression.invoke(2, 4).toString()); // extra param should be rejected assertTrue("The expression did not evaluate to 3: " + result, result == 3); } @Test public void testMultipleLambdaParams() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("((x,y)->x+y)"); int result = Integer.valueOf(expression.invoke(3, 4).toString()); assertTrue("The expression did not evaluate to 7: " + result, result == 7); } @Test public void testCatchExeptionOnLessParam() throws Exception { String expectedText = "Only [1] arguments were provided for a lambda expression that requires at least [2]"; LambdaExpression expression = (LambdaExpression) elp.eval("((x,y)->x+y)"); boolean result = false; String exceptionText = ""; try { expression.invoke(3).toString(); } catch (ELException elEx) { exceptionText = elEx.getMessage(); result = exceptionText.contains(expectedText); } assertTrue("The exception message did not contain: " + expectedText + " but was: " + exceptionText, result); } /** * Assigned Lambda expression * incr = x->x+1")).invoke(10) * * @throws Exception */ @Test public void testAssignedLambdaExp() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("incr = x->x+1"); int result = Integer.valueOf(expression.invoke(10).toString()); assertTrue("The expression did not evaluate to 11: " + result, result == 11); // ensure we can use the incr identifier that the lambda was assigned to result = Integer.valueOf(elp.eval("incr(11)").toString()); assertTrue("The expression did not evaluate to 12: " + result, result == 12); } /** * return the evaluated value not an expression * ()->64 * * @throws Exception */ @Test public void testNoParam() throws Exception { Integer result = Integer.valueOf(elp.eval("()->64").toString()); // will return the evaluated value not an expression assertTrue("The expression did not evaluate to 64: " + result, result == 64); } /** * The parenthesis is optional if and only if there is one parameter * "x->64"))).invoke(3) * * @throws Exception */ @Test public void testOptionalParenthesis() throws Exception { //The parenthesis is optional if and only if there is one parameter. LambdaExpression expression = (LambdaExpression) elp.eval("x->64"); Integer result = Integer.valueOf(expression.invoke(3).toString()); assertTrue("The expression did not evaluate to 64: " + result, result == 64); } /** * eval will return null as println returns void, but console should have Hello World. * ()->System.out.println(\"Hello World\") * * @throws Exception */ @Test public void testPrintFromBody() throws Exception { // eval will return null as println returns void, but console should have Hello World. Object result = elp.eval("()->System.out.println(\"Hello World\")"); assertTrue("The expression did not evaluate to null: " + result, result == null); } /** * parameters passed in ,invoked directly * ((x,y)->x+y)(3,4)) * * @throws Exception */ @Test public void testInvokeFunctionImmediate() throws Exception { Integer result = Integer.valueOf(elp.eval("((x,y)->x+y)(3,4)").toString()); // invoked assertTrue("The expression did not evaluate to 7: " + result, result == 7); } /** * parameters passed in ,invoked indirectly * v = (x,y)->x+y; v(3,4) * * @throws Exception */ @Test public void testInvokeFunctionIndirect() throws Exception { Integer result = Integer.valueOf(elp.eval("v = (x,y) ->x+y; v(3,4)").toString()); // invoked indirectly assertTrue("The expression did not evaluate to 7: " + result, result == 7); } /** * parameters passed in ,invoked indirectly and separate * t = (x,y)->x+y; * t(3,4) * * @throws Exception */ @Test public void testInvokeFunctionIndirectSeperate() throws Exception { elp.eval("t = (x,y)->x+y"); // Separate Integer result = Integer.valueOf(elp.eval("t(3,4)").toString()); assertTrue("The expression did not evaluate to 7: " + result, result == 7); } /** * * fact = n -> n==0? 1: n*fact(n-1); fact(5) * * @throws Exception */ @Test public void testInvokeFunctionIndirect2() throws Exception { Integer result = Integer.valueOf(elp.eval(" fact = n -> n==0? 1: n*fact(n-1); fact(5)").toString()); // should be 5*4*3*2*1 assertTrue("The expression did not evaluate to 120: " + result, result == 120); } /** * * employees.where(e->e.firstName == ‘Charlie’) * * @throws Exception */ @Test public void testPassedAsArgumentToMethod() throws Exception { elp.defineBean("employee", new Employee("Charlie Brown", "Charlie", "Brown")); String name = (String) elp.eval("employee.name"); assertTrue("The name expected is Charlie Brown but was: " + name, name.equals("Charlie Brown")); String result = (String) elp.eval("employee.sanitizeNames(e->e.firstname == 'Charlie')"); // // pass the Lambda as argument to method assertTrue("The result did not evaluate to NAME MATCHES: CHARLIE: " + result, result.equals("NAME MATCHES: Charlie")); } /** * * (elp.eval("(a1, a2) -> a1 > a2"))).invoke(2,3,4) * * @throws Exception */ @Test public void testCompareParameters() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("(a1, a2) -> a1 > a2"); Boolean result = (Boolean) expression.invoke(2, 3, 1); // also tests that the extra parameter is ignored assertTrue("The result did not evaluate to false: " + result.toString(), result.equals(false)); } /** * * (firstStr, secondStr)-> Integer.compare(firstStr.length(),secondStr.length())"))).invoke("First","Second") * should coerce to String * * @throws Exception */ @Test public void testParameterCoerceToString() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("(firstStr, secondStr)-> Integer.compare(firstStr.length(),secondStr.length())"); String result = expression.invoke("First", "Second").toString(); assertTrue("The result did not evaluate to -1: " + result, result.equals("-1")); } /** * * ( firstInt, secondInt)-> Integer.compare(firstInt,secondInt)"))).invoke(5,6) * should coerce to int * * @throws Exception */ @Test public void testParameterCoerceToInt() throws Exception { LambdaExpression expression = (LambdaExpression) elp.eval("( firstInt, secondInt)-> Integer.compare(firstInt,secondInt)"); String result = expression.invoke(5, 6).toString(); assertTrue("The result did not evaluate to -1: " + result, result.equals("-1")); } /** * ${parseMe = x -> (y -> (Integer.parseInt(y)))(x) + x ; parseMe("1234") * * @throws Exception */ @Test public void testNestedFunction1() throws Exception { String result = elp.eval("parseMe = x -> (y -> (Integer.parseInt(y)))(x) + x ; parseMe(\"1234\")").toString(); assertTrue("The result did not evaluate to 2468: " + result, result.equals("2468")); } }
epl-1.0
pecko/debrief
org.mwc.cmap.legacy/src/MWC/GUI/Shapes/Symbols/Vessels/TorpedoSym.java
810
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ package MWC.GUI.Shapes.Symbols.Vessels; public class TorpedoSym extends MissileSym { /** * */ private static final long serialVersionUID = 1L; // hey, we don't need to do anything, really public String getType() { return "Torpedo"; } }
epl-1.0
522986491/yangtools
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/DataContainerNode.java
1755
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.api.schema; import java.util.Collection; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; /** * * Abstract node which does not have value but contains valid {@link DataContainerChild} nodes. * * Schema of this node is described by instance of {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer}. * * <h2>Implementation notes</h2> * This interface should not be implemented directly, but rather implementing one of it's subclasses * <ul> * <li>{@link ContainerNode} * <li>{@link MapEntryNode} * <li>{@link UnkeyedListEntryNode} * <li>{@link ChoiceNode} * <li>{@link AugmentationNode} * </ul> * * @param <K> {@link PathArgument} which identifies instance of {@link DataContainerNode} */ public interface DataContainerNode<K extends PathArgument> extends // NormalizedNodeContainer<K, PathArgument, DataContainerChild<? extends PathArgument, ?>> { /** * Returns iteration of all child nodes * * Order of returned child nodes may be defined by subinterfaces. * * <b>Implementation Notes:</b> * <p> * All nodes returned in this iterable, MUST also be accessible via * {@link #getChild(PathArgument)} using their associated identifier. * * @return Iteration of all child nodes */ @Override Collection<DataContainerChild<? extends PathArgument, ?>> getValue(); }
epl-1.0
Mirage20/che
assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentModule.java
7260
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.wsagent.server; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.multibindings.MapBinder; import com.google.inject.name.Names; import org.eclipse.che.ApiEndpointAccessibilityChecker; import org.eclipse.che.EventBusURLProvider; import org.eclipse.che.UriApiEndpointProvider; import org.eclipse.che.UserTokenProvider; import org.eclipse.che.api.auth.oauth.OAuthTokenProvider; import org.eclipse.che.api.core.jsonrpc.JsonRpcRequestReceiver; import org.eclipse.che.api.core.jsonrpc.JsonRpcRequestTransmitter; import org.eclipse.che.api.core.jsonrpc.JsonRpcResponseReceiver; import org.eclipse.che.api.core.jsonrpc.JsonRpcResponseTransmitter; import org.eclipse.che.api.core.jsonrpc.impl.BasicJsonRpcObjectValidator; import org.eclipse.che.api.core.jsonrpc.impl.JsonRpcDispatcher; import org.eclipse.che.api.core.jsonrpc.impl.JsonRpcObjectValidator; import org.eclipse.che.api.core.jsonrpc.impl.WebSocketJsonRpcDispatcher; import org.eclipse.che.api.core.jsonrpc.impl.WebSocketJsonRpcRequestDispatcher; import org.eclipse.che.api.core.jsonrpc.impl.WebSocketJsonRpcRequestTransmitter; import org.eclipse.che.api.core.jsonrpc.impl.WebSocketJsonRpcResponseDispatcher; import org.eclipse.che.api.core.jsonrpc.impl.WebSocketJsonRpcResponseTransmitter; import org.eclipse.che.api.core.notification.WSocketEventBusClient; import org.eclipse.che.api.core.rest.ApiInfoService; import org.eclipse.che.api.core.rest.CoreRestModule; import org.eclipse.che.api.core.util.FileCleaner.FileCleanerModule; import org.eclipse.che.api.core.websocket.WebSocketMessageReceiver; import org.eclipse.che.api.core.websocket.WebSocketMessageTransmitter; import org.eclipse.che.api.core.websocket.impl.BasicWebSocketMessageTransmitter; import org.eclipse.che.api.core.websocket.impl.BasicWebSocketTransmissionValidator; import org.eclipse.che.api.core.websocket.impl.GuiceInjectorEndpointConfigurator; import org.eclipse.che.api.core.websocket.impl.WebSocketTransmissionValidator; import org.eclipse.che.api.git.GitConnectionFactory; import org.eclipse.che.api.git.GitUserResolver; import org.eclipse.che.api.git.LocalGitUserResolver; import org.eclipse.che.api.project.server.ProjectApiModule; import org.eclipse.che.api.ssh.server.HttpSshServiceClient; import org.eclipse.che.api.ssh.server.SshServiceClient; import org.eclipse.che.api.user.server.spi.PreferenceDao; import org.eclipse.che.commons.lang.Pair; import org.eclipse.che.git.impl.jgit.JGitConnectionFactory; import org.eclipse.che.inject.DynaModule; import org.eclipse.che.plugin.java.server.rest.WsAgentURLProvider; import org.eclipse.che.security.oauth.RemoteOAuthTokenProvider; import javax.inject.Named; import java.net.URI; /** * @author Evgen Vidolob */ @DynaModule public class WsAgentModule extends AbstractModule { @Override protected void configure() { bind(ApiInfoService.class); bind(PreferenceDao.class).to(org.eclipse.che.RemotePreferenceDao.class); bind(OAuthTokenProvider.class).to(RemoteOAuthTokenProvider.class); bind(SshServiceClient.class).to(HttpSshServiceClient.class); bind(org.eclipse.che.plugin.ssh.key.script.SshKeyProvider.class) .to(org.eclipse.che.plugin.ssh.key.script.SshKeyProviderImpl.class); install(new CoreRestModule()); install(new FileCleanerModule()); install(new ProjectApiModule()); install(new org.eclipse.che.swagger.deploy.DocsModule()); install(new org.eclipse.che.api.debugger.server.DebuggerModule()); install(new org.eclipse.che.commons.schedule.executor.ScheduleModule()); bind(GitUserResolver.class).to(LocalGitUserResolver.class); bind(GitConnectionFactory.class).to(JGitConnectionFactory.class); bind(URI.class).annotatedWith(Names.named("api.endpoint")).toProvider(UriApiEndpointProvider.class); bind(String.class).annotatedWith(Names.named("user.token")).toProvider(UserTokenProvider.class); bind(WSocketEventBusClient.class).asEagerSingleton(); bind(String.class).annotatedWith(Names.named("event.bus.url")).toProvider(EventBusURLProvider.class); bind(ApiEndpointAccessibilityChecker.class); bind(WsAgentAnalyticsAddresser.class); bind(String.class).annotatedWith(Names.named("wsagent.endpoint")) .toProvider(WsAgentURLProvider.class); configureJsonRpc(); configureWebSocket(); } //it's need for WSocketEventBusClient and in the future will be replaced with the property @Named("notification.client.event_subscriptions") @Provides @SuppressWarnings("unchecked") Pair<String, String>[] eventSubscriptionsProvider(@Named("event.bus.url") String eventBusURL) { return new Pair[]{Pair.of(eventBusURL, "")}; } //it's need for EventOriginClientPropagationPolicy and in the future will be replaced with the property @Named("notification.client.propagate_events") @Provides @SuppressWarnings("unchecked") Pair<String, String>[] propagateEventsProvider(@Named("event.bus.url") String eventBusURL) { return new Pair[]{Pair.of(eventBusURL, "")}; } private void configureWebSocket() { requestStaticInjection(GuiceInjectorEndpointConfigurator.class); bind(WebSocketTransmissionValidator.class).to(BasicWebSocketTransmissionValidator.class); bind(WebSocketMessageTransmitter.class).to(BasicWebSocketMessageTransmitter.class); MapBinder<String, WebSocketMessageReceiver> receivers = MapBinder.newMapBinder(binder(), String.class, WebSocketMessageReceiver.class); receivers.addBinding("jsonrpc-2.0").to(WebSocketJsonRpcDispatcher.class); } private void configureJsonRpc() { bind(JsonRpcObjectValidator.class).to(BasicJsonRpcObjectValidator.class); bind(JsonRpcResponseTransmitter.class).to(WebSocketJsonRpcResponseTransmitter.class); bind(JsonRpcRequestTransmitter.class).to(WebSocketJsonRpcRequestTransmitter.class); MapBinder<String, JsonRpcDispatcher> dispatchers = MapBinder.newMapBinder(binder(), String.class, JsonRpcDispatcher.class); dispatchers.addBinding("request").to(WebSocketJsonRpcRequestDispatcher.class); dispatchers.addBinding("response").to(WebSocketJsonRpcResponseDispatcher.class); MapBinder<String, JsonRpcRequestReceiver> requestReceivers = MapBinder.newMapBinder(binder(), String.class, JsonRpcRequestReceiver.class); MapBinder<String, JsonRpcResponseReceiver> responseReceivers = MapBinder.newMapBinder(binder(), String.class, JsonRpcResponseReceiver.class); } }
epl-1.0
bwollman/41_follow
src/main/java/ghm/follow/gui/Debug.java
1354
/* * Copyright (C) 2000-2003 Greg Merrill (greghmerrill@yahoo.com) * * This file is part of Follow (http://follow.sf.net). * * Follow is free software; you can redistribute it and/or modify it under the * terms of version 2 of the GNU General Public License as published by the Free * Software Foundation. * * Follow 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 * Follow; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package ghm.follow.gui; import ghm.follow.FollowApp; import java.awt.event.ActionEvent; import java.util.logging.Logger; /** * Perform an action for debugging. * * @author <a href="mailto:greghmerrill@yahoo.com">Greg Merrill</a> * @author Murali Krishnan */ public class Debug extends FollowAppAction { public static final String NAME = "debug"; private Logger log = Logger.getLogger(Debug.class.getName()); public Debug(FollowApp app) { super(app, "Debug", "U", "U", ActionContext.APP); } public void actionPerformed(ActionEvent e) { log.finer("Debug action."); } }
gpl-2.0
jimjonesbr/marc2geo
marc2geo/src/main/java/de/ulb/marc2geo/infrastructure/MySQLConnector.java
1027
package de.ulb.marc2geo.infrastructure; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.log4j.Logger; import de.ulb.marc2geo.core.GlobalSettings; public class MySQLConnector { private java.sql.Connection connect = null; private static Logger logger = Logger.getLogger("DataLoader"); public Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://"+GlobalSettings.getDatabaseHost()+"/"+GlobalSettings.getDatabaseName()+ "?user="+GlobalSettings.getDatabaseUser()+"&password="+GlobalSettings.getDatabasePassword()); //connect = DriverManager.getConnection("jdbc:mysql://giv-lodum.uni-muenster.de/transfer?user=jones&password="); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); logger.fatal("Error connecting to the database server >> " + e.getMessage()); } return connect; } }
gpl-2.0
acsid/stendhal
src/games/stendhal/server/entity/mapstuff/sign/ShopSignFactory.java
2716
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.server.entity.mapstuff.sign; // // import games.stendhal.server.core.config.factory.ConfigurableFactory; import games.stendhal.server.core.config.factory.ConfigurableFactoryContext; /** * A base factory for <code>ShopSign</code> objects. */ public class ShopSignFactory implements ConfigurableFactory { // // ShopSignFactory // /** * Extract the shop name from a context. * * @param ctx * The configuration context. Must provide 'shop'. * * @return The shop name. */ protected String getShop(final ConfigurableFactoryContext ctx) { return ctx.getRequiredString("shop"); } /** * Extract the sign title from a context. * * @param ctx * The configuration context. Must provide 'title'. * * @return The sign title. */ protected String getTitle(final ConfigurableFactoryContext ctx) { return ctx.getRequiredString("title"); } /** * Extract the selling/buying-type from a context. * * @param ctx * The configuration context. Must provide 'seller'. * * @return The sign title. */ private boolean getSeller(ConfigurableFactoryContext ctx) { // TODO: make this a required field return ctx.getBoolean("seller", true); } /** * Extract the caption from a context. * * @param ctx * The configuration context. May provide 'caption'. * * @return The sign title. */ private String getCaption(ConfigurableFactoryContext ctx) { return ctx.getString("caption", null); } // // ConfigurableFactory // /** * Create a shop sign. * * @param ctx * Configuration context. * * @return A ShopSign. * * @see ShopSign */ @Override public Object create(final ConfigurableFactoryContext ctx) { return new ShopSign(getShop(ctx), getTitle(ctx), getCaption(ctx), getSeller(ctx)); } }
gpl-2.0
BackupTheBerlios/arara-svn
core/trunk/src/main/java/net/indrix/arara/servlets/common/AbstractInitSearchServlet.java
4371
package net.indrix.arara.servlets.common; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.indrix.arara.dao.AbstractDAO; import net.indrix.arara.dao.DatabaseDownException; import net.indrix.arara.servlets.ServletConstants; import org.apache.log4j.Logger; public abstract class AbstractInitSearchServlet extends HttpServlet { protected static Logger logger = Logger.getLogger("net.indrix.aves"); /** * init method for InitSearchPhotosByUserServlet servlet */ public void init() { logger.debug("Initializing " + this.getClass()); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { List <String>erros = new ArrayList<String>(); RequestDispatcher dispatcher = null; ServletContext context = this.getServletContext(); String nextPage = req.getParameter(ServletConstants.NEXT_PAGE_KEY); String servletToCall = req.getParameter(ServletConstants.SERVLET_TO_CALL_KEY); String action = req.getParameter(ServletConstants.ACTION); String pageToShow = req.getParameter(ServletConstants.PAGE_TO_SHOW_KEY); HttpSession session = req.getSession(); logger.debug("Retrieving data..."); try { List list = getListOfData(getDao()); if ((list != null) && (!list.isEmpty())) { logger.debug("Setting data in request"); if ((list != null) && (!list.isEmpty())) { logger.debug("Data found... putting to session."); session.setAttribute(getListKeyToSession(), list); req.setAttribute(ServletConstants.SERVLET_TO_CALL_KEY, servletToCall); req.setAttribute(ServletConstants.ACTION, action); req.setAttribute(ServletConstants.PAGE_TO_SHOW_KEY, pageToShow); req.setAttribute(ServletConstants.NEXT_PAGE_KEY, nextPage); logger.debug(this.getClass() + " | " + servletToCall + " | " + action + " | " + pageToShow); } else { logger.debug("Data not found..."); erros.add(ServletConstants.DATABASE_ERROR); nextPage = ServletConstants.INITIAL_PAGE; } } else { logger.debug("Data not found..."); erros.add(ServletConstants.DATABASE_ERROR); nextPage = ServletConstants.INITIAL_PAGE; } } catch (DatabaseDownException e) { erros.add(ServletConstants.DATABASE_ERROR); nextPage = ServletConstants.INITIAL_PAGE; } catch (SQLException e) { erros.add(ServletConstants.DATABASE_ERROR); nextPage = ServletConstants.INITIAL_PAGE; } if (!erros.isEmpty()) { // coloca erros no request para registrar.jsp processar e apresentar // mensagem de erro req.setAttribute(ServletConstants.ERRORS_KEY, erros); // direciona usuário para página de registro novamente nextPage = ServletConstants.INITIAL_PAGE; } dispatcher = context.getRequestDispatcher(nextPage); dispatcher.forward(req, res); } /** * Retrieve the final list of data, to be put in session and used by view * * @return the final list of data, to be put in session and used by view */ protected abstract List getListOfData(AbstractDAO dao) throws DatabaseDownException, SQLException; /** * Retrieve the DAO to be used * @return */ protected abstract AbstractDAO getDao(); /** * The key to put the list of common names in session * * @return The key to put the list of common names in session */ protected abstract String getListKeyToSession(); }
gpl-2.0
makerbot/ReplicatorG
src/replicatorg/drivers/gen3/JettyEEPROM.java
6122
package replicatorg.drivers.gen3; class JettyG3EEPROM extends Sanguino3GEEPRPOM { final public static int VERSION_LOW = 0x0000; final public static int VERSION_HIGH = 0x0001; final public static int AXIS_INVERSION = 0x0002; final public static int ENDSTOP_INVERSION = 0x0003; final public static int MACHINE_NAME = 0x0020; final public static int AXIS_HOME_POSITIONS = 0x0060; final public static int ESTOP_CONFIGURATION = 0x0074; final public static int TOOL0_TEMP = 0x0080; final public static int TOOL1_TEMP = 0x0081; final public static int PLATFORM_TEMP = 0x0082; final public static int EXTRUDE_DURATION = 0x0083; final public static int EXTRUDE_MMS = 0x0084; final public static int MOOD_LIGHT_SCRIPT = 0x0085; final public static int MOOD_LIGHT_CUSTOM_RED = 0x0086; final public static int MOOD_LIGHT_CUSTOM_GREEN = 0x0087; final public static int MOOD_LIGHT_CUSTOM_BLUE = 0x0088; final public static int JOG_MODE_SETTINGS = 0x0089; final public static int BUZZER_REPEATS = 0x008A; final public static int STEPS_PER_MM_X = 0x008B; final public static int STEPS_PER_MM_Y = 0x0093; final public static int STEPS_PER_MM_Z = 0x009B; final public static int STEPS_PER_MM_A = 0x00A3; final public static int STEPS_PER_MM_B = 0x00AB; final public static int FILAMENT_USED = 0x00B3; final public static int FILAMENT_USED_TRIP = 0x00BB; final public static int ABP_COPIES = 0x00C3; final public static int PREHEAT_DURING_ESTIMATE = 0x00C4; final public static int OVERRIDE_GCODE_TEMP = 0x00C5; final public static int STEPPER_DRIVER = 0x0126; final public static int ACCEL_MAX_FEEDRATE_X = 0x0127; final public static int ACCEL_MAX_FEEDRATE_Y = 0x012B; final public static int ACCEL_MAX_FEEDRATE_Z = 0x012F; final public static int ACCEL_MAX_FEEDRATE_A = 0x0133; final public static int ACCEL_MAX_FEEDRATE_B = 0x0137; final public static int ACCEL_MAX_ACCELERATION_X = 0x013B; final public static int ACCEL_MAX_ACCELERATION_Y = 0x013F; final public static int ACCEL_MAX_ACCELERATION_Z = 0x0143; final public static int ACCEL_MAX_ACCELERATION_A = 0x0147; final public static int ACCEL_MAX_EXTRUDER_NORM = 0x014B; final public static int ACCEL_MAX_EXTRUDER_RETRACT = 0x014F; final public static int ACCEL_E_STEPS_PER_MM = 0x0153; final public static int ACCEL_MIN_FEED_RATE = 0x0157; final public static int ACCEL_MIN_TRAVEL_FEED_RATE = 0x015B; final public static int ACCEL_ADVANCE_K2 = 0x015F; final public static int ACCEL_MIN_PLANNER_SPEED = 0x0163; final public static int ACCEL_ADVANCE_K = 0x0167; final public static int ACCEL_NOODLE_DIAMETER = 0x016B; final public static int ACCEL_MIN_SEGMENT_TIME = 0x016F; final public static int LCD_TYPE = 0x0173; final public static int ENDSTOPS_USED = 0x0174; final public static int HOMING_FEED_RATE_X = 0x0175; final public static int HOMING_FEED_RATE_Y = 0x0179; final public static int HOMING_FEED_RATE_Z = 0x017D; final public static int ACCEL_REV_MAX_FEED_RATE = 0x0181; final public static int ACCEL_EXTRUDER_DEPRIME = 0x0185; final public static int ACCEL_SLOWDOWN_LIMIT = 0x0189; final public static int ACCEL_CLOCKWISE_EXTRUDER = 0x018D; final public static int INVERTED_EXTRUDER_5D = 0x0191; final public static int ACCEL_MAX_SPEED_CHANGE_X = 0x0192; final public static int ACCEL_MAX_SPEED_CHANGE_Y = 0x0196; final public static int ACCEL_MAX_SPEED_CHANGE_Z = 0x019A; final public static int ACCEL_MAX_SPEED_CHANGE_A = 0x019E; final public static int RAM_USAGE_DEBUG = 0x01D0; } class SailfishEEPROM extends JettyG3EEPROM { final public static int SLOWDOWN_FLAG = 0x0189; final public static int ACCEL_MAX_SPEED_CHANGE_B = 0x01A2; final public static int ACCEL_MAX_ACCELERATION_B = 0x01A6; final public static int ACCEL_EXTRUDER_DEPRIME_B = 0x01AA; final public static int TOOL_COUNT = 0x01AE; final public static int TOOLHEAD_OFFSET_SETTINGS = 0x01B0; final public static int AXIS_LENGTHS = 0x01BC; final public static int FILAMENT_LIFETIME_B = 0x01D4; final public static int DITTO_PRINT_ENABLED = 0x01DC; final public static int VID_PID_INFO = 0x01E5; final public static int EXTRUDER_HOLD = 0x01E9; } class JettyMBEEPROM extends Sanguino3GEEPRPOM { final public static int ACCELERATION_STATE = 0x023E; final public static int BOT_STATUS_BYTES = 0x018A; final public static int AXIS_LENGTHS = 0x018C; final public static int AXIS_STEPS_PER_MM = 0x01A0; final public static int FILAMENT_LIFETIME = 0x01B4; final public static int FILAMENT_TRIP = 0x01C4; final public static int PROFILES_BASE = 0x01D5; final public static int PROFILES_INIT = 0x023D; final public static int MAX_ACCELERATION_AXIS = 0x0240; final public static int MAX_ACCELERATION_NORMAL_MOVE = 0x024A; final public static int MAX_ACCELERATION_EXTRUDER_MOVE = 0x024C; final public static int MAX_SPEED_CHANGE = 0x024E; final public static int JKN_ADVANCE_K = 0x0258; final public static int JKN_ADVANCE_K2 = 0x025C; final public static int EXTRUDER_DEPRIME_STEPS = 0x0260; final public static int SLOWDOWN_FLAG = 0x0264; final public static int DEFAULTS_FLAG = 0x0265; final public static int FUTURE_USE = 0x0266; final public static int AXIS_MAX_FEEDRATES = 0x027A; final public static int OVERRIDE_GCODE_TEMP = 0x0FFD; final public static int HEAT_DURING_PAUSE = 0x0FFE; }
gpl-2.0
UNColombia/2019766-1-BOG-2015-2
java/HAeA/src/unalcol/clone/Clone.java
1277
package unalcol.clone; import unalcol.reflect.util.*; /** * <p>ServiceProvider of cloning methods.</p> * <p>Copyright: Copyright (c) 2010</p> * * @author Jonatan Gomez Perdomo * @version 1.0 */ public class Clone{ protected static boolean wrapperLoaded = false; /** * Gets the current cloning service for the given object * @param obj Object from which the CloneService will be retrieved * @return A CloneService if some cloning service has been defined as current * cloning service for the given object, <i>null</i> otherwise */ public static CloneService getService( Object obj ){ if( !wrapperLoaded ){ wrapperLoaded = ReflectUtil.getProvider().register(CloneServiceWrapper.class); } return ((CloneService)ReflectUtil.getProvider().default_service(CloneService.class,obj)); } /** * Creates a clone of a given object * @param obj Object to be cloned * @return A clone of the object, if a cloning service is available for the given object, <i>null</i> otherwise */ public static Object get( Object obj ){ CloneService service = getService(obj); if( service != null ){ return service.clone(obj); } return null; } }
gpl-2.0
CaptainSly/tiled-java
src/tiled/mapeditor/undo/ChangePropertiesEdit.java
1488
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tiled.mapeditor.undo; import java.util.Properties; import javax.swing.undo.AbstractUndoableEdit; import tiled.mapeditor.Resources; /** * * @author upachler */ public class ChangePropertiesEdit extends AbstractUndoableEdit { private boolean undone = false; private Properties backupProperties; private Properties properties; /// creates a new edit that stores a backup of the layer's old Properties /// object. Note that this object needs to be a clone of the the layer's /// property object in its state before the edit was performed. public ChangePropertiesEdit(Properties properties, Properties oldPropertiesCopy) { backupProperties = oldPropertiesCopy; this.properties = properties; } public void undo(){ super.undo(); assert !undone; swapProperties(); undone = true; } public void redo(){ super.redo(); assert undone; swapProperties(); undone = false; } private void swapProperties() { Properties newBackupProperties = (Properties) properties.clone(); properties.clear(); properties.putAll(backupProperties); backupProperties = newBackupProperties; } @Override public String getPresentationName() { return Resources.getString("edit.changeproperties.name"); } }
gpl-2.0
spencerjackson/fred-staging
src/freenet/node/NodeCryptoConfig.java
10903
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.node; import java.net.UnknownHostException; import freenet.config.InvalidConfigValueException; import freenet.config.NodeNeedRestartException; import freenet.config.SubConfig; import freenet.io.comm.FreenetInetAddress; import freenet.node.SecurityLevels.FRIENDS_THREAT_LEVEL; import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL; import freenet.support.Logger; import freenet.support.api.BooleanCallback; import freenet.support.api.IntCallback; import freenet.support.api.StringCallback; /** * Tracks config parameters related to a NodeCrypto. The NodeCrypto may or may not exist. If it exists, * parameter changes are passed on to it, if it doesn't, they can be changed trivially. * * Allows users to set the opennet port number while opennet is disabled, enable opennet on the fly etc. * @author toad */ public class NodeCryptoConfig { /** Port number. -1 = choose a random available port number at activation time. */ private int portNumber; /** Bind address. 0.0.0.0 = all addresses. */ private FreenetInetAddress bindTo; /** If nonzero, 1/dropProbability = probability of UdpSocketHandler dropping a packet (for debugging * purposes; not static as we may need to simulate some nodes with more loss than others). */ private int dropProbability; /** The NodeCrypto, if there is one */ private NodeCrypto crypto; /** Whether we should prevent multiple connections to the same IP (taking into account other * NodeCrypto's - this will usually be set for opennet but not for darknet). */ private boolean oneConnectionPerAddress; /** If true, we will allow to connect to nodes via local (LAN etc) IP addresses, * regardless of any per-peer setting. */ private boolean alwaysAllowLocalAddresses; /** If true, assume we are NATed regardless of the evidence, and therefore always send * aggressive handshakes (every 10-30 seconds). */ private boolean assumeNATed; /** If true, include local addresses on noderefs */ public boolean includeLocalAddressesInNoderefs; /** If false we won't make any effort do disguise the length of packets */ private boolean paddDataPackets; NodeCryptoConfig(SubConfig config, int sortOrder, boolean isOpennet, SecurityLevels securityLevels) throws NodeInitException { config.register("listenPort", -1 /* means random */, sortOrder++, true, true, "Node.port", "Node.portLong", new IntCallback() { @Override public Integer get() { synchronized(NodeCryptoConfig.class) { if(crypto != null) portNumber = crypto.portNumber; return portNumber; } } @Override public void set(Integer val) throws InvalidConfigValueException { if(portNumber < -1 || portNumber == 0 || portNumber > 65535) { throw new InvalidConfigValueException("Invalid port number"); } synchronized(NodeCryptoConfig.class) { if(portNumber == val) return; // FIXME implement on the fly listenPort changing // Note that this sort of thing should be the exception rather than the rule!!!! if(crypto != null) throw new InvalidConfigValueException("Switching listenPort on the fly not yet supported"); portNumber = val; } } @Override public boolean isReadOnly() { return true; } }, false); try{ portNumber = config.getInt("listenPort"); }catch (Exception e){ // FIXME is this really necessary? Logger.error(this, "Caught "+e, e); System.err.println(e); e.printStackTrace(); portNumber = -1; } config.register("bindTo", "0.0.0.0", sortOrder++, true, true, "Node.bindTo", "Node.bindToLong", new NodeBindtoCallback()); try { bindTo = new FreenetInetAddress(config.getString("bindTo"), false); } catch (UnknownHostException e) { throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_BIND_USM, "Invalid bindTo: "+config.getString("bindTo")); } config.register("testingDropPacketsEvery", 0, sortOrder++, true, false, "Node.dropPacketEvery", "Node.dropPacketEveryLong", new IntCallback() { @Override public Integer get() { synchronized(NodeCryptoConfig.this) { return dropProbability; } } @Override public void set(Integer val) throws InvalidConfigValueException { if(val < 0) throw new InvalidConfigValueException("testingDropPacketsEvery must not be negative"); synchronized(NodeCryptoConfig.this) { if(val == dropProbability) return; dropProbability = val; if(crypto == null) return; } crypto.onSetDropProbability(val); } }, false); dropProbability = config.getInt("testingDropPacketsEvery"); config.register("oneConnectionPerIP", isOpennet, sortOrder++, true, false, "Node.oneConnectionPerIP", "Node.oneConnectionPerIPLong", new BooleanCallback() { @Override public Boolean get() { synchronized(NodeCryptoConfig.this) { return oneConnectionPerAddress; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(NodeCryptoConfig.this) { oneConnectionPerAddress = val; } } }); oneConnectionPerAddress = config.getBoolean("oneConnectionPerIP"); if(isOpennet) { securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { // Might be useful for nodes on the same NAT etc, so turn it off for LOW. Otherwise is sensible. // It's always off on darknet, since we can reasonably expect to know our peers, even if we are paranoid // about them! if(newLevel == NETWORK_THREAT_LEVEL.LOW) oneConnectionPerAddress = false; if(oldLevel == NETWORK_THREAT_LEVEL.LOW) oneConnectionPerAddress = true; } }); } config.register("alwaysAllowLocalAddresses", !isOpennet, sortOrder++, true, false, "Node.alwaysAllowLocalAddresses", "Node.alwaysAllowLocalAddressesLong", new BooleanCallback() { @Override public Boolean get() { synchronized(NodeCryptoConfig.this) { return alwaysAllowLocalAddresses; } } @Override public void set(Boolean val) throws InvalidConfigValueException { synchronized(NodeCryptoConfig.this) { alwaysAllowLocalAddresses = val; } } }); alwaysAllowLocalAddresses = config.getBoolean("alwaysAllowLocalAddresses"); if(!isOpennet) { securityLevels.addFriendsThreatLevelListener(new SecurityLevelListener<FRIENDS_THREAT_LEVEL>() { public void onChange(FRIENDS_THREAT_LEVEL oldLevel, FRIENDS_THREAT_LEVEL newLevel) { if(newLevel == FRIENDS_THREAT_LEVEL.HIGH) alwaysAllowLocalAddresses = false; if(oldLevel == FRIENDS_THREAT_LEVEL.HIGH) alwaysAllowLocalAddresses = false; } }); } config.register("assumeNATed", true, sortOrder++, true, true, "Node.assumeNATed", "Node.assumeNATedLong", new BooleanCallback() { @Override public Boolean get() { return assumeNATed; } @Override public void set(Boolean val) throws InvalidConfigValueException { assumeNATed = val; } }); assumeNATed = config.getBoolean("assumeNATed"); // Include local IPs in noderef file config.register("includeLocalAddressesInNoderefs", !isOpennet, sortOrder++, true, false, "NodeIPDectector.inclLocalAddress", "NodeIPDectector.inclLocalAddressLong", new BooleanCallback() { @Override public Boolean get() { return includeLocalAddressesInNoderefs; } @Override public void set(Boolean val) throws InvalidConfigValueException { includeLocalAddressesInNoderefs = val; } }); includeLocalAddressesInNoderefs = config.getBoolean("includeLocalAddressesInNoderefs"); // enable/disable Padding of outgoing packets (won't affect auth-packets) config.register("paddDataPackets", true, sortOrder++, true, false, "Node.paddDataPackets", "Node.paddDataPacketsLong", new BooleanCallback() { @Override public Boolean get() { return paddDataPackets; } @Override public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException { if (val.equals(get())) return; paddDataPackets = val; } }); paddDataPackets = config.getBoolean("paddDataPackets"); securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() { public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) { // Might be useful for nodes which are running with a tight bandwidth quota to minimize the overhead, // so turn it off for LOW. Otherwise is sensible. if(newLevel == NETWORK_THREAT_LEVEL.LOW) paddDataPackets = false; if(oldLevel == NETWORK_THREAT_LEVEL.LOW) paddDataPackets = true; } }); } /** The number of config options i.e. the amount to increment sortOrder by */ public static final int OPTION_COUNT = 3; synchronized void starting(NodeCrypto crypto2) { if(crypto != null) throw new IllegalStateException("Replacing existing NodeCrypto "+crypto+" with "+crypto2); crypto = crypto2; } synchronized void started(NodeCrypto crypto2) { if(crypto != null) throw new IllegalStateException("Replacing existing NodeCrypto "+crypto+" with "+crypto2); } synchronized void maybeStarted(NodeCrypto crypto2) { } synchronized void stopping(NodeCrypto crypto2) { crypto = null; } public synchronized int getPort() { return portNumber; } class NodeBindtoCallback extends StringCallback { @Override public String get() { return bindTo.toString(); } @Override public void set(String val) throws InvalidConfigValueException { if(val.equals(get())) return; // FIXME why not? Can't we use freenet.io.NetworkInterface like everywhere else, just adapt it for UDP? throw new InvalidConfigValueException("Cannot be updated on the fly"); } @Override public boolean isReadOnly() { return true; } } public synchronized FreenetInetAddress getBindTo() { return bindTo; } public synchronized void setPort(int port) { portNumber = port; } public synchronized int getDropProbability() { return dropProbability; } public synchronized boolean oneConnectionPerAddress() { return oneConnectionPerAddress; } public synchronized boolean alwaysAllowLocalAddresses() { return alwaysAllowLocalAddresses; } public boolean alwaysHandshakeAggressively() { return assumeNATed; } public boolean includeLocalAddressesInNoderefs() { return includeLocalAddressesInNoderefs; } public boolean paddDataPackets() { return paddDataPackets; } }
gpl-2.0
Teameeting/Teameeting-MsgServer
MsgServerClientSdk/SdkMsgClientAndroid/sdkmsgclient/src/main/java/org/dync/teameeting/sdkmsgclient/msgs/MSSqlite.java
5488
package org.dync.teameeting.sdkmsgclient.msgs; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.HashMap; /** * Created by hp on 7/11/16. */ public class MSSqlite { private static SqliteDbHelper mSql3Db = null; public MSSqlite(Context context) { mSql3Db = new SqliteDbHelper(context); } public boolean OpenDb() { return true; } public boolean CloseDb() { return true; } public boolean IsUserExistsInDb(String userId, String seqnId) { SQLiteDatabase db = mSql3Db.getReadableDatabase(); String sqlSelect = "select count(*) from " + SqliteDbHelper.MS_TABLE_STOREID_SEQN + " where userId='" + userId + "' and seqnId='" + seqnId +"';" ; Cursor cursor = db.rawQuery(sqlSelect, null); int code = 0; if (cursor.moveToFirst()) { do { code = cursor.getInt(0); } while(cursor.moveToNext()); } boolean exist = ((code==0)?false:true); cursor.close(); db.close(); return exist; } public boolean InsertSeqn(String userId, String seqnId, long seqn) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); ContentValues value = new ContentValues(); value.put("userId", userId); value.put("seqnId", seqnId); value.put("seqn", seqn); value.put("isfetched", 0); db.insert(SqliteDbHelper.MS_TABLE_STOREID_SEQN, null, value); db.close(); return true; } public boolean UpdateSeqn(String userId, String seqnId, long seqn) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); ContentValues value = new ContentValues(); value.put("seqn", seqn); db.update(SqliteDbHelper.MS_TABLE_STOREID_SEQN, value, "userId=? and seqnId=?", new String[]{userId, seqnId}); db.close(); return true; } public boolean UpdateSeqn(String userId, String seqnId, long seqn, int isFetched) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); ContentValues value = new ContentValues(); value.put("seqn", seqn); value.put("isfetched", isFetched); db.update(SqliteDbHelper.MS_TABLE_STOREID_SEQN, value, "userId=? and seqnId=?", new String[]{userId, seqnId}); db.close(); return true; } public long SelectSeqn(String userId, String seqnId) { SQLiteDatabase db = mSql3Db.getReadableDatabase(); String sqlSelect = "select seqn from " + SqliteDbHelper.MS_TABLE_STOREID_SEQN + " where userId='" + userId + "' and seqnId='" + seqnId +"';" ; Cursor cursor = db.rawQuery(sqlSelect, null); long code = -1; if (cursor.moveToFirst()) { do { code = cursor.getLong(0); } while(cursor.moveToNext()); } cursor.close(); db.close(); return code; } public boolean DeleteSeqn(String userId, String seqnId) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); db.delete(SqliteDbHelper.MS_TABLE_STOREID_SEQN, "userId=? and seqnId=?", new String[]{userId, seqnId}); db.close(); return true; } public boolean InsertGroupId(String userId, String grpId) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); ContentValues value = new ContentValues(); value.put("userId", userId); value.put("seqnId", grpId); db.insert(SqliteDbHelper.MS_TABLE_GROUPS_ID, null, value); db.close(); return true; } public boolean IsGroupExistsInDb(String userId, String groupId) { SQLiteDatabase db = mSql3Db.getReadableDatabase(); String sqlSelect = "select count(*) from " + SqliteDbHelper.MS_TABLE_GROUPS_ID + " where userId='" + userId + "' and seqnId='" + groupId +"';" ; Cursor cursor = db.rawQuery(sqlSelect, null); int code = 0; if (cursor.moveToFirst()) { do { code = cursor.getInt(0); } while(cursor.moveToNext()); } boolean exist = ((code==0)?false:true); cursor.close(); db.close(); return exist; } public ArrayList<GroupInfo> SelectGroupInfo(String userId) { SQLiteDatabase db = mSql3Db.getReadableDatabase(); String sqlSelect = "select * from " + SqliteDbHelper.MS_TABLE_STOREID_SEQN +" where userId='" + userId + "';" ; Cursor cursor = db.rawQuery(sqlSelect, null); ArrayList<GroupInfo> arrInfo = new ArrayList<GroupInfo> (); if (cursor.moveToFirst()) { do { HashMap<String, String> in = new HashMap<String, String>(); GroupInfo gi = new GroupInfo(); gi.setmUserId(cursor.getString(0)); gi.setmSeqnId(cursor.getString(1)); gi.setmSeqn(cursor.getLong(2)); gi.setmIsFetched(cursor.getInt(3)); arrInfo.add(gi); } while(cursor.moveToNext()); } cursor.close(); db.close(); return arrInfo; } public boolean DeleteGroupId(String userId, String grpId) { SQLiteDatabase db = mSql3Db.getWritableDatabase(); db.delete(SqliteDbHelper.MS_TABLE_GROUPS_ID, "userId=? and seqnId=?", new String[]{userId, grpId}); db.close(); return true; } }
gpl-2.0
buiduchuy/fts-g1-fuhcm
Code/Website/src/vn/edu/fpt/fts/dao/OrderDAO.java
11502
/** * */ package vn.edu.fpt.fts.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import vn.edu.fpt.fts.common.Common; import vn.edu.fpt.fts.common.DBAccess; import vn.edu.fpt.fts.pojo.DealOrder; import vn.edu.fpt.fts.pojo.Order; /** * @author Huy * */ public class OrderDAO { private final static String TAG = "OrderDAO"; public int insertOrder(Order bean) { Connection con = null; PreparedStatement stmt = null; int ret = 0; try { con = DBAccess.makeConnection(); String sql = "INSERT INTO [Order] ( " + "Price," + "CreateTime," + "OrderStatusID," + "Active" + ") VALUES (" + "?, " + "?, " + "?, " + "?)"; stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); int i = 1; stmt.setDouble(i++, bean.getPrice()); // Price stmt.setString(i++, bean.getCreateTime()); // CreateTime stmt.setInt(i++, bean.getOrderStatusID()); // OrderStatusID stmt.setInt(i++, Common.activate); // Active stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); if (rs != null && rs.next()) { ret = (int) rs.getLong(1); } } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); System.out.println("Can't insert to Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return ret; } public int updateOrder(Order bean) { Connection con = null; PreparedStatement stmt = null; int ret = 0; try { con = DBAccess.makeConnection(); String sql = "UPDATE [Order] SET " + " Price = ?," + " CreateTime = ?," + " OrderStatusID = ?," + " Active = ? " + " WHERE OrderID = '" + bean.getOrderID() + "' "; stmt = con.prepareStatement(sql); int i = 1; stmt.setDouble(i++, bean.getPrice()); // Price stmt.setString(i++, bean.getCreateTime()); // CreateTime stmt.setInt(i++, bean.getOrderStatusID()); // OrderStatusID stmt.setInt(i++, bean.getActive()); // Active ret = stmt.executeUpdate(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); System.out.println("Can't update to Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return ret; } public int updateOrderStatusID(int orderID, int orderStatusID) { Connection con = null; PreparedStatement stmt = null; int ret = 0; try { con = DBAccess.makeConnection(); String sql = "UPDATE [Order] SET " + " OrderStatusID = ?" + " WHERE OrderID = '" + orderID + "' "; stmt = con.prepareStatement(sql); int i = 1; stmt.setInt(i++, orderStatusID); // OrderStatusID ret = stmt.executeUpdate(); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); System.out.println("Can't update OrderStatusID to Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return ret; } public Order getOrderByID(int orderID) { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = DBAccess.makeConnection(); String sql = "SELECT * FROM [Order] WHERE OrderID=?"; stm = con.prepareStatement(sql); int i = 1; stm.setInt(i++, orderID); rs = stm.executeQuery(); DealOrderDAO dealOrderDao = new DealOrderDAO(); DealDAO dealDao = new DealDAO(); DealOrder dealOrder = new DealOrder(); Order order; while (rs.next()) { order = new Order(); order.setOrderID(rs.getInt("OrderID")); order.setPrice(rs.getDouble("Price")); order.setCreateTime(rs.getString("CreateTime")); order.setOrderStatusID(rs.getInt("OrderStatusID")); order.setActive(rs.getInt("Active")); dealOrder = dealOrderDao.getDealOrderByOrderID(rs .getInt("OrderID")); order.setDeal(dealDao.getDealByID(dealOrder.getDealID())); return order; } } catch (SQLException e) { e.printStackTrace(); System.out.println("Can't load data from Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return null; } public List<Order> getAllOrder() { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = DBAccess.makeConnection(); String sql = "SELECT * FROM [Order]"; stm = con.prepareStatement(sql); rs = stm.executeQuery(); DealOrderDAO dealOrderDao = new DealOrderDAO(); DealDAO dealDao = new DealDAO(); DealOrder dealOrder = new DealOrder(); Order order; List<Order> list = new ArrayList<Order>(); while (rs.next()) { order = new Order(); order.setOrderID(rs.getInt("OrderID")); order.setPrice(rs.getDouble("Price")); order.setCreateTime(rs.getString("CreateTime")); order.setOrderStatusID(rs.getInt("OrderStatusID")); order.setActive(rs.getInt("Active")); dealOrder = dealOrderDao.getDealOrderByOrderID(rs .getInt("OrderID")); if (dealOrder != null) { order.setDeal(dealDao.getDealByID(dealOrder.getDealID())); } list.add(order); } return list; } catch (SQLException e) { e.printStackTrace(); System.out.println("Can't load data from Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return null; } public List<Order> getTop10Order() { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = DBAccess.makeConnection(); String sql = "SELECT TOP 10 * FROM [Order] ORDER BY OrderID DESC"; stm = con.prepareStatement(sql); rs = stm.executeQuery(); DealOrderDAO dealOrderDao = new DealOrderDAO(); DealDAO dealDao = new DealDAO(); DealOrder dealOrder = new DealOrder(); Order order; List<Order> list = new ArrayList<Order>(); while (rs.next()) { order = new Order(); order.setOrderID(rs.getInt("OrderID")); order.setPrice(rs.getDouble("Price")); order.setCreateTime(rs.getString("CreateTime")); order.setOrderStatusID(rs.getInt("OrderStatusID")); order.setActive(rs.getInt("Active")); dealOrder = dealOrderDao.getDealOrderByOrderID(rs .getInt("OrderID")); if (dealOrder != null) { order.setDeal(dealDao.getDealByID(dealOrder.getDealID())); } list.add(order); } return list; } catch (SQLException e) { e.printStackTrace(); System.out.println("Can't load data from Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return null; } public Order getOrderByGoodsID(int goodsID) { OrderDAO orderDao = new OrderDAO(); List<Order> list = new ArrayList<Order>(); Order order = new Order(); list = orderDao.getAllOrder(); for (int i = 0; i < list.size(); i++) { if (list.get(i).getDeal() != null) { if (list.get(i).getDeal().getGoodsID() == goodsID) order = list.get(i); } } return order; } public List<Order> getOrderByOwnerID(int ownerID) { OrderDAO orderDao = new OrderDAO(); List<Order> list = new ArrayList<Order>(); List<Order> listOrder = new ArrayList<Order>(); list = orderDao.getAllOrder(); if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getDeal() != null) { if (list.get(i).getDeal().getGoods() != null) { if (list.get(i).getDeal().getGoods().getOwnerID() == ownerID) { listOrder.add(list.get(i)); } } } } } return listOrder; } public List<Order> getOrderByDriverID(int driverID) { OrderDAO orderDao = new OrderDAO(); List<Order> list = new ArrayList<Order>(); List<Order> listOrder = new ArrayList<Order>(); list = orderDao.getAllOrder(); if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i).getDeal() != null) { if (list.get(i).getDeal().getRoute() != null) { if (list.get(i).getDeal().getRoute().getDriverID() == driverID) { listOrder.add(list.get(i)); } } } } } return listOrder; } public List<Order> searchOrderByID(int orderID) { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = DBAccess.makeConnection(); String sql = "SELECT * FROM [Order] WHERE OrderID LIKE '%' + REPLACE(?, '%', '[%]') + '%'"; stm = con.prepareStatement(sql); int i = 1; stm.setInt(i++, orderID); rs = stm.executeQuery(); DealOrderDAO dealOrderDao = new DealOrderDAO(); DealDAO dealDao = new DealDAO(); DealOrder dealOrder = new DealOrder(); Order order; List<Order> list = new ArrayList<Order>(); while (rs.next()) { order = new Order(); order.setOrderID(rs.getInt("OrderID")); order.setPrice(rs.getDouble("Price")); order.setCreateTime(rs.getString("CreateTime")); order.setOrderStatusID(rs.getInt("OrderStatusID")); order.setActive(rs.getInt("Active")); dealOrder = dealOrderDao.getDealOrderByOrderID(rs .getInt("OrderID")); if (dealOrder != null) { order.setDeal(dealDao.getDealByID(dealOrder.getDealID())); } list.add(order); } return list; } catch (SQLException e) { e.printStackTrace(); System.out.println("Can't load data from Order table"); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } finally { try { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); Logger.getLogger(TAG).log(Level.SEVERE, null, e); } } return null; } }
gpl-2.0
Fakkar/TeligramFars
TMessagesProj/src/main/java/com/teligramfars/messenger/audioinfo/mp3/MP3Info.java
8724
/* * Copyright 2013-2014 Odysseus Software GmbH * * 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.pouyadr.messenger.audioinfo.mp3; import org.pouyadr.messenger.audioinfo.AudioInfo; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; public class MP3Info extends AudioInfo { static final Logger LOGGER = Logger.getLogger(MP3Info.class.getName()); interface StopReadCondition { boolean stopRead(MP3Input data) throws IOException; } public MP3Info(InputStream input, long fileLength) throws IOException, ID3v2Exception, MP3Exception { this(input, fileLength, Level.FINEST); } public MP3Info(InputStream input, final long fileLength, Level debugLevel) throws IOException, ID3v2Exception, MP3Exception { brand = "MP3"; version = "0"; MP3Input data = new MP3Input(input); if (ID3v2Info.isID3v2StartPosition(data)) { ID3v2Info info = new ID3v2Info(data, debugLevel); album = info.getAlbum(); albumArtist = info.getAlbumArtist(); artist = info.getArtist(); comment = info.getComment(); cover = info.getCover(); smallCover = info.getSmallCover(); compilation = info.isCompilation(); composer = info.getComposer(); copyright = info.getCopyright(); disc = info.getDisc(); discs = info.getDiscs(); duration = info.getDuration(); genre = info.getGenre(); grouping = info.getGrouping(); lyrics = info.getLyrics(); title = info.getTitle(); track = info.getTrack(); tracks = info.getTracks(); year = info.getYear(); } if (duration <= 0 || duration >= 3600000L) { // don't trust strange durations (e.g. old lame versions always write TLEN 97391548) try { duration = calculateDuration(data, fileLength, new StopReadCondition() { final long stopPosition = fileLength - 128; @Override public boolean stopRead(MP3Input data) throws IOException { return (data.getPosition() == stopPosition) && ID3v1Info.isID3v1StartPosition(data); } }); } catch (MP3Exception e) { if (LOGGER.isLoggable(debugLevel)) { LOGGER.log(debugLevel, "Could not determine MP3 duration", e); } } } if (title == null || album == null || artist == null) { if (data.getPosition() <= fileLength - 128) { // position to last 128 bytes data.skipFully(fileLength - 128 - data.getPosition()); if (ID3v1Info.isID3v1StartPosition(input)) { ID3v1Info info = new ID3v1Info(input); if (album == null) { album = info.getAlbum(); } if (artist == null) { artist = info.getArtist(); } if (comment == null) { comment = info.getComment(); } if (genre == null) { genre = info.getGenre(); } if (title == null) { title = info.getTitle(); } if (track == 0) { track = info.getTrack(); } if (year == 0) { year = info.getYear(); } } } } } MP3Frame readFirstFrame(MP3Input data, StopReadCondition stopCondition) throws IOException { int b0 = 0; int b1 = stopCondition.stopRead(data) ? -1 : data.read(); while (b1 != -1) { if (b0 == 0xFF && (b1 & 0xE0) == 0xE0) { // first 11 bits should be 1 data.mark(2); // set mark at b2 int b2 = stopCondition.stopRead(data) ? -1 : data.read(); if (b2 == -1) { break; } int b3 = stopCondition.stopRead(data) ? -1 : data.read(); if (b3 == -1) { break; } MP3Frame.Header header = null; try { header = new MP3Frame.Header(b1, b2, b3); } catch (MP3Exception e) { // not a valid frame header } if (header != null) { // we have a candidate /* * The code gets a bit complex here, because we need to be able to reset() to b2 if * the check fails. Thus, we have to reset() to b2 before doing a call to mark(). */ data.reset(); // reset input to b2 data.mark(header.getFrameSize() + 2); // rest of frame (size - 2) + next header /* * read frame data */ byte[] frameBytes = new byte[header.getFrameSize()]; frameBytes[0] = (byte) 0xFF; frameBytes[1] = (byte) b1; try { data.readFully(frameBytes, 2, frameBytes.length - 2); // may throw EOFException } catch (EOFException e) { break; } MP3Frame frame = new MP3Frame(header, frameBytes); /* * read next header */ if (!frame.isChecksumError()) { int nextB0 = stopCondition.stopRead(data) ? -1 : data.read(); int nextB1 = stopCondition.stopRead(data) ? -1 : data.read(); if (nextB0 == -1 || nextB1 == -1) { return frame; } if (nextB0 == 0xFF && (nextB1 & 0xFE) == (b1 & 0xFE)) { // quick check: nextB1 must match b1's version & layer int nextB2 = stopCondition.stopRead(data) ? -1 : data.read(); int nextB3 = stopCondition.stopRead(data) ? -1 : data.read(); if (nextB2 == -1 || nextB3 == -1) { return frame; } try { if (new MP3Frame.Header(nextB1, nextB2, nextB3).isCompatible(header)) { data.reset(); // reset input to b2 data.skipFully(frameBytes.length - 2); // skip to end of frame return frame; } } catch (MP3Exception e) { // not a valid frame header } } } } /* * seems to be a false sync... */ data.reset(); // reset input to b2 } /* * read next byte */ b0 = b1; b1 = stopCondition.stopRead(data) ? -1 : data.read(); } return null; } MP3Frame readNextFrame(MP3Input data, StopReadCondition stopCondition, MP3Frame previousFrame) throws IOException { MP3Frame.Header previousHeader = previousFrame.getHeader(); data.mark(4); int b0 = stopCondition.stopRead(data) ? -1 : data.read(); int b1 = stopCondition.stopRead(data) ? -1 : data.read(); if (b0 == -1 || b1 == -1) { return null; } if (b0 == 0xFF && (b1 & 0xE0) == 0xE0) { // first 11 bits should be 1 int b2 = stopCondition.stopRead(data) ? -1 : data.read(); int b3 = stopCondition.stopRead(data) ? -1 : data.read(); if (b2 == -1 || b3 == -1) { return null; } MP3Frame.Header nextHeader = null; try { nextHeader = new MP3Frame.Header(b1, b2, b3); } catch (MP3Exception e) { // not a valid frame header } if (nextHeader != null && nextHeader.isCompatible(previousHeader)) { byte[] frameBytes = new byte[nextHeader.getFrameSize()]; frameBytes[0] = (byte) b0; frameBytes[1] = (byte) b1; frameBytes[2] = (byte) b2; frameBytes[3] = (byte) b3; try { data.readFully(frameBytes, 4, frameBytes.length - 4); } catch (EOFException e) { return null; } return new MP3Frame(nextHeader, frameBytes); } } data.reset(); return null; } long calculateDuration(MP3Input data, long totalLength, StopReadCondition stopCondition) throws IOException, MP3Exception { MP3Frame frame = readFirstFrame(data, stopCondition); if (frame != null) { // check for Xing header int numberOfFrames = frame.getNumberOfFrames(); if (numberOfFrames > 0) { // from Xing/VBRI header return frame.getHeader().getTotalDuration(numberOfFrames * frame.getSize()); } else { // scan file numberOfFrames = 1; long firstFramePosition = data.getPosition() - frame.getSize(); long frameSizeSum = frame.getSize(); int firstFrameBitrate = frame.getHeader().getBitrate(); long bitrateSum = firstFrameBitrate; boolean vbr = false; int cbrThreshold = 10000 / frame.getHeader().getDuration(); // assume CBR after 10 seconds while (true) { if (numberOfFrames == cbrThreshold && !vbr && totalLength > 0) { return frame.getHeader().getTotalDuration(totalLength - firstFramePosition); } if ((frame = readNextFrame(data, stopCondition, frame)) == null) { break; } int bitrate = frame.getHeader().getBitrate(); if (bitrate != firstFrameBitrate) { vbr = true; } bitrateSum += bitrate; frameSizeSum += frame.getSize(); numberOfFrames++; } return 1000L * frameSizeSum * numberOfFrames * 8 / bitrateSum; } } else { throw new MP3Exception("No audio frame"); } } }
gpl-2.0
steffengr/hops-metadata-dal-impl-ndb
src/main/java/io/hops/metadata/ndb/dalimpl/yarn/SchedulerApplicationClusterJ.java
5036
/* * Hops Database abstraction layer for storing the hops metadata in MySQL Cluster * Copyright (C) 2015 hops.io * * 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 io.hops.metadata.ndb.dalimpl.yarn; import com.mysql.clusterj.annotation.Column; import com.mysql.clusterj.annotation.PersistenceCapable; import com.mysql.clusterj.annotation.PrimaryKey; import io.hops.exception.StorageException; import io.hops.metadata.ndb.ClusterjConnector; import io.hops.metadata.ndb.wrapper.HopsQuery; import io.hops.metadata.ndb.wrapper.HopsQueryBuilder; import io.hops.metadata.ndb.wrapper.HopsQueryDomainType; import io.hops.metadata.ndb.wrapper.HopsSession; import io.hops.metadata.yarn.TablesDef; import io.hops.metadata.yarn.dal.SchedulerApplicationDataAccess; import io.hops.metadata.yarn.entity.SchedulerApplication; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class SchedulerApplicationClusterJ implements TablesDef.SchedulerApplicationTableDef, SchedulerApplicationDataAccess<SchedulerApplication> { @PersistenceCapable(table = TABLE_NAME) public interface SchedulerApplicationDTO { @PrimaryKey @Column(name = APPID) String getappid(); void setappid(String appid); @Column(name = USER) String getuser(); void setuser(String user); @Column(name = QUEUENAME) String getqueuename(); void setqueuename(String queuename); } private final ClusterjConnector connector = ClusterjConnector.getInstance(); @Override public Map<String, SchedulerApplication> getAll() throws StorageException { HopsSession session = connector.obtainSession(); HopsQueryBuilder qb = session.getQueryBuilder(); HopsQueryDomainType<SchedulerApplicationDTO> dobj = qb.createQueryDefinition( SchedulerApplicationClusterJ.SchedulerApplicationDTO.class); HopsQuery<SchedulerApplicationDTO> query = session. createQuery(dobj); List<SchedulerApplicationClusterJ.SchedulerApplicationDTO> results = query. getResultList(); return createApplicationIdMap(results); } @Override public void addAll(Collection<SchedulerApplication> toAdd) throws StorageException { HopsSession session = connector.obtainSession(); List<SchedulerApplicationDTO> toPersist = new ArrayList<SchedulerApplicationDTO>(); for (SchedulerApplication req : toAdd) { toPersist.add(createPersistable(req, session)); } session.savePersistentAll(toPersist); } @Override public void removeAll(Collection<SchedulerApplication> toRemove) throws StorageException { HopsSession session = connector.obtainSession(); List<SchedulerApplicationDTO> toPersist = new ArrayList<SchedulerApplicationDTO>(); for (SchedulerApplication entry : toRemove) { toPersist.add(session.newInstance(SchedulerApplicationDTO.class, entry. getAppid())); } session.deletePersistentAll(toPersist); } private Map<String, SchedulerApplication> createApplicationIdMap( List<SchedulerApplicationClusterJ.SchedulerApplicationDTO> list) { Map<String, SchedulerApplication> schedulerApplications = new HashMap<String, SchedulerApplication>(); for (SchedulerApplicationClusterJ.SchedulerApplicationDTO persistable : list) { SchedulerApplication app = createHopSchedulerApplication(persistable); schedulerApplications.put(app.getAppid(), app); } return schedulerApplications; } private SchedulerApplication createHopSchedulerApplication( SchedulerApplicationDTO schedulerApplicationDTO) { return new SchedulerApplication(schedulerApplicationDTO.getappid(), schedulerApplicationDTO.getuser(), schedulerApplicationDTO. getqueuename()); } private SchedulerApplicationDTO createPersistable(SchedulerApplication hop, HopsSession session) throws StorageException { SchedulerApplicationClusterJ.SchedulerApplicationDTO schedulerApplicationDTO = session.newInstance( SchedulerApplicationClusterJ.SchedulerApplicationDTO.class); schedulerApplicationDTO.setappid(hop.getAppid()); schedulerApplicationDTO.setuser(hop.getUser()); schedulerApplicationDTO.setqueuename(hop.getQueuename()); return schedulerApplicationDTO; } }
gpl-2.0
tauprojects/mpp
src/main/java/org/deuce/objectweb/asm/Handler.java
2539
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.deuce.objectweb.asm; /** * Information about an exception handler block. * * @author Eric Bruneton */ class Handler { /** * Beginning of the exception handler's scope (inclusive). */ Label start; /** * End of the exception handler's scope (exclusive). */ Label end; /** * Beginning of the exception handler's code. */ Label handler; /** * Internal name of the type of exceptions handled by this handler, or * <tt>null</tt> to catch any exceptions. */ String desc; /** * Constant pool index of the internal name of the type of exceptions * handled by this handler, or 0 to catch any exceptions. */ int type; /** * Next exception handler block info. */ Handler next; }
gpl-2.0
logicmoo/jrelisp-abcl-ws
TheRealDiffernce/lisp/FaslReadtable.java
5381
/* * FaslReadtable.java * * Copyright (C) 2005 Peter Graves * $Id$ * * 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. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. */ package org.armedbear.lisp; public final class FaslReadtable extends Readtable { public FaslReadtable() { super(); } protected void initialize() { Byte[] syntax = this.syntax.constants; syntax[9] = SYNTAX_TYPE_WHITESPACE; // tab syntax[10] = SYNTAX_TYPE_WHITESPACE; // linefeed syntax[12] = SYNTAX_TYPE_WHITESPACE; // form feed syntax[13] = SYNTAX_TYPE_WHITESPACE; // return syntax[' '] = SYNTAX_TYPE_WHITESPACE; syntax['"'] = SYNTAX_TYPE_TERMINATING_MACRO; syntax['\''] = SYNTAX_TYPE_TERMINATING_MACRO; syntax['('] = SYNTAX_TYPE_TERMINATING_MACRO; syntax[')'] = SYNTAX_TYPE_TERMINATING_MACRO; syntax[','] = SYNTAX_TYPE_TERMINATING_MACRO; syntax[';'] = SYNTAX_TYPE_TERMINATING_MACRO; syntax['`'] = SYNTAX_TYPE_TERMINATING_MACRO; syntax['#'] = SYNTAX_TYPE_NON_TERMINATING_MACRO; syntax['\\'] = SYNTAX_TYPE_SINGLE_ESCAPE; syntax['|'] = SYNTAX_TYPE_MULTIPLE_ESCAPE; LispObject[] readerMacroFunctions = this.readerMacroFunctions.constants; readerMacroFunctions[';'] = LispReader.READ_COMMENT; readerMacroFunctions['"'] = FaslReader.FASL_READ_STRING; readerMacroFunctions['('] = FaslReader.FASL_READ_LIST; readerMacroFunctions[')'] = LispReader.READ_RIGHT_PAREN; readerMacroFunctions['\''] = FaslReader.FASL_READ_QUOTE; readerMacroFunctions['#'] = FaslReader.FASL_READ_DISPATCH_CHAR; // BACKQUOTE-MACRO and COMMA-MACRO are defined in backquote.lisp. readerMacroFunctions['`'] = Symbol.BACKQUOTE_MACRO; readerMacroFunctions[','] = Symbol.COMMA_MACRO; DispatchTable dt = new DispatchTable(); LispObject[] dtfunctions = dt.functions.constants; dtfunctions['('] = FaslReader.FASL_SHARP_LEFT_PAREN; dtfunctions['*'] = FaslReader.FASL_SHARP_STAR; dtfunctions['.'] = FaslReader.FASL_SHARP_DOT; dtfunctions[':'] = FaslReader.FASL_SHARP_COLON; dtfunctions['A'] = FaslReader.FASL_SHARP_A; dtfunctions['B'] = FaslReader.FASL_SHARP_B; dtfunctions['C'] = FaslReader.FASL_SHARP_C; dtfunctions['O'] = FaslReader.FASL_SHARP_O; dtfunctions['P'] = FaslReader.FASL_SHARP_P; dtfunctions['R'] = FaslReader.FASL_SHARP_R; dtfunctions['S'] = FaslReader.FASL_SHARP_S; dtfunctions['X'] = FaslReader.FASL_SHARP_X; dtfunctions['\''] = FaslReader.FASL_SHARP_QUOTE; dtfunctions['\\'] = FaslReader.FASL_SHARP_BACKSLASH; dtfunctions['|'] = LispReader.SHARP_VERTICAL_BAR; dtfunctions[')'] = LispReader.SHARP_ILLEGAL; dtfunctions['<'] = LispReader.SHARP_ILLEGAL; dtfunctions[' '] = LispReader.SHARP_ILLEGAL; dtfunctions[8] = LispReader.SHARP_ILLEGAL; // backspace dtfunctions[9] = LispReader.SHARP_ILLEGAL; // tab dtfunctions[10] = LispReader.SHARP_ILLEGAL; // newline, linefeed dtfunctions[12] = LispReader.SHARP_ILLEGAL; // page dtfunctions[13] = LispReader.SHARP_ILLEGAL; // return dtfunctions['?'] = FaslReader.FASL_SHARP_QUESTION_MARK; dispatchTables.constants['#'] = dt; readtableCase = Keyword.PRESERVE; // after all, all symbols will have been uppercased by the reader, // if applicable, when reading the source file; so, any lower-case // symbols are really meant to be lower case, even if printed without // pipe characters, which may happen if the READTABLE-CASE of the // current readtable is :PRESERVE when printing the symbols } private static final FaslReadtable instance = new FaslReadtable(); public static final FaslReadtable getInstance() { return instance; } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/security/src/main/java/common/java/security/spec/MGF1ParameterSpec.java
2878
/* * 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 java.security.spec; import org.apache.harmony.security.internal.nls.Messages; /** * The parameter specification for the Mask Generation Function (MGF1) in * the RSA-PSS Signature and OAEP Padding scheme. * <p> * Defined in the <a * href="http://www.rsa.com/rsalabs/pubs/PKCS/html/pkcs-1.html">PKCS #1 v2.1</a> * standard */ public class MGF1ParameterSpec implements AlgorithmParameterSpec { /** * The predefined MGF1 parameter specification with an "SHA-1" message * digest. */ public static final MGF1ParameterSpec SHA1 = new MGF1ParameterSpec("SHA-1"); //$NON-NLS-1$ /** * The predefined MGF1 parameter specification with an "SHA-256" message * digest. */ public static final MGF1ParameterSpec SHA256 = new MGF1ParameterSpec("SHA-256"); //$NON-NLS-1$ /** * The predefined MGF1 parameter specification with an "SHA-384" message * digest. */ public static final MGF1ParameterSpec SHA384 = new MGF1ParameterSpec("SHA-384"); //$NON-NLS-1$ /** * The predefined MGF1 parameter specification with an "SHA-512" message * digest. */ public static final MGF1ParameterSpec SHA512 = new MGF1ParameterSpec("SHA-512"); //$NON-NLS-1$ // Message digest algorithm name private final String mdName; /** * Creates a new {@code MGF1ParameterSpec} with the specified message digest * algorithm name. * * @param mdName * the name of the message digest algorithm. */ public MGF1ParameterSpec(String mdName) { this.mdName = mdName; if (this.mdName == null) { throw new NullPointerException(Messages.getString("security.80")); //$NON-NLS-1$ } } /** * Returns the name of the message digest algorithm. * * @return the name of the message digest algorithm. */ public String getDigestAlgorithm() { return mdName; } }
gpl-2.0
arodchen/MaxSim
maxine/com.oracle.max.tele.vm/src/com/sun/max/tele/object/TeleBaseAtomicBumpPointerAllocator.java
3158
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.max.tele.object; import com.sun.max.tele.*; import com.sun.max.tele.reference.*; import com.sun.max.unsafe.*; import com.sun.max.vm.heap.gcx.*; /** * @see BaseAtomicBumpPointerAllocator */ public class TeleBaseAtomicBumpPointerAllocator extends TeleTupleObject { Address start = Address.zero(); Address end = Address.zero(); Address top = Address.zero(); public TeleBaseAtomicBumpPointerAllocator(TeleVM vm, RemoteReference reference) { super(vm, reference); } @Override protected boolean updateObjectCache(long epoch, StatsPrinter statsPrinter) { if (!super.updateObjectCache(epoch, statsPrinter)) { return false; } start = vm().fields().BaseAtomicBumpPointerAllocator_start.readWord(reference()).asAddress(); end = vm().fields().BaseAtomicBumpPointerAllocator_end.readWord(reference()).asAddress(); top = vm().fields().BaseAtomicBumpPointerAllocator_top.readWord(reference()).asAddress(); return true; } /** * @see BaseAtomicBumpPointerAllocator#start() */ public Address start() { return start; } /** * @see BaseAtomicBumpPointerAllocator#end() */ public Address end() { return end; } /** * @see BaseAtomicBumpPointerAllocator */ public Address top() { return top; } /** * Determines whether an address is in the allocated portion of the memory region served by the sub-class of {@link BaseAtomicBumpPointerAllocator} * described by this {@link TeleBaseAtomicBumpPointerAllocator}. */ public boolean containsInAllocated(Address address) { return start.lessEqual(address) && top.greaterThan(address); } /** * Determines whether an address is in the memory region the sub-class of {@link BaseAtomicBumpPointerAllocator} * described by this {@link TeleBaseAtomicBumpPointerAllocator} allocates memory from. */ public boolean contains(Address address) { return start.lessEqual(address) && end.greaterThan(address); } }
gpl-2.0
Jacksson/mywmsnb
mywms.as/los.inventory-ejb/src/java/de/linogistix/los/inventory/exception/InventoryExceptionKey.java
3897
/* * Copyright (c) 2006 - 2013 LinogistiX GmbH * * www.linogistix.com * * Project myWMS-LOS */ package de.linogistix.los.inventory.exception; public enum InventoryExceptionKey { ADVICE_ASSIGNED, ADVICE_POSITIONS_ASSIGNED, ADVICE_CANNOT_BE_ACCEPTED, ADVICE_FINISHED, ADVICE_MANDATORY, ADVICE_REFRESH_ERROR, AMBIGUOUS_SCAN, AMOUNT_MUST_BE_GREATER_THAN_ZERO, ARGUMENT_NULL, ARTICLE_NULL, CANNOT_BE_DELETED, CANNOT_RESERVE_MORE_THAN_AVAILABLE, CLIENT_MISMATCH, CLIENT_NULL, CONSTRAINT_VIOLATION, CREATE_AVIS_FAILED, CREATE_GOODSRECEIPT, CREATE_ORDERREQUEST_FAILED, CREATE_ORDERREQUEST_FAILED_WRONG_CLIENT, CREATE_STOCKUNIT_ONSTOCK, CREATE_STOCKUNIT_ON_STORAGELOCATION_FAILED, CREATE_UNITLOAD, DESTINATION_UNITLOAD_LOCKED, ERROR_CONCURRENT_ACCESS, ERROR_GETTING_DEFAULT_UNITLOADTYPE, ERROR_NOTIFIEDAMOUNT_NEGATIVE, INVENTORY_CREATE_STOCKUNIT_ON_TOP, ITEMDATA_EXISTS, ITEMDATA_ISLOCKED, ITEMDATA_LOT_MISMATCH, ITEMDATA_NOT_FOUND, ITEMDATA_NOT_ON_UNITLOAD, LABEL_NOT_PRINTED, LOT_ALREADY_EXIST, LOT_ISLOCKED, LOT_MANDATORY, LOT_MISMATCH, LOT_NAME_NULL, LOT_NOT_UNIQUE, LOT_TOO_YOUNG, MUST_SCAN_STOCKUNIT, NOT_ACCEPTED, NOT_A_FIXED_ASSIGNED_LOCATION, NOT_A_GOODSIN_LOCATION, NO_EXTINGUISHORDER_WITH_NUMBER, NO_GOODS_RECEIPT_LOCATION, NO_INVENTORY_FOR_LOT, NO_LOT_WITH_NAME, NO_PICKREQUEST, NO_STOCKUNIT, NO_STOCKUNIT_ON_FIXED_ASSIGNED_LOC, NO_SUCH_CLIENT, NO_SUCH_GOODS_OUT, NO_SUCH_ITEMDATA, NO_SUCH_LOT, NO_SUCH_ORDERPOSITION, NO_SUCH_STORAGELOCATION, NO_SUCH_UNITLOAD, NO_SUITABLE_LOCATION, NO_SUITABLE_LOT, ORDER_ALREADY_STARTED, ORDER_ALREADY_FINISHED, ORDER_CANNOT_BE_STARTED, ORDER_CANNOT_BE_CREATED, PICKORDER_CANNOT_BE_CREATED, ORDER_CONSTRAINT_VIOLATED, ORDER_NOT_FINIHED, ORDER_NOT_FINISHED, PICKED_TOO_MANY, PICKREQUEST_ALREDAY_FINISHED, PICKREQUEST_CONSTRAINT_VIOLATED, PICKREQUEST_CREATION, PICKREQUEST_NOT_FINISHED, PICK_POSITION_CONTRAINT_VIOLATED, PICK_UNEXPECTED_NULL, PICK_WRONG_SOURCE, PICK_WRONG_AMOUNT, POSITION_ALREADY_ASSIGNED_ADVICE, POSITION_NO_ADVICE, REPLENISH_ALREADY_COMES, REPLENISH_NOT_NEEDED, REPLENISH_ALREADY_FINISHED, REPLENISH_MISSING_SOURCE, REPLENISH_MISSING_DESTINATION, REPLENISH_NOT_RELEASED, REPLENISH_RESERVED, REPLENISH_CANNOT_REMOVE_ACTIVE, STOCKUNIT_CONSTRAINT_VIOLATED, STOCKUNIT_HAS_RESERVATION, STOCKUNIT_IS_LOCKED, STOCKUNIT_NO_LOT, STOCKUNIT_TRANSFER_FAILED, STOCKUNIT_TRANSFER_NOT_ALLOWED, STORAGELOCATION_CONSTRAINT_VIOLATED, STORAGE_ADD_TO_EXISTING, STORAGE_FAILED, STORAGE_NO_DESTINATION_FOUND, STORAGE_WRONG_LOCATION_BUT_ALLOWED, STORAGE_WRONG_LOCATION_NOT_ALLOWED, UNIT_LOAD_CONSTRAINT_VIOLATED, UNIT_LOAD_EXISTS, UNSUFFICIENT_AMOUNT, UNSUFFICIENT_RESERVED_AMOUNT, CUSTOM_TEXT, WRONG_STATE, SHIPPING_MSG_NO_GOODSOUT, SHIPPING_MSG_WRONG_GOODSOUT, UNITLOAD_DELETE_ERROR_STORAGEREQUEST, UNIT_LOAD_NOT_EMPTY, GOODS_RECEIPT_NOT_FINISHED, GOODS_RECEIPT_STOCK_ADDED, WRONG_ITEMDATA, SERIAL_ALREADY_EXISTS, ORDER_RESERVED, PICK_ALREADY_STARTED, PICK_ALREADY_FINISHED, PICK_CONFIRM_NO_STOCK, PICK_CONFIRM_NOT_PICKED_COUNTED, PICK_CONFIRM_MISSING_ORDER, PICK_CONFIRM_MISSING_UNITLOALD, PICK_CONFIRM_WRONG_UNITLOAD, PICK_CONFIRM_MISSING_SERIAL, PICK_CONFIRM_INVALID_AMOUNT, PICK_GEN_DIFF_STRAT, PICK_GEN_CLIENT_MIX, MISSING_PARAMETER, ORDER_NO_UNIQUE_NUMBER, STORAGE_STRATEGY_UNDEFINED, POSITION_CANNOT_BE_REMOVED, GOODS_OUT_EXISTS_FOR_UNITLOAD, GOODS_OUT_NOT_FINISHED, GRPOS_HAS_NO_STOCK }
gpl-2.0
Z-Shang/onscripter-gbk
svn/onscripter-read-only/src/org/bouncycastle/crypto/test/ECIESTest.java
9268
package org.bouncycastle.crypto.test; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.engines.TwofishEngine; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import java.math.BigInteger; import java.security.SecureRandom; /** * test for ECIES - Elliptic Curve Integrated Encryption Scheme */ public class ECIESTest extends SimpleTest { ECIESTest() { } public String getName() { return "ECIES"; } private void staticTest() throws Exception { ECCurve.Fp curve = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECDomainParameters params = new ECDomainParameters( curve, curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d params); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( curve.decodePoint(Hex.decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q params); AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey); AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey); // // stream test // IESEngine i1 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); IESEngine i2 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; IESParameters p = new IESParameters(d, e, 64); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); byte[] message = Hex.decode("1234567890abcdef"); byte[] out1 = i1.processBlock(message, 0, message.length); if (!areEqual(out1, Hex.decode("2442ae1fbf90dd9c06b0dcc3b27e69bd11c9aee4ad4cfc9e50eceb44"))) { fail("stream cipher test failed on enc"); } byte[] out2 = i2.processBlock(out1, 0, out1.length); if (!areEqual(out2, message)) { fail("stream cipher test failed"); } // // twofish with CBC // BufferedBlockCipher c1 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new TwofishEngine())); BufferedBlockCipher c2 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new TwofishEngine())); i1 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c1); i2 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c2); d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; p = new IESWithCipherParameters(d, e, 64, 128); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); message = Hex.decode("1234567890abcdef"); out1 = i1.processBlock(message, 0, message.length); if (!areEqual(out1, Hex.decode("2ea288651e21576215f2424bbb3f68816e282e3931b44bd1c429ebdb5f1b290cf1b13309"))) { fail("twofish cipher test failed on enc"); } out2 = i2.processBlock(out1, 0, out1.length); if (!areEqual(out2, message)) { fail("twofish cipher test failed"); } } private void doTest(AsymmetricCipherKeyPair p1, AsymmetricCipherKeyPair p2) throws Exception { // // stream test // IESEngine i1 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); IESEngine i2 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; IESParameters p = new IESParameters(d, e, 64); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); byte[] message = Hex.decode("1234567890abcdef"); byte[] out1 = i1.processBlock(message, 0, message.length); byte[] out2 = i2.processBlock(out1, 0, out1.length); if (!areEqual(out2, message)) { fail("stream cipher test failed"); } // // twofish with CBC // BufferedBlockCipher c1 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new TwofishEngine())); BufferedBlockCipher c2 = new PaddedBufferedBlockCipher( new CBCBlockCipher(new TwofishEngine())); i1 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c1); i2 = new IESEngine( new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c2); d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; p = new IESWithCipherParameters(d, e, 64, 128); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); message = Hex.decode("1234567890abcdef"); out1 = i1.processBlock(message, 0, message.length); out2 = i2.processBlock(out1, 0, out1.length); if (!areEqual(out2, message)) { fail("twofish cipher test failed"); } } public void performTest() throws Exception { staticTest(); ECCurve.Fp curve = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECDomainParameters params = new ECDomainParameters( curve, curve.decodePoint(Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n ECKeyPairGenerator eGen = new ECKeyPairGenerator(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(params, new SecureRandom()); eGen.init(gParam); AsymmetricCipherKeyPair p1 = eGen.generateKeyPair(); AsymmetricCipherKeyPair p2 = eGen.generateKeyPair(); doTest(p1, p2); } public static void main( String[] args) { runTest(new ECIESTest()); } }
gpl-2.0
emmental/isetools
src/main/java/ca/nines/ise/util/LocationData.java
3029
/* * Copyright (C) 2014 Michael Joyce <ubermichael@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 version 2. * * 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 ca.nines.ise.util; import java.util.Formatter; /** * Location data to add to an XML node. * * All location data is added during the parsing process in a user data * attribute for each node. * * see * http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html * * @author Michael Joyce <ubermichael@gmail.com> */ public class LocationData { /** * The key used to store the data in the user data. */ public static final String LOCATION_DATA_KEY = "locationDataKey"; /** * The XML systemId that generated the source. Usually the file name. */ private final String systemId; /** * The line number of the start tag. */ private final int startLine; /** * The column of the start tag. */ private final int startColumn; /** * The line of the end tag. */ private final int endLine; /** * The column of the end tag, */ private final int endColumn; public LocationData(String systemId, int startLine, int startColumn, int endLine, int endColumn) { super(); this.systemId = systemId; this.startLine = startLine; this.startColumn = startColumn; this.endLine = endLine; this.endColumn = endColumn; } /** * The systemID (usually a file path) for the XML data. * * @return a description of the source of the XML data */ public String getSystemId() { return systemId; } /** * Gets line number of the start tag * * @return line number */ public int getStartLine() { return startLine; } /** * Gets the column number of the start tag * * @return the column number */ public int getStartColumn() { return startColumn; } /** * Gets the line number of the end tag * * @return end line number */ public int getEndLine() { return endLine; } /** * Gets the column number of the end tag * * @return end column number */ public int getEndColumn() { return endColumn; } /** * Stringifies the location data. Really only useful for debugging. * * @return a mostly-useless string. */ @Override public String toString() { Formatter formatter = new Formatter(); formatter.format("%s:%s:%s", systemId, startLine, startColumn); return formatter.toString(); } }
gpl-2.0
blazegraph/database
bigdata-core-test/bigdata/src/test/com/bigdata/service/TestScatterSplit.java
13630
/* Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.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; version 2 of the License. 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 */ /* * Created on Mar 11, 2008 */ package com.bigdata.service; import java.io.IOException; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutionException; import com.bigdata.btree.BTree; import com.bigdata.btree.IRangeQuery; import com.bigdata.btree.ITupleIterator; import com.bigdata.btree.IndexMetadata; import com.bigdata.btree.ScatterSplitConfiguration; import com.bigdata.btree.keys.TestKeyBuilder; import com.bigdata.btree.proc.BatchInsert.BatchInsertConstructor; import com.bigdata.io.SerializerUtil; import com.bigdata.journal.BufferMode; import com.bigdata.journal.ITx; import com.bigdata.journal.TemporaryRawStore; import com.bigdata.mdi.IMetadataIndex; import com.bigdata.mdi.PartitionLocator; import com.bigdata.resources.ResourceManager; import com.bigdata.resources.ResourceManager.Options; import com.bigdata.service.ndx.ClientIndexView; import com.bigdata.service.ndx.RawDataServiceTupleIterator; import com.bigdata.util.Bytes; /** * Some unit tests for moving an index partition. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class TestScatterSplit extends AbstractEmbeddedFederationTestCase { public TestScatterSplit() { super(); } public TestScatterSplit(String name) { super(name); } /** * Overridden to specify the {@link BufferMode#Disk} mode and to lower the * threshold at which an overflow operation will be selected. */ public Properties getProperties() { final Properties properties = new Properties(super.getProperties()); // overrides Transient in the base class. properties.setProperty(Options.BUFFER_MODE, BufferMode.Disk .toString()); // this test relies on 2 or more data services. properties.setProperty(EmbeddedClient.Options.NDATA_SERVICES, "2"); // Note: disable copy of small index segments to the new journal during overflow. properties.setProperty(Options.COPY_INDEX_THRESHOLD,"0"); // // set low minimum #of active partitions per data service. // properties.setProperty(Options.MINIMUM_ACTIVE_INDEX_PARTITIONS,"1"); // // enable moves (one per target). // properties.setProperty(ResourceManager.Options.MAXIMUM_MOVES_PER_TARGET,"1"); // // // allow move of shards which would otherwise be split. // properties.setProperty(ResourceManager.Options.MAXIMUM_MOVE_PERCENT_OF_SPLIT,"2.0"); // // // disable the CPU threshold for moves. // properties.setProperty(ResourceManager.Options.MOVE_PERCENT_CPU_TIME_THRESHOLD,".0"); // enable scatter splits properties.setProperty(ResourceManager.Options.SCATTER_SPLIT_ENABLED,"true"); // /* // * Note: Disables the initial round robin policy for the load balancer // * service so that it will use our fakes scores. // */ // properties.setProperty(LoadBalancerService.Options.INITIAL_ROUND_ROBIN_UPDATE_COUNT, "0"); // turn off acceleration features. properties.setProperty(Options.ACCELERATE_OVERFLOW_THRESHOLD, "0"); properties.setProperty(Options.ACCELERATE_SPLIT_THRESHOLD, "0"); // Note: Set a low maximum shard size. properties.setProperty(Options.NOMINAL_SHARD_SIZE, ""+Bytes.megabyte); // properties.setProperty(Options.INITIAL_EXTENT, ""+1*Bytes.megabyte); // properties.setProperty(Options.MAXIMUM_EXTENT, ""+1*Bytes.megabyte); return properties; } /** * Test writes on a scale-out index until it has enough data to undergo a * scatter split, validates that the index was distributed into N shards per * DS and validates the scale-out index after the scatter split against * ground truth. * * @throws IOException * @throws ExecutionException * @throws InterruptedException */ public void test_scatterSplit() throws IOException, InterruptedException, ExecutionException { final int dataServiceCount = 2; final int expectedIndexPartitionCount = 4; /* * Register the index. */ final String name = "testIndex"; final UUID indexUUID = UUID.randomUUID(); { final IndexMetadata indexMetadata = new IndexMetadata(name,indexUUID); // must support delete markers indexMetadata.setDeleteMarkers(true); /* * Explicitly setup the scatter split operation to distribute 4 * index partitions across 2 data services (this is done explicitly * in case the configuration defaults are changed). */ indexMetadata .setScatterSplitConfiguration(new ScatterSplitConfiguration( true,// enabled .25,// percentOfSplitThreshold dataServiceCount, // expectedIndexPartitionCount// )); // register the scale-out index, creating a single index partition. fed.registerIndex(indexMetadata, dataService0.getServiceUUID()); } /* * Verify the initial index partition. */ final PartitionLocator pmd0; { final ClientIndexView ndx = (ClientIndexView) fed.getIndex(name, ITx.UNISOLATED); final IMetadataIndex mdi = ndx.getMetadataIndex(); assertEquals("#index partitions", 1, mdi.rangeCount()); // This is the initial partition locator metadata record. pmd0 = mdi.get(new byte[]{}); assertEquals("partitionId", 0L, pmd0.getPartitionId()); assertEquals("dataServiceUUID", dataService0 .getServiceUUID(), pmd0.getDataServiceUUID()); } assertEquals("partitionCount", 1, getPartitionCount(name)); /* * Setup the ground truth B+Tree. */ final BTree groundTruth; { final IndexMetadata indexMetadata = new IndexMetadata(indexUUID); groundTruth = BTree.create(new TemporaryRawStore(), indexMetadata); } /* * Populate the index with data until the initial the journal for the * data service on which the initial partition resides overflows. * * Note: The index split will occur asynchronously once (a) the index * partition has a sufficient #of entries; and (b) a group commit * occurs. However, this loop will continue to run, so writes will * continue to accumulate on the index partition on the live journal. * Once the overflow process completes the client be notified that the * index partition which it has been addressing no longer exists on the * data service. At that point the client SHOULD re-try the operation. * Once the client returns from the retry we will notice that the * partition count has increased and exit this loop. */ final int batchSize = 5000; long overflowCounter = dataService0.getAsynchronousOverflowCounter(); int npartitions = -1; { if(log.isInfoEnabled()) log.info("Writing on indices to provoke overflow"); int nrounds = 0; long nwritten = 0L; while (npartitions <= 1) { final byte[][] keys = new byte[batchSize][]; final byte[][] vals = new byte[batchSize][]; for (int i = 0; i < batchSize; i++) { keys[i] = TestKeyBuilder.asSortKey(nwritten + i); vals[i] = SerializerUtil.serialize(nwritten + i); } // insert the data into the ground truth index. groundTruth .submit(0/* fromIndex */, batchSize/* toIndex */, keys, vals, BatchInsertConstructor.RETURN_NO_VALUES, null/* handler */); // Set flag to force overflow on group commit. dataService0 .forceOverflow(false/* immediate */, false/* compactingMerge */); // insert the data into the scale-out index. fed.getIndex(name, ITx.UNISOLATED) .submit(0/* fromIndex */, batchSize/* toIndex */, keys, vals, BatchInsertConstructor.RETURN_NO_VALUES, null/* handler */); overflowCounter = awaitAsynchronousOverflow(dataService0, overflowCounter); assertEquals("rangeCount", groundTruth.getEntryCount(), fed .getIndex(name, ITx.UNISOLATED).rangeCount()); nrounds++; nwritten += batchSize; npartitions = getPartitionCount(name); // if (log.isInfoEnabled()) // log.info System.err.println ("Populating the index: overflowCounter=" + overflowCounter + ", nrounds=" + nrounds + ", nwritten=" + nwritten + ", nentries=" + groundTruth.getEntryCount() + " (" + fed.getIndex(name, ITx.UNISOLATED).rangeCount() + "), npartitions=" + npartitions); /* * Compare the index against ground truth after overflow. */ if(log.isInfoEnabled()) log.info("Verifying scale-out index against ground truth"); assertSameEntryIterator(groundTruth, fed.getIndex(name, ITx.UNISOLATED)); } } /* * Figure out which index partition was moved and verify that there is * now (at least) one index partition on each data service. */ { int ndataService0 = 0;// #of index partitions on data service 0. int ndataService1 = 0;// #of index partitions on data service 1. final ITupleIterator itr = new RawDataServiceTupleIterator( fed.getMetadataService(),// MetadataService.getMetadataIndexName(name), // ITx.READ_COMMITTED,// true, // readConsistent null, // fromKey null, // toKey 0, // capacity, IRangeQuery.DEFAULT,// flags null // filter ); int n = 0; while (itr.hasNext()) { final PartitionLocator locator = (PartitionLocator) SerializerUtil .deserialize(itr.next().getValue()); System.err.println("locators["+n+"]="+locator); if (locator.getDataServiceUUID().equals(dataService0 .getServiceUUID())) { ndataService0++; } else if (locator.getDataServiceUUID().equals( dataService1.getServiceUUID())) { ndataService1++; } else { fail("Not expecting partition move to this service: " + locator); } n++; } npartitions = getPartitionCount(name); System.err.println("npartitions=" + npartitions); System.err.println("npartitions(ds0)=" + ndataService0); System.err.println("npartitions(ds1)=" + ndataService1); // Verify expected #of partitions. assertEquals("partitionCount=" + npartitions, expectedIndexPartitionCount, npartitions); assertEquals("#dataService0=" + ndataService0, expectedIndexPartitionCount / 2, ndataService0); assertEquals("#dataService1=" + ndataService0, expectedIndexPartitionCount / 2, ndataService1); } } }
gpl-2.0
CarstenHollmann/SOS
hibernate/common/src/main/java/org/n52/sos/ds/hibernate/util/procedure/create/LinkedDescriptionCreationStrategy.java
4317
/* * Copyright (C) 2012-2021 52°North Spatial Information Research GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * 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. */ package org.n52.sos.ds.hibernate.util.procedure.create; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Locale; import java.util.Scanner; import org.hibernate.Session; import org.n52.series.db.beans.ProcedureEntity; import org.n52.shetland.ogc.ows.exception.NoApplicableCodeException; import org.n52.shetland.ogc.ows.exception.OwsExceptionReport; import org.n52.shetland.ogc.sos.SosProcedureDescription; import org.n52.shetland.ogc.sos.SosProcedureDescriptionUnknownType; import org.n52.sos.ds.hibernate.util.procedure.HibernateProcedureCreationContext; import org.n52.svalbard.decode.exception.DecodingException; import org.n52.svalbard.util.XmlHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; public class LinkedDescriptionCreationStrategy implements DescriptionCreationStrategy { private static final Logger LOGGER = LoggerFactory.getLogger(LinkedDescriptionCreationStrategy.class); @Override public boolean apply(ProcedureEntity p) { return p != null && !Strings.isNullOrEmpty(p.getDescriptionFile()) && (p.getDescriptionFile().startsWith("http")); } @Override public SosProcedureDescription<?> create(ProcedureEntity p, String descriptionFormat, Locale i18n, HibernateProcedureCreationContext ctx, Session s) throws OwsExceptionReport { String xml = loadDescriptionFromHttp(p.getDescriptionFile()); return new SosProcedureDescriptionUnknownType(p.getIdentifier(), p.getFormat().getFormat(), xml); } private String loadDescriptionFromHttp(String descriptionFile) throws OwsExceptionReport { InputStream is = null; Scanner scanner = null; try { URL url = new URL(descriptionFile); HttpURLConnection request1 = (HttpURLConnection) url.openConnection(); request1.setRequestMethod("GET"); request1.connect(); is = request1.getInputStream(); scanner = new Scanner(is, "UTF-8"); String inputStreamString = scanner.useDelimiter("\\A").next(); return checkXml(inputStreamString); } catch (IOException | DecodingException e) { throw new NoApplicableCodeException().causedBy(e) .withMessage("Error while querying sensor description from:{}", descriptionFile); } finally { if (scanner != null) { scanner.close(); } if (is != null) { try { is.close(); } catch (IOException ioe) { LOGGER.error("Error while closing inputStream", ioe); } } } } private String checkXml(String xml) throws DecodingException { XmlHelper.parseXmlString(xml); if (xml.startsWith("<?xml")) { return xml.substring(xml.indexOf(">") + 1); } return xml; } }
gpl-2.0
karlstroetmann/Algorithms
Java/PowerIterative.java
528
import java.util.*; import java.math.*; public class PowerIterative { public static void main(String[] args) { for (int i = 0; i <= 32; ++i) { BigInteger base = BigInteger.valueOf(137); System.out.println("power(" + 3 + ", " + i + ") = " + power(base, i)); } } static BigInteger power(BigInteger m, int n) { BigInteger r = BigInteger.valueOf(1); for (int i = 0; i < n; ++i) { r = r.multiply(m); } return r; } }
gpl-2.0
LinkBR/PlayerSQL
src/main/java/com/mengcraft/playersql/jdbc/ConnectionHandler.java
1418
package com.mengcraft.playersql.jdbc; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.LinkedBlockingQueue; public class ConnectionHandler { private final String name; private final ConnectionFactory factory; private final LinkedBlockingQueue<Connection> queue; protected ConnectionHandler(String name, ConnectionFactory factory) { this.name = name; this.factory = factory; this.queue = new LinkedBlockingQueue<>(); } public String name() { return name; } public Connection getConnection() throws SQLException { Connection c = queue.poll(); if (c == null) { c = factory.create(); } else if (!check(c)) { return getConnection(); } return c; } public void release(Connection c) { queue.offer(c); } private boolean check(Connection c) { try { return c.isValid(1); } catch (SQLException e) { // e.printStackTrace(); } return false; } public void shutdown() { for (Connection connection : queue) { close(connection); } queue.clear(); } private void close(Connection connection) { try { connection.close(); } catch (SQLException e) { // e.printStackTrace(); } } }
gpl-2.0