repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
FranPR9/NBALIVEFEED
app/src/main/java/fpr9/com/nbalivefeed/entities/RecordContainer.java
430
package fpr9.com.nbalivefeed.entities; /** * Created by FranciscoPR on 07/11/16. */ public class RecordContainer { private String id; private Record record; public String getId() { return id; } public void setId(String id) { this.id = id; } public Record getRecord() { return record; } public void setRecord(Record record) { this.record = record; } }
mit
kevintanhongann/nextrtc-signaling-server
src/main/java/org/nextrtc/signalingserver/api/NextRTCEventBus.java
719
package org.nextrtc.signalingserver.api; import lombok.extern.log4j.Log4j; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.google.common.eventbus.EventBus; @Log4j @Service("nextRTCEventBus") @Scope("singleton") public class NextRTCEventBus { private EventBus eventBus; public NextRTCEventBus() { this.eventBus = new EventBus(); } public void post(NextRTCEvent event) { log.info("POSTED EVENT: " + event); eventBus.post(event); } @Deprecated public void post(Object o) { eventBus.post(o); } public void register(Object listeners) { log.info("REGISTERED LISTENER: " + listeners); eventBus.register(listeners); } }
mit
LSTS/imcproxy
src/pt/lsts/imc/ImcClientSocket.java
1796
package pt.lsts.imc; import java.io.IOException; import java.net.URI; import java.util.concurrent.Future; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; @WebSocket public class ImcClientSocket { protected Session remote; protected WebSocketClient client = new WebSocketClient(); @OnWebSocketConnect public void onConnect(Session remote) { this.remote = remote; } @OnWebSocketMessage public void onBinary(Session session, byte buff[], int offset, int length) { try { IMCMessage msg = ImcProxyServer.deserialize(buff, offset, length); onMessage(msg); } catch (Exception e) { e.printStackTrace(); } } public void onMessage(IMCMessage msg) { msg.dump(System.out); } public void sendMessage(IMCMessage msg) throws IOException { if (remote == null || !remote.isOpen()) throw new IOException("Error sending message: not connected"); remote.getRemote().sendBytes(ImcProxyServer.wrap(msg)); } public Future<Session> connect(URI server) throws Exception { client.start(); return client.connect(this, server, new ClientUpgradeRequest()); } public void close() throws Exception { client.stop(); } public static void main(String[] args) throws Exception { ImcClientSocket socket = new ImcClientSocket(); Future<Session> future = socket.connect(new URI("ws://localhost:9090")); System.out.printf("Connecting..."); future.get(); socket.sendMessage(new Temperature(10.67f)); socket.close(); } }
mit
cr0ybot/MIRROR
libraries/JBox2D/src/org/jbox2d/testbed/TestSettings.java
2286
/* * JBox2D - A Java Port of Erin Catto's Box2D * * JBox2D homepage: http://jbox2d.sourceforge.net/ * Box2D homepage: http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package org.jbox2d.testbed; public class TestSettings { public int hz; public int iterationCount; public boolean enableWarmStarting; public boolean enablePositionCorrection; public boolean enableTOI; public boolean pause; public boolean singleStep; public boolean drawShapes; public boolean drawJoints; public boolean drawCoreShapes; public boolean drawOBBs; public boolean drawCOMs; public boolean drawStats; public boolean drawImpulses; public boolean drawAABBs; public boolean drawPairs; public boolean drawContactPoints; public boolean drawContactNormals; public boolean drawContactForces; public boolean drawFrictionForces; public TestSettings() { hz = 60; iterationCount = 10; drawStats = true; drawAABBs = false; drawPairs = false; drawShapes = true; drawJoints = true; drawCoreShapes = false; drawContactPoints = false; drawContactNormals = false; drawContactForces = false; drawFrictionForces = false; drawOBBs = false; drawCOMs = false; enableWarmStarting = true; enablePositionCorrection = true; enableTOI = true; pause = false; singleStep = false; } }
mit
csmervyn/java-learn
java-learn-io/src/test/java/org/github/mervyn/io/FileInputStreamTest.java
1707
package org.github.mervyn.io; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @ClassName: FileInputStreamTest * @Description: 测试FileInputStream * @author: mervyn * @date 2015年12月26日 上午11:28:07 * */ public class FileInputStreamTest { protected Logger logger = LoggerFactory.getLogger(this.getClass()); /** * testFileInputStream1(测试FileInputStream(File file)构造函数,构造节点输入流) * TODO(这里描述这个方法适用条件 – 可选) * TODO(这里描述这个方法的执行流程 – 可选) * TODO(这里描述这个方法的使用方法 – 可选) * TODO(这里描述这个方法的注意事项 – 可选) * * @Title: testFileInputStream * @Description: 测试FileInputStream(File file)构造函数,构造节点输入流 * @param @throws IOException * @return void 返回类型 * @throws */ @Test public void testFileInputStream1() throws IOException{ String pathname = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "test.txt"; File f = new File(pathname); //构造一个FileInputStream InputStream in = new FileInputStream(f); byte[] b = new byte[(int) f.length()]; //从输入流中读取数据,一次性读入所有字节 int len = in.read(b); //关闭输入流 in.close(); logger.debug("读入了" + len + "个字节的数据"); logger.debug("读入的数据是:" + new String(b)); } }
mit
Sch3lp/ProductivityWithShortcuts
src/main/java/be/swsb/productivity/chapter5/beans/CoffeeBeans.java
120
package be.swsb.productivity.chapter5.beans; public abstract class CoffeeBeans { public abstract String scent(); }
mit
zsgithub3895/common.code
src/com/zs/leetcode/array/MergeIntervals.java
1011
package com.zs.leetcode.array; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MergeIntervals { public static void main(String[] args) { } public List<Interval> merge(List<Interval> intervals) { List<Interval> list = new ArrayList<Interval>(); if (intervals.size() == 0) { return list; } Collections.sort(intervals, new MyComparator()); int start = intervals.get(0).start; int end = intervals.get(0).end; for (int i = 1; i < intervals.size(); i++) { Interval inter = intervals.get(i); if (inter.start > end) { list.add(new Interval(start, end)); start = inter.start; end = inter.end; }else{ end = Math.max(end, inter.end); } } list.add(new Interval(start, end)); return list; } class MyComparator implements Comparator<Interval> { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } } }
mit
SRI-CSL/bixie
src/main/java/bixie/checker/transition_relation/FaultLocalizationTransitionRelation.java
5883
package bixie.checker.transition_relation; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import bixie.boogie.controlflow.AbstractControlFlowFactory; import bixie.boogie.controlflow.BasicBlock; import bixie.boogie.controlflow.CfgProcedure; import bixie.boogie.controlflow.expression.CfgExpression; import bixie.boogie.controlflow.statement.CfgStatement; import bixie.boogie.controlflow.util.HasseDiagram; import bixie.boogie.controlflow.util.PartialBlockOrderNode; import bixie.prover.Prover; import bixie.prover.ProverExpr; /** * @author schaef TODO: if we plan to do interprocedural analysis, we have to * change the way globals are handled here. */ public class FaultLocalizationTransitionRelation extends AbstractTransitionRelation { public LinkedList<ProverExpr> obligations = new LinkedList<ProverExpr>(); public HashMap<CfgStatement, BasicBlock> stmtOriginMap = new HashMap<CfgStatement, BasicBlock>(); HasseDiagram hd; public FaultLocalizationTransitionRelation(CfgProcedure cfg, AbstractControlFlowFactory cff, Prover p) { super(cfg, cff, p); makePrelude(); // create the ProverExpr for the precondition ProverExpr[] prec = new ProverExpr[cfg.getRequires().size()]; int i = 0; for (CfgExpression expr : cfg.getRequires()) { prec[i] = this.expression2proverExpression(expr); i++; } this.requires = this.prover.mkAnd(prec); // create the ProverExpr for the precondition ProverExpr[] post = new ProverExpr[cfg.getEnsures().size()]; i = 0; for (CfgExpression expr : cfg.getEnsures()) { post[i] = this.expression2proverExpression(expr); i++; } this.ensures = this.prover.mkAnd(post); this.hd = new HasseDiagram(cfg); computeSliceVC(cfg); this.hd = null; finalizeAxioms(); } private void computeSliceVC(CfgProcedure cfg) { PartialBlockOrderNode pon = hd.findNode(cfg.getRootNode()); LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>(); todo.add(cfg.getRootNode()); HashSet<BasicBlock> mustreach = pon.getElements(); // System.err.println("-------"); // for (BasicBlock b : mustreach) System.err.println(b.getLabel()); // System.err.println("traverse "); while (!todo.isEmpty()) { BasicBlock current = todo.pop(); obligations.addAll(statements2proverExpression(current.getStatements())); for (CfgStatement stmt : current.getStatements()) { this.stmtOriginMap.put(stmt, current); } BasicBlock next = foo(current, mustreach); if (next!=null) { if (mustreach.contains(next)) { todo.add(next); } else { System.err.println("FIXME: don't know what to do with "+next.getLabel()); } } } // System.err.println("traverse done"); } private BasicBlock foo(BasicBlock b, HashSet<BasicBlock> mustpass) { HashSet<BasicBlock> done = new HashSet<BasicBlock>(); LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>(); HashMap<BasicBlock, LinkedList<ProverExpr>> map = new HashMap<BasicBlock, LinkedList<ProverExpr>>(); todo.addAll(b.getSuccessors()); done.add(b); map.put(b, new LinkedList<ProverExpr>()); map.get(b).add(this.prover.mkLiteral(true)); while (!todo.isEmpty()) { BasicBlock current = todo.pop(); boolean allDone = true; LinkedList<LinkedList<ProverExpr>> prefix = new LinkedList<LinkedList<ProverExpr>>(); for (BasicBlock pre : current.getPredecessors()) { if (!done.contains(pre)) { allDone = false; break; } prefix.add(map.get(pre)); } if (!allDone) { todo.add(current); continue; } done.add(current); LinkedList<ProverExpr> conj = new LinkedList<ProverExpr>(); if (prefix.size()>1) { //TODO LinkedList<ProverExpr> shared = prefix.getFirst(); for (LinkedList<ProverExpr> list : prefix) { shared = sharedPrefix(shared, list); } conj.add(this.prover.mkAnd(shared.toArray(new ProverExpr[shared.size()]))); LinkedList<ProverExpr> disj = new LinkedList<ProverExpr>(); for (LinkedList<ProverExpr> list : prefix) { LinkedList<ProverExpr> cutlist = new LinkedList<ProverExpr>(); cutlist.addAll(list); cutlist.removeAll(shared); disj.add(this.prover.mkAnd(cutlist.toArray(new ProverExpr[cutlist.size()]))); } conj.add(this.prover.mkOr(disj.toArray(new ProverExpr[disj.size()]))); } else if (prefix.size()==1) { conj.addAll(prefix.getFirst()); } else { throw new RuntimeException("unexpected"); } if (mustpass.contains(current)) { if (conj.size()==1 && conj.getFirst().equals(this.prover.mkLiteral(true))) { // in that case, the predecessor was already in mustpass so nothing needs to be done. } else { ProverExpr formula = this.prover.mkAnd(conj.toArray(new ProverExpr[conj.size()])); this.obligations.add(formula); } return current; } else { for (CfgStatement stmt : current.getStatements()) { this.stmtOriginMap.put(stmt, current); } conj.addAll(statements2proverExpression(current.getStatements())); map.put(current, conj); for (BasicBlock suc : current.getSuccessors()) { if (!todo.contains(suc) && !done.contains(suc)) { todo.add(suc); } } } } return null; } private LinkedList<ProverExpr> sharedPrefix(LinkedList<ProverExpr> shared, LinkedList<ProverExpr> list) { Iterator<ProverExpr> iterA = shared.iterator(); Iterator<ProverExpr> iterB = list.iterator(); LinkedList<ProverExpr> ret = new LinkedList<ProverExpr>(); while(iterA.hasNext() && iterB.hasNext()) { ProverExpr next = iterA.next(); if (next == iterB.next()) { ret.add(next); } } return ret; } }
mit
meefik/java-examples
SpringAOP/src/main/java/ru/ifmo/springaop/namepc/NamePointcutExample.java
1153
package ru.ifmo.springaop.namepc; import org.springframework.aop.Advisor; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.NameMatchMethodPointcut; import ru.ifmo.springaop.staticpc.SimpleAdvice; /** * Пример среза, где сревнение имени метода осуществляется просто по его имени. */ public class NamePointcutExample { public static void main(String[] args) { NameBean target = new NameBean(); // create advisor NameMatchMethodPointcut pc = new NameMatchMethodPointcut(); pc.addMethodName("foo"); pc.addMethodName("bar"); Advisor advisor = new DefaultPointcutAdvisor(pc, new SimpleAdvice()); // create the proxy ProxyFactory pf = new ProxyFactory(); pf.setTarget(target); pf.addAdvisor(advisor); NameBean proxy = (NameBean)pf.getProxy(); proxy.foo(); proxy.foo(999); proxy.bar(); proxy.yup(); } }
mit
haducloc/appslandia-common
src/main/java/com/appslandia/common/base/BufferedWriter.java
3684
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.base; import java.io.IOException; import java.io.Writer; /** * @see java.io.BufferedWriter * * @author <a href="mailto:haducloc13@gmail.com">Loc Ha</a> * */ public class BufferedWriter extends Writer { private Writer out; private char cb[]; private int nChars, nextChar; private static int defaultCharBufferSize = 8192; public BufferedWriter(Writer out) { this(out, defaultCharBufferSize); } public BufferedWriter(Writer out, int sz) { super(out); if (sz <= 0) throw new IllegalArgumentException("sz"); this.out = out; cb = new char[sz]; nChars = sz; nextChar = 0; } private void ensureOpen() throws IOException { if (out == null) throw new IOException("Stream closed"); } void flushBuffer() throws IOException { ensureOpen(); if (nextChar == 0) return; out.write(cb, 0, nextChar); nextChar = 0; } public void write(int c) throws IOException { ensureOpen(); if (nextChar >= nChars) flushBuffer(); cb[nextChar++] = (char) c; } private int min(int a, int b) { if (a < b) return a; return b; } public void write(char cbuf[], int off, int len) throws IOException { ensureOpen(); if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (len >= nChars) { /* * If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ flushBuffer(); out.write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(nChars - nextChar, t - b); System.arraycopy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= nChars) flushBuffer(); } } public void write(String s, int off, int len) throws IOException { ensureOpen(); int b = off, t = off + len; while (b < t) { int d = min(nChars - nextChar, t - b); s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= nChars) flushBuffer(); } } public void newLine() throws IOException { write(System.lineSeparator(), 0, System.lineSeparator().length()); } public void flush() throws IOException { flushBuffer(); out.flush(); } public void close() throws IOException { if (out == null) { return; } try (Writer w = out) { flushBuffer(); } finally { out = null; cb = null; } } }
mit
pearlqueen/java-simple-mvc
src/main/java/com/dmurph/mvc/gui/combo/MVCJComboBox.java
10703
/** * Copyright (c) 2010 Daniel Murphy * * 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. */ /** * Created at Aug 20, 2010, 2:58:08 AM */ package com.dmurph.mvc.gui.combo; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import javax.swing.JComboBox; import com.dmurph.mvc.model.MVCArrayList; /** * This class is for having a combo box that will always reflect the data of * an MVCArrayList. There is a lot of flexibility provided with filtering * and sorting the elements. * * @author Daniel Murphy */ public class MVCJComboBox<E> extends JComboBox { private static final long serialVersionUID = 1L; private MVCJComboBoxModel<E> model; private MVCArrayList<E> data; private IMVCJComboBoxFilter<E> filter; private final Object lock = new Object(); private MVCJComboBoxStyle style; private Comparator<E> comparator = null; private final PropertyChangeListener plistener = new PropertyChangeListener() { @SuppressWarnings("unchecked") public void propertyChange(PropertyChangeEvent argEvt) { String prop = argEvt.getPropertyName(); if (prop.equals(MVCArrayList.ADDED)) { add((E)argEvt.getNewValue()); } else if(prop.equals(MVCArrayList.ADDED_ALL)){ addAll((Collection<E>) argEvt.getNewValue()); } else if (prop.equals(MVCArrayList.CHANGED)) { change((E)argEvt.getOldValue(),(E) argEvt.getNewValue()); } else if (prop.equals(MVCArrayList.REMOVED)) { remove((E)argEvt.getOldValue()); } else if(prop.equals(MVCArrayList.REMOVED_ALL)){ synchronized(lock){ model.removeAllElements(); } } } }; /** * Constructs with no data, no filter, no * {@link Comparator}, and style set to * {@link MVCJComboBoxStyle#ADD_NEW_TO_BEGINNING}. */ public MVCJComboBox() { this(null, new IMVCJComboBoxFilter<E>() { public boolean showItem(E argComponent) { return true; }; }, MVCJComboBoxStyle.SORT, null); } /** * Constructs a combo box with the given style. If you want * the {@link MVCJComboBoxStyle#SORT} style, then you'll want to specify * a comparator as well. * @param argData * @param argStyle */ public MVCJComboBox(MVCJComboBoxStyle argStyle) { this(null, new IMVCJComboBoxFilter<E>() { public boolean showItem(E argComponent) { return true; }; }, argStyle, null); } /** * Constracts a dynamic combo box with the given data and * default style of {@link MVCJComboBoxStyle#SORT}. * @param argData */ public MVCJComboBox(MVCArrayList<E> argData, Comparator<E> argComparator) { this(argData, new IMVCJComboBoxFilter<E>() { public boolean showItem(E argComponent) { return true; }; }, MVCJComboBoxStyle.SORT, argComparator); } /** * Constructs a combo box with the given data and style. If you want * the {@link MVCJComboBoxStyle#SORT} style, then you'll want to specify * a comparator as well. * @param argData * @param argStyle */ public MVCJComboBox(MVCArrayList<E> argData, MVCJComboBoxStyle argStyle) { this(argData, new IMVCJComboBoxFilter<E>() { public boolean showItem(E argComponent) { return true; }; }, argStyle, null); } /** * Constructs a dynamic combo box with the given data, filter, and comparator. * The style will be {@link MVCJComboBoxStyle#SORT} by default. * @param argData * @param argFilter * @param argComparator */ public MVCJComboBox(MVCArrayList<E> argData, IMVCJComboBoxFilter<E> argFilter, Comparator<E> argComparator) { this(argData, argFilter, MVCJComboBoxStyle.SORT, null); } /** * * @param argData * @param argFilter * @param argStyle * @param argComparator */ public MVCJComboBox(MVCArrayList<E> argData, IMVCJComboBoxFilter<E> argFilter, MVCJComboBoxStyle argStyle, Comparator<E> argComparator) { data = argData; style = argStyle; filter = argFilter; comparator = argComparator; model = new MVCJComboBoxModel<E>(); super.setModel(model); if(data != null){ argData.addPropertyChangeListener(plistener); // add the data for (E o : data) { if(filter.showItem(o)){ model.addElement(o); } } // start with allowing the comparator to be null, in case they intend to set it later. and call refreshData() if(style == MVCJComboBoxStyle.SORT && comparator != null){ model.sort(comparator); } } } /** * Gets the rendering style of this combo box. Default style is * {@link MVCJComboBoxStyle#SORT}. * @return */ public MVCJComboBoxStyle getStyle(){ return style; } /** * Gets the data list. This is used to access * data with {@link #refreshData()}, so override * if you want to customize what the data is (sending * null to the contructor for the data * is a good idea in that case) * @return */ public ArrayList<E> getData(){ return data; } /** * Sets the data of this combo box. This causes the box * to refresh it's model * @param argData can be null */ public void setData(MVCArrayList<E> argData){ synchronized (lock) { if(data != null){ data.removePropertyChangeListener(plistener); } data = argData; if(data != null){ data.addPropertyChangeListener(plistener); } } refreshData(); } /** * Sets the comparator used for the {@link MVCJComboBoxStyle#SORT} style. * @param argComparator */ public void setComparator(Comparator<E> argComparator) { this.comparator = argComparator; } /** * Gets the comparator that's used for sorting. * @return */ public Comparator<E> getComparator() { return comparator; } /** * @return the filter */ public IMVCJComboBoxFilter<E> getFilter() { return filter; } /** * @param argFilter the filter to set */ public void setFilter(IMVCJComboBoxFilter<E> argFilter) { filter = argFilter; } /** * @see javax.swing.JComboBox#processKeyEvent(java.awt.event.KeyEvent) */ @Override public void processKeyEvent(KeyEvent argE) { if(argE.getKeyChar() == KeyEvent.VK_BACK_SPACE || argE.getKeyChar() == KeyEvent.VK_DELETE){ setSelectedItem(null); super.hidePopup(); }else{ super.processKeyEvent(argE); } } /** * Sets the style of this combo box * @param argStyle */ public void setStyle(MVCJComboBoxStyle argStyle){ style = argStyle; if(style == MVCJComboBoxStyle.SORT){ if(comparator == null){ throw new NullPointerException("DynamicJComboBox style is set to Alpha Sort, but the comparator is null."); } model.sort(comparator); } } public void refreshData(){ synchronized (lock) { // remove all elements model.removeAllElements(); if(getData() == null){ return; } for(E e: getData()){ if(filter.showItem(e)){ model.addElement(e); } } if(style == MVCJComboBoxStyle.SORT){ if(comparator == null){ throw new NullPointerException("DynamicJComboBox style is set to Alpha Sort, but the comparator is null."); } model.sort(comparator); } } } private void add(E argNewObj) { boolean b = filter.showItem(argNewObj); if (b == false) { return; } synchronized (lock) { switch(style){ case SORT:{ if(comparator == null){ throw new NullPointerException("DynamicJComboBox style is set to Alpha Sort, but the comparator is null."); } boolean inserted = false; for(int i=0; i<model.getSize(); i++){ E e = model.getElementAt(i); if(comparator.compare(e, argNewObj) > 0){ model.insertElementAt(argNewObj, i); inserted = true; break; } } if(!inserted){ model.addElement(argNewObj); } break; } case ADD_NEW_TO_BEGINNING:{ model.insertElementAt(argNewObj, 0); break; } case ADD_NEW_TO_END:{ model.addElement(argNewObj); } } } } private void addAll(Collection<E> argNewObjects) { LinkedList<E> filtered = new LinkedList<E>(); Iterator<E> it = argNewObjects.iterator(); while(it.hasNext()){ E e = it.next(); if(filter.showItem(e)){ filtered.add(e); } } if(filtered.size() == 0){ return; } synchronized (lock) { switch(style){ case SORT:{ if(comparator == null){ throw new NullPointerException("DynamicJComboBox style is set to Alpha Sort, but the comparator is null."); } model.addElements(filtered); model.sort(comparator); break; } case ADD_NEW_TO_BEGINNING:{ model.addElements(0, filtered); break; } case ADD_NEW_TO_END:{ model.addElements(filtered); } } } } private void change(E argOld, E argNew) { boolean so = filter.showItem(argOld); boolean sn = filter.showItem(argNew); if(!sn){ remove(argOld); return; } if(!so){ if(sn){ add(argNew); return; }else{ return; } } synchronized (lock) { int size = model.getSize(); for (int i = 0; i < size; i++) { E e = model.getElementAt(i); if (e == argOld) { model.setElementAt(argNew, i); return; } } if(style == MVCJComboBoxStyle.SORT){ if(comparator == null){ throw new NullPointerException("DynamicJComboBox style is set to Alpha Sort, but the comparator is null."); } model.sort(comparator); } } } private void remove(E argVal) { boolean is = filter.showItem(argVal); if (!is) { return; } synchronized (lock) { for(int i=0; i<model.getSize();i ++){ E e = model.getElementAt(i); if(e == argVal){ model.removeElementAt(i); return; } } } } }
mit
jwfwessels/AFK
src/afk/ge/tokyo/ems/systems/DebugRenderSystem.java
6629
/* * Copyright (c) 2013 Triforce - in association with the University of Pretoria and Epi-Use <Advance/> * * 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 afk.ge.tokyo.ems.systems; import afk.bot.london.Sonar; import afk.ge.BBox; import afk.ge.ems.Engine; import afk.ge.ems.ISystem; import afk.ge.ems.Utils; import afk.ge.tokyo.ems.components.Camera; import afk.ge.tokyo.ems.components.Display; import afk.ge.tokyo.ems.components.Mouse; import afk.ge.tokyo.ems.components.Selection; import afk.ge.tokyo.ems.nodes.CollisionNode; import afk.ge.tokyo.ems.nodes.SonarNode; import afk.gfx.GfxEntity; import static afk.gfx.GfxEntity.*; import static afk.gfx.GfxUtils.X_AXIS; import static afk.gfx.GfxUtils.Y_AXIS; import static afk.gfx.GfxUtils.Z_AXIS; import afk.gfx.GraphicsEngine; import com.hackoeur.jglm.Mat4; import com.hackoeur.jglm.Matrices; import com.hackoeur.jglm.Vec3; import com.hackoeur.jglm.Vec4; import java.util.List; /** * * @author daniel */ public class DebugRenderSystem implements ISystem { Engine engine; GraphicsEngine gfxEngine; public DebugRenderSystem(GraphicsEngine gfxEngine) { this.gfxEngine = gfxEngine; } @Override public boolean init(Engine engine) { this.engine = engine; return true; } @Override public void update(float t, float dt) { Camera camera = engine.getGlobal(Camera.class); Mouse mouse = engine.getGlobal(Mouse.class); Display display = engine.getGlobal(Display.class); Selection selection = engine.getGlobal(Selection.class); List<CollisionNode> nodes = engine.getNodeList(CollisionNode.class); for (CollisionNode node : nodes) { BBox bbox = new BBox(node.state, node.bbox); GfxEntity gfx = gfxEngine.getDebugEntity(bbox); gfx.position = bbox.getCenterPoint(); gfx.rotation = node.state.rot; gfx.scale = new Vec3(1); gfx.colour = selection.getEntity() == node.entity ? GREEN : MAGENTA; } List<SonarNode> snodes = engine.getNodeList(SonarNode.class); for (SonarNode node : snodes) { final Vec3[] POS_AXIS = { X_AXIS, Y_AXIS, Z_AXIS }; final Vec3[] NEG_AXIS = { X_AXIS.getNegated(), Y_AXIS.getNegated(), Z_AXIS.getNegated() }; Sonar sonar = node.controller.events.sonar; Mat4 m = Utils.getMatrix(node.state); Vec3 pos = node.state.pos.add(m.multiply(node.bbox.offset.toDirection()).getXYZ()); float[] sonarmins = { sonar.distance[3], sonar.distance[4], sonar.distance[5] }; float[] sonarmaxes = { sonar.distance[0], sonar.distance[1], sonar.distance[2] }; for (int i = 0; i < 3; i++) { if (!Float.isNaN(node.sonar.min.get(i))) { drawSonar(node, NEG_AXIS[i], sonarmins[i], node.sonar.min.get(i), pos.subtract(m.multiply(NEG_AXIS[i].scale(node.bbox.extent.get(i)).toDirection()).getXYZ())); } if (!Float.isNaN(node.sonar.max.get(i))) { drawSonar(node, POS_AXIS[i], sonarmaxes[i], node.sonar.max.get(i), pos.add(m.multiply(POS_AXIS[i].scale(node.bbox.extent.get(i)).toDirection()).getXYZ())); } } gfxEngine.getDebugEntity(new Vec3[] { new Vec3(-1000, 0, 0), new Vec3(1000, 0, 0) }).colour = new Vec3(0.7f, 0, 0); gfxEngine.getDebugEntity(new Vec3[] { new Vec3(0, -1000, 0), new Vec3(0, 1000, 0) }).colour = new Vec3(0, 0.7f, 0); gfxEngine.getDebugEntity(new Vec3[] { new Vec3(0, 0, -1000), new Vec3(0, 0, 1000) }).colour = new Vec3(0, 0, 0.7f); final float fov = 60.0f, near = 0.1f, far = 200.0f; Mat4 proj = Matrices.perspective(fov, display.screenWidth/display.screenHeight, near, far); Mat4 view = Matrices.lookAt(camera.eye, camera.at, camera.up); Mat4 cam = proj.multiply(view); Mat4 camInv = cam.getInverse(); Vec4 mouseNear4 = camInv.multiply(new Vec4(mouse.nx,mouse.ny,-1,1)); Vec4 mouseFar4 = camInv.multiply(new Vec4(mouse.nx,mouse.ny,1,1)); Vec3 mouseNear = mouseNear4.getXYZ().scale(1.0f/mouseNear4.getW()); Vec3 mouseFar = mouseFar4.getXYZ().scale(1.0f/mouseFar4.getW()); gfxEngine.getDebugEntity(new Vec3[] { mouseNear, mouseFar }).colour = new Vec3(1,0,0); } } private void drawSonar(SonarNode node, Vec3 axis, float sonar, float value, Vec3 pos) { GfxEntity gfx = gfxEngine.getDebugEntity(new Vec3[] { Vec3.VEC3_ZERO, axis.scale((Float.isInfinite(sonar) ? value : sonar)) }); gfx.position = pos; gfx.rotation = node.state.rot; gfx.scale = new Vec3(1); gfx.colour = MAGENTA; } @Override public void destroy() { } }
mit
chinnychin19/CS308_Proj3
src/view/menuBar/workspace/WorkSpacePreferenceReader.java
1836
package view.menuBar.workspace; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.swing.JOptionPane; import view.Constants; import view.ViewController; /** * Class that reads in workspace preference files * * @author Lalita Maraj * @author Susan Zhang * */ public class WorkSpacePreferenceReader { private ViewController myController; public WorkSpacePreferenceReader (ViewController controller) { myController = controller; } public void loadPreferences (File prefFile) throws IOException { BufferedReader br = new BufferedReader(new FileReader(prefFile)); String sCurrentLine = br.readLine(); if (!sCurrentLine.equals("preferences")) { JOptionPane.showMessageDialog(null, Constants.WRONG_PREF_FILE_MESSAGE); } while ((sCurrentLine = br.readLine()) != null) { String[] s = sCurrentLine.split(" "); if (s[0].equals(Constants.BACKGROUND_KEYWORD) && s.length == Constants.COLOR_LINE_LENGTH) { myController.setBGColor(Integer.parseInt(s[1])); setPalette(s[1], s[2], s[3], s[4]); } if (s[0].equals(Constants.PEN_KEYWORD) && s.length == Constants.COLOR_LINE_LENGTH) { myController.setPenColor(Integer.parseInt(s[1])); setPalette(s[1], s[2], s[3], s[4]); } if (s[0].equals(Constants.IMAGE_KEYWORD) && s[1] != null) { myController.changeImage(Integer.parseInt(s[1])); } } br.close(); } private void setPalette(String index, String r, String g, String b){ myController.setPalette(Integer.parseInt(index), Integer.parseInt(r), Integer.parseInt(g), Integer.parseInt(b)); } }
mit
swaplicado/siie32
src/erp/cfd/SCfdiSignature.java
1709
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.cfd; import java.io.Serializable; /** * * @author Juan Barajas */ public final class SCfdiSignature implements Serializable { private String msUuid; private String msFechaTimbrado; private String msSelloCFD; private String msNoCertificadoSAT; private String msSelloSAT; private String msRfcEmisor; private String msRfcReceptor; private double mdTotalCy; public SCfdiSignature() { msUuid = ""; msFechaTimbrado = ""; msSelloCFD = ""; msNoCertificadoSAT = ""; msSelloSAT = ""; msRfcEmisor = ""; msRfcReceptor = ""; mdTotalCy = 0; } public void setUuid(String s) { msUuid = s; } public void setFechaTimbrado(String s) { msFechaTimbrado = s; } public void setSelloCFD(String s) { msSelloCFD = s; } public void setNoCertificadoSAT(String s) { msNoCertificadoSAT = s; } public void setSelloSAT(String s) { msSelloSAT = s; } public void setRfcEmisor(String s) { msRfcEmisor = s; } public void setRfcReceptor(String s) { msRfcReceptor = s; } public void setTotalCy(double d) { mdTotalCy = d; } public String getUuid() { return msUuid; } public String getFechaTimbrado() { return msFechaTimbrado; } public String getSelloCFD() { return msSelloCFD; } public String getNoCertificadoSAT() { return msNoCertificadoSAT; } public String getSelloSAT() { return msSelloSAT; } public String getRfcEmisor() { return msRfcEmisor; } public String getRfcReceptor() { return msRfcReceptor; } public double getTotalCy() { return mdTotalCy; } }
mit
SpongePowered/Sponge
src/main/java/org/spongepowered/common/entity/ai/goal/SpongeGoalType.java
1809
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.entity.ai.goal; import org.spongepowered.api.entity.ai.goal.Goal; import org.spongepowered.api.entity.ai.goal.GoalType; import org.spongepowered.api.entity.living.Agent; public final class SpongeGoalType implements GoalType { private final Class<? extends Goal<? extends Agent>> goalClass; public SpongeGoalType(final Class<? extends Goal<? extends Agent>> goalClass) { this.goalClass = goalClass; } @Override public Class<? extends Goal<?>> goalClass() { return this.goalClass; } }
mit
Ehbraheem/Baking-Time
app/src/main/java/com/example/profbola/bakingtime/provider/IngredientDbHelper.java
2247
package com.example.profbola.bakingtime.provider; import android.database.sqlite.SQLiteDatabase; import com.example.profbola.bakingtime.provider.RecipeContract.IngredientEntry; import static com.example.profbola.bakingtime.utils.RecipeConstants.IngredientDbHelperConstants.INGREDIENT_RECIPE_ID_IDX; /** * Created by prof.BOLA on 6/23/2017. */ public class IngredientDbHelper { // private static final String DATABASE_NAME = "bakingtime.db"; // private static final int DATABASE_VERSION = 1; // public IngredientDbHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } public static void onCreate(SQLiteDatabase db) { final String SQL_CREATE_INGREDIENTS_TABLE = "CREATE TABLE " + IngredientEntry.TABLE_NAME + " ( " + IngredientEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + IngredientEntry.COLUMN_INGREDIENT + " STRING NOT NULL, " + IngredientEntry.COLUMN_MEASURE + " STRING NOT NULL, " + IngredientEntry.COLUMN_QUANTITY + " REAL NOT NULL, " + IngredientEntry.COLUMN_RECIPE_ID + " INTEGER, " + " FOREIGN KEY ( " + IngredientEntry.COLUMN_RECIPE_ID + " ) REFERENCES " + RecipeContract.RecipeEntry.TABLE_NAME + " ( " + RecipeContract.RecipeEntry.COLUMN_ID + " ) " + " UNIQUE ( " + IngredientEntry.COLUMN_INGREDIENT + " , " + IngredientEntry.COLUMN_RECIPE_ID + " ) ON CONFLICT REPLACE " + ");"; final String SQL_CREATE_INDEX = "CREATE INDEX " + INGREDIENT_RECIPE_ID_IDX + " ON " + IngredientEntry.TABLE_NAME + " ( " + IngredientEntry.COLUMN_RECIPE_ID + " );"; db.execSQL(SQL_CREATE_INGREDIENTS_TABLE); db.execSQL(SQL_CREATE_INDEX); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + IngredientEntry.TABLE_NAME); onCreate(db); } }
mit
hghwng/mooc-algs1
2/RandomizedQueue.java
2505
import java.util.Iterator; import java.util.NoSuchElementException; @SuppressWarnings("unchecked") public class RandomizedQueue<Item> implements Iterable<Item> { private Item[] _arr; private int _length = 0; private void resize(int newLength) { if (newLength > _arr.length) newLength = 2 * _arr.length; else if (newLength < _arr.length / 4) newLength = _arr.length / 2; else return; Item[] newArr = (Item[])(new Object[newLength]); for (int i = 0; i < _length; ++i) { newArr[i] = _arr[i]; } _arr = newArr; } public RandomizedQueue() { _arr = (Item[])(new Object[1]); } public boolean isEmpty() { return _length == 0; } public int size() { return _length; } public void enqueue(Item item) { if (item == null) throw new NullPointerException(); resize(_length + 1); _arr[_length] = item; ++_length; } public Item dequeue() { if (_length == 0) throw new NoSuchElementException(); int idx = StdRandom.uniform(_length); Item ret = _arr[idx]; _arr[idx] = _arr[_length - 1]; _arr[_length - 1] = null; --_length; resize(_length); return ret; } public Item sample() { if (_length == 0) throw new NoSuchElementException(); return _arr[StdRandom.uniform(_length)]; } private class RandomizedQueueIterator implements Iterator<Item> { Item[] _state; int _current = 0; public RandomizedQueueIterator() { _state = (Item[])(new Object[_length]); for (int i = 0; i < _length; ++i) { _state[i] = _arr[i]; } StdRandom.shuffle(_state); } public boolean hasNext() { return _current != _state.length; } public Item next() { if (!hasNext()) throw new NoSuchElementException(); return _state[_current++]; } public void remove() { throw new UnsupportedOperationException(); } } public Iterator<Item> iterator() { return new RandomizedQueueIterator(); } public static void main(String[] args) { RandomizedQueue<Integer> queue = new RandomizedQueue<Integer>(); for (int i = 0; i < 10; ++i) { queue.enqueue(i); } for (int e: queue) { StdOut.println(e); } } }
mit
ivelin1936/Studing-SoftUni-
Programming Fundamentals/Basics-MoreExercises/src/com/company/TrainingHallEquipment.java
1209
package com.company; import java.util.Scanner; public class TrainingHallEquipment { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double budget = Double.parseDouble(scanner.nextLine()); int numberOfItems = Integer.parseInt(scanner.nextLine()); double subTotal = 0; for (int i = 1; i <= numberOfItems ; i++) { String itemName = scanner.nextLine(); double itemPrice = Double.parseDouble(scanner.nextLine()); int itemCount = Integer.parseInt(scanner.nextLine()); if (itemCount == 1) { System.out.printf("Adding %d %s to cart.%n", itemCount, itemName); } else { System.out.printf("Adding %d %ss to cart.%n", itemCount, itemName); } subTotal += itemCount * itemPrice; } System.out.printf("Subtotal: $%.2f %n", subTotal); if (subTotal <= budget) { System.out.printf("Money left: $%.2f", (budget - subTotal)); } else { System.out.printf("Not enough. We need $%.2f more.", (subTotal - budget)); } } }
mit
superdyzio/PWR-Stuff
INF/Algorytmy i Struktury Danych/zad1/main.java
2259
import java.io.IOException; import java.util.Scanner; import iterators.*; import User.User; public class main { public static void zad1(ArrayIterator it){ PredicateCoN pred = new PredicateCoN(4); PredicateCoN pred2 = new PredicateCoN(2); IteratorCoN con = new IteratorCoN(it,pred); IteratorCoN co = new IteratorCoN(con,pred2); System.out.printf("Ostatni element ogólnie: %s\n",((User)it.current()).login); co.last(); System.out.printf("Ostatni element wg iteratora: %s\n",((User)co.current()).login); User pom; while(!co.isDone()) { pom = (User) con.current(); System.out.println(pom.login); co.previous(); } } public static void zad2(ArrayIterator it){ PredicateZad2 pred = new PredicateZad2(); IteratorZad2 zad = new IteratorZad2(it,pred); zad.first(); User pom; while (!zad.isDone()) { pom = (User) zad.current(); System.out.println(pom.login); zad.next(); } } public static void zad3(ArrayIterator it){ PredicateZad3 pred = new PredicateZad3(); IteratorZad3 zad = new IteratorZad3(it,pred); zad.first(); User pom; while (!zad.isDone()) { pom = (User) zad.current(); System.out.println(pom.login); zad.next(); } } public static void main(final String[] args) throws IOException { final int n = 14; User[] tab = new User[n]; Scanner wej = new Scanner(System.in); tab[0] = new User("Andrzej",1000,null,0); tab[1] = new User("Bogdan",-200,tab[0],1); tab[2] = new User("Cyprian",-100,null,2); tab[3] = new User("Dawid",23000,null,3); tab[4] = new User("Ebi",500,tab[2],4); tab[5] = new User("Franek",-60,tab[1],5); tab[6] = new User("George",70,null,6); tab[7] = new User("Henryk",-8,null,7); tab[8] = new User("Ignacy",900,null,8); tab[9] = new User("Ja",900,tab[7],9); tab[10] = new User("Kociao",100,null,10); tab[11] = new User("Lol",-111,tab[10],11); tab[12] = new User("Misiek",120,null,12); tab[13] = new User("Nowy",1300,tab[6],13); ArrayIterator it = new ArrayIterator(tab,0,n); it.last(); System.out.println("Które zadanie chcesz wyœwietliæ?"); int wybor = wej.nextInt(); switch (wybor) { case 1: zad1(it); break; case 2: zad2(it); break; case 3: zad3(it); } wej.close(); } }
mit
BahodirBoydedayev/conferenceApp
src/main/java/app/location/Location.java
454
package app.location; import app.core.BaseEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @NoArgsConstructor @AllArgsConstructor @Getter @Setter @Entity @Table(name = "app_location") public class Location extends BaseEntity { @Column(name = "name") private String name; }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.s13e.datavisualization/src/Variation_Diff/validation/EntityTypeValidator.java
534
/** * * $Id$ */ package Variation_Diff.validation; /** * A sample validator interface for {@link Variation_Diff.EntityType}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface EntityTypeValidator { boolean validate(); boolean validateType(String value); }
mit
dayse/gesplan
src/xfuzzy/xfplot/Xfplot2DPanel.java
6711
//--------------------------------------------------------------------------------// // COPYRIGHT NOTICE // //--------------------------------------------------------------------------------// // Copyright (c) 2012, Instituto de Microelectronica de Sevilla (IMSE-CNM) // // // // All rights reserved. // // // // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions are met: // // // // * Redistributions of source code must retain the above copyright notice, // // this list of conditions and the following disclaimer. // // // // * Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // // // * Neither the name of the IMSE-CNM 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 HOLDERS 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 xfuzzy.xfplot; import javax.swing.*; import java.awt.*; /** * Clase que desarrolla el panel para la representación gráfica en 2 * dimensiones * * @author Francisco José Moreno Velo * */ public class Xfplot2DPanel extends JPanel { //----------------------------------------------------------------------------// // CONSTANTES PRIVADAS // //----------------------------------------------------------------------------// /** * Código asociado a la clase serializable */ private static final long serialVersionUID = 95505666603053L; /** * Altura del panel */ private static final int HEIGHT = 500; /** * Anchura del panel */ private static final int WIDTH = 700; //----------------------------------------------------------------------------// // MIEMBROS PRIVADOS // //----------------------------------------------------------------------------// /** * Referencia al apágina principal de la aplicación */ private Xfplot xfplot; //----------------------------------------------------------------------------// // CONSTRUCTOR // //----------------------------------------------------------------------------// /** * Constructor */ public Xfplot2DPanel(Xfplot xfplot) { super(); this.xfplot = xfplot; setSize(new Dimension(WIDTH,HEIGHT)); setPreferredSize(new Dimension(WIDTH,HEIGHT)); setBackground(Color.white); setBorder(BorderFactory.createLoweredBevelBorder()); } //----------------------------------------------------------------------------// // MÉTODOS PÚBLICOS // //----------------------------------------------------------------------------// /** * Pinta la representación gráfica. * Este método sobreescribe el método paint() de JPanel(). */ public void paint(Graphics g) { super.paint(g); paintAxis(g); paintVariables(g); paintFunction(g); } //----------------------------------------------------------------------------// // MÉTODOS PRIVADOS // //----------------------------------------------------------------------------// /** * Dibuja los ejes de la representación gráfica */ private void paintAxis(Graphics g) { int width = getSize().width; int height = getSize().height; int xmin = width/8; int xmax = width*7/8; int ymin = height*7/8; int ymax = height/8; g.drawLine(xmin, ymin, xmin, ymax); g.drawLine(xmin, ymin, xmax, ymin); for(int i=0; i<6; i++) { int y = ymin + (ymax - ymin)*i/5; g.drawLine(xmin-3, y, xmin, y); } for(int i=0; i<6; i++) { int x = xmin + (xmax - xmin)*i/5; g.drawLine(x, ymin+3, x, ymin); } } /** * Dibuja los nombres de las variables a representar */ private void paintVariables(Graphics g) { int width = getSize().width; int height = getSize().height; int xx = width * 9 / 10; int xy = height * 9 / 10; int yx = width / 10; int yy = height / 10; g.drawString(xfplot.getXVariable().toString(), xx, xy); g.drawString(xfplot.getZVariable().toString(), yx, yy); } /** * Dibuja la función en tramos lineales */ private void paintFunction(Graphics g) { double function[] = xfplot.get2DFunction(); if(function == null) return; int x0, y0, x1, y1; int width = getSize().width; int height = getSize().height; int xrange = width * 3 / 4; int yrange = height * 3 / 4; int xmin = width/8; int ymin = height*7/8; Color old = g.getColor(); g.setColor(Color.red); x0 = xmin; y0 = ymin - (int) Math.round(function[0]*yrange); for(int i=1; i<function.length; i++) { x1 = xmin + i*xrange/(function.length-1); y1 = ymin - (int) Math.round(function[i]*yrange); g.drawLine(x0,y0,x1,y1); x0 = x1; y0 = y1; } g.setColor(old); } }
mit
DeyuGoGo/EasyJavaDesignPatterns
HeadFirstDesignPatterns/src/proxy/test/Server.java
622
package proxy.test; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import util.JavaLog; public class Server extends UnicastRemoteObject implements RemoteInterface{ private static final long serialVersionUID = 1L; protected Server() throws RemoteException { super(); } public static void main(String[] args) { try { RemoteInterface service = new Server(); Naming.rebind("Hello", service); JavaLog.d("sadfasfd"); } catch (Exception e) { JavaLog.d("sadfasfd:" + e); } } @Override public String Hi() { return "Hello,Deyu"; } }
mit
Open-RIO/ToastAPI
src/main/java/jaci/openrio/toast/core/loader/simulation/GuiRobotState.java
3232
package jaci.openrio.toast.core.loader.simulation; import jaci.openrio.toast.lib.state.RobotState; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; /** * A GUI Element for switching the Robot State during Simulation * * @author Jaci */ public class GuiRobotState extends JComponent implements MouseListener { RobotState state; int x, y; int width = 100; int height = 30; static final Color bgPassive = new Color(20, 20, 20); static final Color bgClicked = new Color(11, 11, 11); static final Color fgPassive = new Color(100, 100, 100); public GuiRobotState(int x, int y, RobotState state, JPanel parent) { this.x = x; this.y = y; this.state = state; this.setBounds(x, y, width, height); parent.add(this); parent.addMouseListener(this); this.setBackground(bgPassive); this.setForeground(fgPassive); } /** * Paints the component. This calls the super as well as calling the second 'paint()' method that will * draw the button based on the state given in {@link SimulationData} */ public void paintComponent(Graphics g) { super.paintComponent(g); paint((Graphics2D) g); } /** * Paints the object with the new Graphics2D object. This takes data from the {@link SimulationData} class in order * to paint the correct button. */ public void paint(Graphics2D g) { g.setColor(this.getBackground()); g.fillRect(0, 0, width, height); g.setColor(SimulationData.currentState == state ? new Color(100, 170, 100) : this.getForeground()); FontMetrics metrics = g.getFontMetrics(); Rectangle2D textBounds = metrics.getStringBounds(state.state, g); g.drawString(state.state, (float) ((width - textBounds.getWidth()) / 2), (float) ((height - textBounds.getHeight()) / 2 + metrics.getAscent())); } /** * Does a check for whether or not the Mouse exists within the bounds of the button. */ public boolean inBounds(MouseEvent e) { return e.getX() > x && e.getX() < x + width && e.getY() > y && e.getY() < y + height; } /** * Apply this button */ public void apply() { SimulationData.currentState = this.state; repaint(); } /** * Stub Method - Not Used */ @Override public void mouseClicked(MouseEvent e) { } /** * Serves to change the colour of the button to indicate it being depressed. */ @Override public void mousePressed(MouseEvent e) { if (inBounds(e)) { this.setBackground(bgClicked); } this.repaint(); } /** * Invokes the new state change */ @Override public void mouseReleased(MouseEvent e) { if (inBounds(e)) apply(); this.setBackground(bgPassive); this.repaint(); } /** * Stub Method - Not Used */ @Override public void mouseEntered(MouseEvent e) { } /** * Stub Method - Not Used */ @Override public void mouseExited(MouseEvent e) { } }
mit
YangMann/drone-slam
drone-slam/src/drone_slam/apps/controlcenter/plugins/attitudechart/AttitudeChartPanel.java
1902
package drone_slam.apps.controlcenter.plugins.attitudechart; import drone_slam.apps.controlcenter.ICCPlugin; import drone_slam.base.IARDrone; import drone_slam.base.navdata.AttitudeListener; import org.jfree.chart.ChartPanel; import javax.swing.*; import java.awt.*; public class AttitudeChartPanel extends JPanel implements ICCPlugin { private IARDrone drone; private AttitudeChart chart; public AttitudeChartPanel() { super(new GridBagLayout()); this.chart = new AttitudeChart(); JPanel chartPanel = new ChartPanel(chart.getChart(), true, true, true, true, true); add(chartPanel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); } private AttitudeListener attitudeListener = new AttitudeListener() { public void windCompensation(float pitch, float roll) { } public void attitudeUpdated(float pitch, float roll) { } public void attitudeUpdated(float pitch, float roll, float yaw) { chart.setAttitude(pitch / 1000, roll / 1000, yaw / 1000); } }; public void activate(IARDrone drone) { this.drone = drone; drone.getNavDataManager().addAttitudeListener(attitudeListener); } public void deactivate() { drone.getNavDataManager().removeAttitudeListener(attitudeListener); } public String getTitle() { return "Attitude Chart"; } public String getDescription() { return "Displays a chart with the latest pitch, roll and yaw"; } public boolean isVisual() { return true; } public Dimension getScreenSize() { return new Dimension(330, 250); } public Point getScreenLocation() { return new Point(330, 390); } public JPanel getPanel() { return this; } }
mit
wallner/connector4java
src/main/java/org/osiam/client/OsiamUserService.java
15934
package org.osiam.client; /* * for licensing see the file license.txt. */ import static org.apache.http.HttpStatus.SC_FORBIDDEN; import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; import static org.apache.http.HttpStatus.SC_CONFLICT; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.DefaultHttpClient; import org.osiam.client.exception.ConflictException; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.ForbiddenException; import org.osiam.client.exception.NoResultException; import org.osiam.client.exception.UnauthorizedException; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.client.query.QueryResult; import org.osiam.client.update.UpdateUser; import org.osiam.resources.scim.User; /** * The OsiamUserService provides all methods necessary to manipulate the User-entries registered in the * given OSIAM installation. For the construction of an instance please use the included {@link OsiamUserService.Builder} */ public final class OsiamUserService extends AbstractOsiamService<User> { // NOSONAR - Builder constructs instances of this class /** * The private constructor for the OsiamUserService. Please use the {@link OsiamUserService.Builder} * to construct one. * * @param userWebResource a valid WebResource to connect to a given OSIAM server */ private OsiamUserService(Builder builder) { super(builder); } /** * Retrieve a single User with the given id. If no user for the given id can be found a {@link NoResultException} * is thrown. * * @param id the id of the wanted user * @param accessToken the OSIAM access token from for the current session * @return the user with the given id * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.NoResultException if no user with the given id can be found * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public User getUser(String id, AccessToken accessToken) { return getResource(id, accessToken); } /** * Retrieve the User who holds the given access token. * Not to be used for the grant Client-Credentials * @param accessToken the OSIAM access token from for the current session * @return the actual logged in user * @throws UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws ConnectionInitializationException * if no connection to the given OSIAM services could be initialized */ public User getMeBasic(AccessToken accessToken) { final User user; if (accessToken == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The given accessToken can't be null."); } try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet realWebresource = createRealWebResource(accessToken); realWebresource.setURI(new URI(getMeWebResource().getURI().toString())); HttpResponse response = httpclient.execute(realWebresource); int httpStatus = response.getStatusLine().getStatusCode(); if (httpStatus != SC_OK) { // NOSONAR - false-positive from clover; if-expression is correct String errorMessage; switch (httpStatus) { case SC_UNAUTHORIZED: errorMessage = getErrorMessage(response, "You are not authorized to access OSIAM. Please make sure your access token is valid"); throw new UnauthorizedException(errorMessage); case SC_FORBIDDEN: errorMessage = "Insufficient scope (" + accessToken.getScope() + ") to retrieve the actual User."; throw new ForbiddenException(errorMessage); case SC_CONFLICT: errorMessage = getErrorMessage(response, "Unable to retrieve the actual User."); throw new ConflictException(errorMessage); default: errorMessage = getErrorMessage(response, String.format("Unable to setup connection (HTTP Status Code: %d)", httpStatus)); throw new ConnectionInitializationException(errorMessage); } } InputStream content = response.getEntity().getContent(); user = mapSingleResourceResponse(content); return user; } catch (IOException | URISyntaxException e) { throw new ConnectionInitializationException("Unable to setup connection", e); } } /** * Retrieve the User who holds the given access token. * Not to be used for the grant Client-Credentials * @param accessToken the OSIAM access token from for the current session * @return the actual logged in user * @throws UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws ConnectionInitializationException * if no connection to the given OSIAM services could be initialized */ public User getMe(AccessToken accessToken) { final User user; if (accessToken == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The given accessToken can't be null."); } try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet realWebresource = createRealWebResource(accessToken); realWebresource.setURI(new URI(getUri() + "/me")); HttpResponse response = httpclient.execute(realWebresource); int httpStatus = response.getStatusLine().getStatusCode(); if (httpStatus != SC_OK) { // NOSONAR - false-positive from clover; if-expression is correct String errorMessage; switch (httpStatus) { case SC_UNAUTHORIZED: errorMessage = getErrorMessage(response, "You are not authorized to access OSIAM. Please make sure your access token is valid"); throw new UnauthorizedException(errorMessage); case SC_FORBIDDEN: errorMessage = "Insufficient scope (" + accessToken.getScope() + ") to retrieve the actual User."; throw new ForbiddenException(errorMessage); case SC_CONFLICT: errorMessage = getErrorMessage(response, "Unable to retrieve the actual User."); throw new ConflictException(errorMessage); default: errorMessage = getErrorMessage(response, String.format("Unable to setup connection (HTTP Status Code: %d)", httpStatus)); throw new ConnectionInitializationException(errorMessage); } } InputStream content = response.getEntity().getContent(); user = mapSingleResourceResponse(content); return user; } catch (IOException | URISyntaxException e) { throw new ConnectionInitializationException("Unable to setup connection", e); } } protected HttpGet getMeWebResource() { HttpGet webResource; try { webResource = new HttpGet(new URI(getEndpoint() + "/me")); webResource.addHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()); } catch (URISyntaxException e) { throw new ConnectionInitializationException("Unable to setup connection " + getEndpoint() + "is not a valid URI.", e); } return webResource; } /** * Retrieve a list of the of all {@link User} resources saved in the OSIAM service. * If you need to have all User but the number is very big, this method can be slow. * In this case you can also use Query.Builder with no filter to split the number of User returned * * @param accessToken * @return a list of all Users * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public List<User> getAllUsers(AccessToken accessToken) { return super.getAllResources(accessToken); } /** * Search for the existing Users by a given search string. For more detailed information about the possible * logical operators and usable fields please have a look into the wiki.<p> * <b>Note:</b> The query string should be URL encoded! * * @param queryString The URL encoded string with the query that should be passed to the OSIAM service * @param accessToken the OSIAM access token from for the current session * @return a QueryResult Containing a list of all found Users * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized * @see <a href="https://github.com/osiam/connector4java/wiki/Working-with-user#search-for-user">https://github.com/osiam/connector4java/wiki/Working-with-user#search-for-user</a> */ public QueryResult<User> searchUsers(String queryString, AccessToken accessToken) { return super.searchResources(queryString, accessToken); } /** * Search for existing Users by the given {@link Query}. * * @param query containing the query to execute. * @param accessToken the OSIAM access token from for the current session * @return a QueryResult Containing a list of all found Users * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public QueryResult<User> searchUsers(Query query, AccessToken accessToken) { return super.searchResources(query, accessToken); } /** * delete the given {@link User} at the OSIAM DB. * @param id id of the User to be delete * @param accessToken the OSIAM access token from for the current session * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.NoResultException if no user with the given id can be found * @throws org.osiam.client.exception.ConflictException if the User could not be deleted * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public void deleteUser(String id, AccessToken accessToken) { deleteResource(id, accessToken); } /** * saves the given {@link User} to the OSIAM DB. * @param user user to be saved * @param accessToken the OSIAM access token from for the current session * @return the same user Object like the given but with filled metadata and a new valid id * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ConflictException if the User could not be created * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public User createUser(User user, AccessToken accessToken) { return createResource(user, accessToken); } /** * update the user of the given id with the values given in the User Object. * For more detailed information how to set new field, update Fields or to delete Fields please look in the wiki * @param id if of the User to be updated * @param updateUser all Fields that need to be updated * @param accessToken the OSIAM access token from for the current session * @return the updated User Object with all new Fields * @see <a href="https://github.com/osiam/connector4java/wiki/Working-with-user">https://github.com/osiam/connector4java/wiki/Working-with-user</a> * @throws org.osiam.client.exception.UnauthorizedException if the request could not be authorized. * @throws org.osiam.client.exception.ConflictException if the User could not be updated * @throws org.osiam.client.exception.NotFoundException if no group with the given id can be found * @throws org.osiam.client.exception.ForbiddenException if the scope doesn't allow this request * @throws org.osiam.client.exception.ConnectionInitializationException * if the connection to the given OSIAM service could not be initialized */ public User updateUser(String id, UpdateUser updateUser , AccessToken accessToken){ if (updateUser == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The given updateUser can't be null."); } return updateResource(id, updateUser.getScimConformUpdateUser(), accessToken); } /** * The Builder class is used to construct instances of the {@link OsiamUserService} */ public static class Builder extends AbstractOsiamService.Builder<User> { /** * Set up the Builder for the construction of an {@link OsiamUserService} instance for the OSIAM service at * the given endpoint * * @param endpoint The URL at which the OSIAM server lives. */ public Builder(String endpoint) { super(endpoint); } /** * constructs an OsiamUserService with the given values * * @return a valid OsiamUserService */ public OsiamUserService build() { return new OsiamUserService(this); } } }
mit
turbolent/lila
src/java/lila/runtime/StringPrintWriter.java
1802
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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 lila.runtime; import java.io.PrintWriter; import java.io.StringWriter; /** * <p>A PrintWriter that maintains a String as its backing store.</p> * * <p>Usage: * <pre> * StringPrintWriter out = new StringPrintWriter(); * printTo(out); * System.out.println( out.getString() ); * </pre> * </p> * * @author Alex Chaffee * @author Scott Stanchfield * @author Gary D. Gregory * @since 2.0 */ class StringPrintWriter extends PrintWriter { /** * Constructs a new instance. */ public StringPrintWriter() { super(new StringWriter()); } /** * Constructs a new instance using the specified initial string-buffer * size. * * @param initialSize an int specifying the initial size of the buffer. */ public StringPrintWriter(int initialSize) { super(new StringWriter(initialSize)); } /** * <p>Since toString() returns information *about* this object, we * want a separate method to extract just the contents of the * internal buffer as a String.</p> * * @return the contents of the internal string buffer */ public String getString() { flush(); return ((StringWriter) this.out).toString(); } }
mit
xaviersierra/digit-guesser
drawer/src/main/java/xsierra/digitguesser/drawer/pipeline/DigitPipeline.java
299
package xsierra.digitguesser.drawer.pipeline; import java.awt.image.BufferedImage; public interface DigitPipeline { /** * @param image An image that contains a drawed digit * @return the guessed digit, a number between 0 - 9 */ byte imageGuessDigit(BufferedImage image); }
mit
connectim/Android
app/src/main/java/connect/view/HightEqWidthRounderImage.java
759
package connect.view; import android.content.Context; import android.util.AttributeSet; import connect.view.roundedimageview.RoundedImageView; /** * Created by Administrator on 2016/12/15. */ public class HightEqWidthRounderImage extends RoundedImageView { public HightEqWidthRounderImage(Context context) { super(context); } public HightEqWidthRounderImage(Context context, AttributeSet attrs) { super(context, attrs); } public HightEqWidthRounderImage(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, widthMeasureSpec); } }
mit
dmytro-bekuzarov/projectx-api
projectx-api-domain/src/main/java/com/sind/projectx/domain/food/menu/MenuSection.java
890
package com.sind.projectx.domain.food.menu; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import java.util.ArrayList; import java.util.List; /** * @author Dmytro Bekuzarov */ public class MenuSection { @NotBlank private String name; @NotEmpty private List<String> items = new ArrayList<>(); private List<MenuSection> sections = new ArrayList<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getItems() { return items; } public void setItems(List<String> items) { this.items = items; } public List<MenuSection> getSections() { return sections; } public void setSections(List<MenuSection> sections) { this.sections = sections; } }
mit
joerg/stash-git-lfs
src/test/java/it/at/oiml/stash/lfs/MyComponentWiredTest.java
1003
// package it.at.oiml.bitbucket.lfs; // // import org.junit.Test; // import org.junit.runner.RunWith; // import com.atlassian.plugins.osgi.test.AtlassianPluginsTestRunner; // import at.oiml.bitbucket.lfs.MyPluginComponent; // import com.atlassian.sal.api.ApplicationProperties; // // import static org.junit.Assert.assertEquals; // // @RunWith(AtlassianPluginsTestRunner.class) // public class MyComponentWiredTest // { // private final ApplicationProperties applicationProperties; // private final MyPluginComponent myPluginComponent; // // public MyComponentWiredTest(ApplicationProperties applicationProperties,MyPluginComponent myPluginComponent) // { // this.applicationProperties = applicationProperties; // this.myPluginComponent = myPluginComponent; // } // // @Test // public void testMyName() // { // assertEquals("names do not match!", "myComponent:" + applicationProperties.getDisplayName(),myPluginComponent.getName()); // } // }
mit
Yujia-Xiao/Leetcode
List/Binary_Tree_Upside_Down.java
1805
/* Binary Tree Upside Down Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. For example: Given a binary tree {1,2,3,4,5}, 1 / \ 2 3 / \ 4 5 return the root of the binary tree [4,5,2,#,#,3,1]. 4 / \ 5 2 / \ 3 1 confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. Hide Tags Tree Hide Similar Problems (E) Reverse Linked List */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode upsideDownBinaryTree(TreeNode root) { TreeNode p = root, parent = null, parentRight = null; while (p!=null) { TreeNode left = p.left; p.left = parentRight; parentRight = p.right; p.right = parent; parent = p; p = left; } return parent; } } /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode upsideDownBinaryTree(TreeNode root) { if(root==null)return root; if(root.left==null && root.right==null)return root; TreeNode newRoot = upsideDownBinaryTree(root.left); root.left.left=root.right; root.left.right=root; root.left=null; root.right=null; return newRoot; } } /* 1 /\ 2 3 /\ 4 5 1 / 2 -3 / 4 - 5 */
mit
trashkalmar/MrParkingNavigator
src/ru/mail/parking/sw2/system/SwRegInfo.java
2177
package ru.mail.parking.sw2.system; import com.sonyericsson.extras.liveware.aef.registration.Registration; import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils; import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation; import android.content.ContentValues; import ru.mail.parking.R; import ru.mail.parking.ui.SettingsActivity; import static ru.mail.parking.App.app; public class SwRegInfo extends RegistrationInformation { public static final String EXTENSION_KEY = app().getPackageName(); private static final ContentValues INFO = new ContentValues(); public SwRegInfo() { INFO.put(Registration.ExtensionColumns.CONFIGURATION_ACTIVITY, SettingsActivity.class.getName()); INFO.put(Registration.ExtensionColumns.NAME, app().getString(R.string.sw_title)); INFO.put(Registration.ExtensionColumns.EXTENSION_KEY, EXTENSION_KEY); INFO.put(Registration.ExtensionColumns.LAUNCH_MODE, Registration.LaunchMode.CONTROL); String icon = ExtensionUtils.getUriString(app(), R.drawable.icon); INFO.put(Registration.ExtensionColumns.HOST_APP_ICON_URI, icon); icon = ExtensionUtils.getUriString(app(), R.drawable.icon_sw); INFO.put(Registration.ExtensionColumns.EXTENSION_48PX_ICON_URI, icon); } @Override public ContentValues getExtensionRegistrationConfiguration() { return INFO; } @Override public int getRequiredWidgetApiVersion() { return RegistrationInformation.API_NOT_REQUIRED; } @Override public int getRequiredSensorApiVersion() { return RegistrationInformation.API_NOT_REQUIRED; } @Override public int getRequiredNotificationApiVersion() { return RegistrationInformation.API_NOT_REQUIRED; } @Override public int getRequiredControlApiVersion() { return 2; } @Override public boolean controlInterceptsBackButton() { return true; } @Override public boolean isDisplaySizeSupported(int width, int height) { return width == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_width) && height == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_height); } }
mit
PATRIC3/patric3_website
portal/patric-diseaseview/src/edu/vt/vbi/patric/portlets/DiseaseOverview.java
7388
/** * **************************************************************************** * Copyright 2014 Virginia Polytechnic Institute and State University * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** */ package edu.vt.vbi.patric.portlets; import edu.vt.vbi.patric.beans.Genome; import edu.vt.vbi.patric.beans.Taxonomy; import edu.vt.vbi.patric.common.DataApiHandler; import edu.vt.vbi.patric.common.SiteHelper; import edu.vt.vbi.patric.common.SolrCore; import edu.vt.vbi.patric.dao.DBDisease; import edu.vt.vbi.patric.dao.ResultType; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectReader; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.portlet.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; public class DiseaseOverview extends GenericPortlet { private static final Logger LOGGER = LoggerFactory.getLogger(DiseaseOverview.class); private ObjectReader jsonReader; @Override public void init() throws PortletException { super.init(); ObjectMapper objectMapper = new ObjectMapper(); jsonReader = objectMapper.reader(Map.class); } @Override protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { SiteHelper.setHtmlMetaElements(request, response, "Disease Overview"); response.setContentType("text/html"); response.setTitle("Disease Overview"); String contextType = request.getParameter("context_type"); String contextId = request.getParameter("context_id"); int taxonId; List<Integer> targetGenusList = Arrays .asList(1386,773,138,234,32008,194,83553,1485,776,943,561,262,209,1637,1763,780,590,620,1279,1301,662,629); DataApiHandler dataApi = new DataApiHandler(); if (contextType.equals("genome")) { Genome genome = dataApi.getGenome(contextId); taxonId = genome.getTaxonId(); } else { taxonId = Integer.parseInt(contextId); } Taxonomy taxonomy = dataApi.getTaxonomy(taxonId); List<String> taxonLineageNames = taxonomy.getLineageNames(); List<String> taxonLineageRanks = taxonomy.getLineageRanks(); List<Integer> taxonLineageIds = taxonomy.getLineageIds(); List<Taxonomy> genusList = new LinkedList<>(); for (int i = 0; i < taxonLineageIds.size(); i++) { if (taxonLineageRanks.get(i).equals("genus") && targetGenusList.contains(taxonLineageIds.get(i))) { Taxonomy genus = new Taxonomy(); genus.setId(taxonLineageIds.get(i)); genus.setTaxonName(taxonLineageNames.get(i)); genusList.add(genus); } } if (genusList.isEmpty()) { SolrQuery query = new SolrQuery("lineage_ids:" + taxonId + " AND taxon_rank:genus AND taxon_id:(" + StringUtils.join(targetGenusList, " OR ") + ")"); String apiResponse = dataApi.solrQuery(SolrCore.TAXONOMY, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); genusList = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Taxonomy.class); } request.setAttribute("contextType", contextType); request.setAttribute("contextId", contextId); request.setAttribute("genusList", genusList); PortletRequestDispatcher prd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/disease_overview.jsp"); prd.include(request, response); } @SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { response.setContentType("application/json"); String type = request.getParameter("type"); String cId = request.getParameter("cId"); DBDisease conn_disease = new DBDisease(); int count_total; JSONArray results = new JSONArray(); PrintWriter writer = response.getWriter(); if (type.equals("incidence")) { JSONObject jsonResult = new JSONObject(); // String cType = request.getParameter("cType"); // sorting // String sort_field = request.getParameter("sort"); // String sort_dir = request.getParameter("dir"); // Map<String, String> key = new HashMap<>(); // Map<String, String> sort = null; // // if (sort_field != null && sort_dir != null) { // sort = new HashMap<String, String>(); // sort.put("field", sort_field); // sort.put("direction", sort_dir); // } // // key.put("cId", cId); // key.put("cType", cType); count_total = 1; jsonResult.put("total", count_total); JSONObject obj = new JSONObject(); obj.put("rownum", "1"); obj.put("pathogen", "Pathogen"); obj.put("disease", "Disease"); obj.put("incidence", "10"); obj.put("infection", "5"); results.add(obj); jsonResult.put("results", results); jsonResult.writeJSONString(writer); } else if (type.equals("disease_tree")) { JSONArray jsonResult = new JSONArray(); String tree_node = request.getParameter("node"); List<ResultType> items = conn_disease.getMeshHierarchy(cId, tree_node); if (items.size() > 0) { int min = Integer.parseInt(items.get(0).get("lvl")); try { for (ResultType item : items) { if (min == Integer.parseInt(item.get("lvl"))) { boolean flag = false; JSONObject obj = DiseaseOverview.encodeNodeJSONObject(item); String mesh_id = (String) obj.get("tree_node"); for (int j = 0; j < jsonResult.size(); j++) { JSONObject temp = (JSONObject) jsonResult.get(j); if (temp.get("tree_node").equals(mesh_id)) { flag = true; temp.put("pathogen", temp.get("pathogen") + "<br>" + obj.get("pathogen")); temp.put("genome", temp.get("genome") + "<br>" + obj.get("genome")); temp.put("vfdb", temp.get("vfdb") + "<br>" + obj.get("vfdb")); temp.put("gad", temp.get("gad") + "<br>" + obj.get("gad")); temp.put("ctd", temp.get("ctd") + "<br>" + obj.get("ctd")); temp.put("taxon_id", temp.get("taxon_id") + "<br>" + obj.get("taxon_id")); jsonResult.set(j, temp); } } if (!flag) { jsonResult.add(obj); } } } } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } } jsonResult.writeJSONString(writer); } writer.close(); } @SuppressWarnings("unchecked") public static JSONObject encodeNodeJSONObject(ResultType rt) { JSONObject obj = new JSONObject(); obj.putAll(rt); obj.put("id", rt.get("tree_node")); obj.put("node", rt.get("tree_node")); obj.put("expanded", "true"); if (rt.get("leaf").equals("1")) { obj.put("leaf", "true"); } else { obj.put("leaf", "false"); } return obj; } }
mit
adamjcook/cs27500
hw1/TestDrive.java
2807
/***************************************************************************** * Course: CS 27500 * Name: Adam Joseph Cook * Email: cook5@purduecal.edu * Assignment: 1 * * The <CODE>TestDrive</CODE> Java application simulates a car being driven * depending on its provided fuel efficiency and fuel amount. * * @author Adam Joseph Cook * <A HREF="mailto:cook5@purduecal.edu"> (cook5@purduecal.edu) </A> *****************************************************************************/ import java.util.Scanner; public class TestDrive { public static void main( String[] args ) { Scanner sc = new Scanner(System.in); Car car; boolean mainDone = false; while (!mainDone) { System.out.print("Enter fuel efficiency: "); double fuelEfficiency = sc.nextDouble(); car = new Car(fuelEfficiency); if (fuelEfficiency == 0) { // The user entered a fuel efficiency of zero, so terminate the // program. System.exit(0); } boolean outerDone = false; while (!outerDone) { System.out.print("Enter amount of fuel: "); double fuelAmountToAdd = sc.nextDouble(); if (fuelAmountToAdd == 0) { // The user entered a zero value for the fuel to add, so // terminate this outer loop. outerDone = true; } else { // Add provided fuel to the car. car.addFuel(fuelAmountToAdd); boolean innerDone = false; while (!innerDone) { System.out.print("Enter distance to travel: "); double distanceToTravel = sc.nextDouble(); if (distanceToTravel == 0) { // The user entered a zero distance to travel, so // terminate this inner loop. innerDone = true; } else { // Attempt to travel the distance provided with the // car. double distanceTraveled = car.drive(distanceToTravel); System.out.println(" Distance actually " + "traveled = " + distanceTraveled); System.out.println(" Current fuelLevel = " + car.getFuelLevel()); System.out.println(" Current odometer = " + car.getOdometer()); } } } } } } }
mit
asposemarketplace/Aspose-Pdf-Java
src/programmersguide/workingwithasposepdfgenerator/workingwithtext/textformatting/inheritingtextformat/java/InheritingTextFormat.java
751
/* * Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved. * * This file is part of Aspose.Pdf. The source code in this file * is only intended as a supplement to the documentation, and is provided * "as is", without warranty of any kind, either expressed or implied. */ package programmersguide.workingwithasposepdfgenerator.workingwithtext.textformatting.inheritingtextformat.java; import com.aspose.pdf.*; public class InheritingTextFormat { public static void main(String[] args) throws Exception { // The path to the documents directory. String dataDir = "src/programmersguide/workingwithasposepdfgenerator/workingwithtext(generator)/textformatting/inheritingtextformat/data/"; } }
mit
project-rhd/smash-app
smash-tweets/smash-tweets-data/src/main/java/smash/data/tweets/pojo/TweetCoordinates.java
1190
package smash.data.tweets.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * @author Yikai Gong */ public class TweetCoordinates implements Serializable { private String type; // Order in lon-lat. Follow the GeoJSON/WKT standard which JTS is holing on // Ref: http://www.macwright.org/lonlat/ // and http://docs.geotools.org/latest/userguide/library/referencing/epsg.html private List<BigDecimal> coordinates; public TweetCoordinates() { } public TweetCoordinates(Double lon, Double lat) { this(); type = "point"; List<BigDecimal> l = new ArrayList<>(); l.add(0, BigDecimal.valueOf(lon)); l.add(1, BigDecimal.valueOf(lat)); coordinates = l; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<BigDecimal> getCoordinates() { return coordinates; } public void setCoordinates(List<BigDecimal> coordinates) { this.coordinates = coordinates; } public BigDecimal getLon() { return coordinates.get(0); } public BigDecimal getLat() { return coordinates.get(1); } }
mit
riccardobellini/recipecatalog-backend-java
src/main/java/com/bellini/recipecatalog/exception/recipe/NotExistingRecipeException.java
559
package com.bellini.recipecatalog.exception.recipe; public class NotExistingRecipeException extends RuntimeException { private static final long serialVersionUID = 2975419159984559986L; private Long id; public NotExistingRecipeException(Long id) { super(); if (id == null) { throw new IllegalArgumentException("Null object used as initializer of the exception"); } this.id = id; } @Override public String getMessage() { return "Recipe " + id + " not found in database"; } }
mit
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/view/activities/PromptsActivity.java
7640
package biz.golek.whattodofordinner.view.activities; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import org.greenrobot.eventbus.Subscribe; import java.util.List; import biz.golek.whattodofordinner.R; import biz.golek.whattodofordinner.business.contract.request_data.GeneratePromptsRequestData; import biz.golek.whattodofordinner.business.contract.response_data.DinnerListItem; import biz.golek.whattodofordinner.view.ActivityDependencyProvider; import biz.golek.whattodofordinner.view.adapters.DinnerListItemArrayAdapter; import biz.golek.whattodofordinner.view.awareness.IActivityDependencyProviderAware; import biz.golek.whattodofordinner.view.messages.DinnerDeletedMessage; import biz.golek.whattodofordinner.view.messages.DinnerUpdatedMessage; import biz.golek.whattodofordinner.view.view_models.PromptsActivityViewModel; public class PromptsActivity extends AppCompatActivity implements IActivityDependencyProviderAware { private String PROMPTS_LIST_VIEW_MODEL = "promptsListViewModel"; private PromptsActivityViewModel viewModel; private ActivityDependencyProvider activityDependencyProvider; private ArrayAdapter adapter; private ListView listView; private DinnerListItem nonOfThisListItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prompts); setupActionBar(); if (savedInstanceState != null) viewModel = (PromptsActivityViewModel) savedInstanceState.getSerializable(PROMPTS_LIST_VIEW_MODEL); else viewModel = (PromptsActivityViewModel)getIntent().getSerializableExtra("VIEW_MODEL"); listView = (ListView) findViewById(R.id.prompts_list); List<DinnerListItem> prompts = viewModel.prompts; nonOfThisListItem = new DinnerListItem(); nonOfThisListItem.id = -1L; nonOfThisListItem.name = getResources().getString(R.string.non_of_this); prompts.add(nonOfThisListItem); adapter = new DinnerListItemArrayAdapter(this, prompts); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DinnerListItem item = (DinnerListItem)listView.getItemAtPosition(position); if (item == nonOfThisListItem) activityDependencyProvider.getGeneratePromptsController().Run(getDenyRequestData()); else activityDependencyProvider.getDinnerChosenController().Run(item.id, item.name); } }); registerForContextMenu(listView); activityDependencyProvider.getEventBusProvider().get().register(this); } @Subscribe public void onDinnerDeleteMessage(DinnerDeletedMessage event) { DinnerListItem dinner = null; for (DinnerListItem d : viewModel.prompts) if (d.id.equals(event.getId())) dinner = d; if (dinner != null) viewModel.prompts.remove(dinner); adapter.notifyDataSetChanged(); } @Subscribe public void onDinnerUpdatedMessage(DinnerUpdatedMessage event) { boolean updated = false; for (DinnerListItem dinner : viewModel.prompts) { if (dinner.id.equals(event.getId())) { dinner.id = event.getId(); dinner.name = event.getName(); updated = true; } } if (updated) adapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); activityDependencyProvider.getEventBusProvider().get().unregister(this); } @NonNull private GeneratePromptsRequestData getDenyRequestData() { GeneratePromptsRequestData rd = new GeneratePromptsRequestData(); rd.soup_profile = viewModel.getSoupProfile(); rd.vegetarian_profile = viewModel.getVegetarianProfile(); rd.maximum_duration = viewModel.getMaximumDuration(); Long[] oldExcludes = viewModel.getExcludes(); List<DinnerListItem> prompts = viewModel.prompts; int oldExcludesLength = oldExcludes!= null ? oldExcludes.length : 0; int promptsSize = prompts != null ? prompts.size() : 0; if (oldExcludesLength + promptsSize > 0) { Long[] excludes = new Long[oldExcludesLength + promptsSize]; Integer index = 0; if (oldExcludes != null) { for (Long id: oldExcludes) { excludes[index++] = id; } } if (prompts != null) { for (DinnerListItem dli: prompts) { excludes[index++] = dli.id; } } rd.excludes = excludes; } return rd; } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId()==R.id.prompts_list) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position); if (dinnerListItem != nonOfThisListItem) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dinner_list_item_menu, menu); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position); switch(item.getItemId()) { case R.id.dinner_list_item_menu_edit: activityDependencyProvider.getEditDinnerController().Run(dinnerListItem.id); return true; case R.id.dinner_list_item_menu_delete: activityDependencyProvider.getDeleteDinnerController().Run(dinnerListItem.id); return true; default: return super.onContextItemSelected(item); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putSerializable(PROMPTS_LIST_VIEW_MODEL, viewModel); super.onSaveInstanceState(outState); } @Override public void Set(ActivityDependencyProvider item) { activityDependencyProvider = item; } }
mit
TeamworkGuy2/JTwg2Templating
src/twg2/template/codeTemplate/ClassTemplateBuilder.java
5967
package twg2.template.codeTemplate; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @param <T> the {@link ClassInfo} to build * * @author TeamworkGuy2 * @since 2015-1-24 */ public final class ClassTemplateBuilder<T extends ClassInfo> { private T tmpl; public ClassTemplateBuilder(T tmpl) { this.tmpl = tmpl; } public ClassTemplateBuilder(T tmpl, String className, String packageName) { this.tmpl = tmpl; tmpl.setClassName(className); tmpl.setPackageName(packageName); } public ClassTemplateBuilder<T> setPackageName(String packageName) { tmpl.setPackageName(packageName); return this; } /** Alias for {@link #addImportStatement(Class...)} */ @SafeVarargs public final ClassTemplateBuilder<T> imports(Class<?>... importStatements) { return addImportStatement(importStatements); } @SafeVarargs public final ClassTemplateBuilder<T> addImportStatement(Class<?>... importStatements) { List<String> statements = tmpl.getImportStatements(); if(statements == null) { statements = new ArrayList<>(); tmpl.setImportStatements(statements); } if(importStatements == null) { return this; } for(Class<?> importStatement : importStatements) { statements.add(importStatement.getCanonicalName()); } return this; } /** Alias for {@link #addImportStatement(String...)} */ @SafeVarargs public final ClassTemplateBuilder<T> imports(String... importStatements) { return addImportStatement(importStatements); } @SafeVarargs public final ClassTemplateBuilder<T> addImportStatement(String... importStatements) { List<String> imports = tmpl.getImportStatements(); if(imports == null) { imports = new ArrayList<>(); tmpl.setImportStatements(imports); } if(importStatements == null) { return this; } for(String importStatement : importStatements) { imports.add(importStatement); } return this; } public ClassTemplateBuilder<T> setClassModifier(String classAccessModifier) { tmpl.setClassModifier(classAccessModifier); return this; } public ClassTemplateBuilder<T> setClassType(String classType) { tmpl.setClassType(classType); return this; } public ClassTemplateBuilder<T> addTypeParameters(Iterable<? extends Map.Entry<String, String>> classParameterNamesAndTypes) { for(Map.Entry<String, String> classParam : classParameterNamesAndTypes) { addTypeParameter(classParam.getKey(), classParam.getValue()); } return this; } public ClassTemplateBuilder<T> addTypeParameter(String classParameterName, String classTypeParameterDefinition) { if(tmpl.getClassTypeParameterDefinitions() == null) { tmpl.setClassTypeParameterDefinitions(new ArrayList<>()); } if(tmpl.getClassTypeParameterNames() == null) { tmpl.setClassTypeParameterNames(new ArrayList<>()); } tmpl.getClassTypeParameterNames().add(classParameterName); tmpl.getClassTypeParameterDefinitions().add(classTypeParameterDefinition); return this; } public ClassTemplateBuilder<T> setClassName(String className) { tmpl.setClassName(className); return this; } /** Alias for {@link #setExtendClassName(Class)} */ public ClassTemplateBuilder<T> extend(Class<?> extendClassName) { return setExtendClassName(extendClassName); } public ClassTemplateBuilder<T> setExtendClassName(Class<?> extendClassName) { tmpl.setExtendClassName(extendClassName.getCanonicalName().replace("java.lang.", "")); return this; } /** Alias for {@link #setExtendClassName(String)} */ public ClassTemplateBuilder<T> extend(String extendClassName) { return setExtendClassName(extendClassName); } public ClassTemplateBuilder<T> setExtendClassName(String extendClassName) { tmpl.setExtendClassName(extendClassName); return this; } /** Alias for {@link #addImplementClassNames(String...)} */ @SafeVarargs public final ClassTemplateBuilder<T> implement(String... implementClassNames) { return addImplementClassNames(implementClassNames); } @SafeVarargs public final ClassTemplateBuilder<T> addImplementClassNames(String... implementClassNames) { List<String> implementNames = tmpl.getImplementClassNames(); if(implementNames == null) { implementNames = new ArrayList<>(); tmpl.setImplementClassNames(implementNames); } if(implementClassNames == null) { return this; } for(String implementClassName : implementClassNames) { implementNames.add(implementClassName); } return this; } /** Alias for {@link #addImplementClassNames(Class...)} */ @SafeVarargs public final ClassTemplateBuilder<T> implement(Class<?>... implementClassNames) { return addImplementClassNames(implementClassNames); } @SafeVarargs public final ClassTemplateBuilder<T> addImplementClassNames(Class<?>... implementClassNames) { List<String> implementNames = tmpl.getImplementClassNames(); if(implementNames == null) { implementNames = new ArrayList<>(); tmpl.setImplementClassNames(implementNames); } if(implementClassNames == null) { return this; } for(Class<?> implementClassName : implementClassNames) { implementNames.add(implementClassName.getCanonicalName().replace("java.lang.", "")); } return this; } public T getTemplate() { return tmpl; } public static ClassTemplateBuilder<ClassInfo> newInst() { return new ClassTemplateBuilder<ClassInfo>(new ClassTemplate()); } public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst) { return new ClassTemplateBuilder<>(inst); } public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst, String className, String packageName) { return new ClassTemplateBuilder<>(inst, className, packageName); } public static ClassTemplateBuilder<ClassTemplate> of(String className) { return of(className, null); } public static ClassTemplateBuilder<ClassTemplate> of(String className, String packageName) { return new ClassTemplateBuilder<>(new ClassTemplate(), className, packageName); } }
mit
andersonsilvade/workspacejava
engsoft1globalcode/aj2lab10_02/src/Agencia.java
2802
/* * Globalcode - "The Developers Company" * * Academia do Java * */ public abstract class Agencia { private String numero; private Banco banco; /** * @param num * Numero da agencia * @param bc * banco ao qual a agencia pertence */ public Agencia(String num, Banco bc) { numero = num; banco = bc; } /** * @return numero do banco */ public Banco getBanco() { return banco; } /** * @return numero da agencia */ public String getNumero() { return numero; } /** * @param b * banco */ public void setBanco(Banco b) { banco = b; } /** * @param num * numero da agencia */ public void setNumero(String num) { numero = num; } /** * Metodo para impressao de todos os dados da classe */ public void imprimeDados() { System.out.println("Agencia no. " + numero); banco.imprimeDados(); } public void ajustarLimites(ContaEspecial[] contasEspeciais) { System.out.println("==================================================================="); System.out.println("Agencia: " + this.getNumero() + " ajustando limites"); for (int i = 0; i < contasEspeciais.length; i++) { ContaEspecial ce = contasEspeciais[i]; if (ce != null) { if (ce.getAgencia() != this) { System.out.println("A conta " + ce.getNumero() + " nao pertence a esta agencia"); } else { double limiteAntigo = ce.getLimite(); ajustarLimiteIndividual(ce); double limiteAjustado = ce.getLimite(); System.out.println("conta " + ce.getNumero() + "\tlimite antigo: " + limiteAntigo + "\tlimite ajustado: " + limiteAjustado); } } } System.out.println("limites ajustados"); System.out.println("==================================================================="); } protected abstract void ajustarLimiteIndividual(ContaEspecial contaEspecial); public Conta abrirConta(Cliente titular, double saldoInicial) { String numeroConta = "" + (int) (Math.random() * 9999999); if (saldoInicial <= 500) { return new Conta(saldoInicial, numeroConta, titular, this); } else if (saldoInicial > 500 && saldoInicial <= 1000) { String hoje = "" + new java.util.Date(); return new ContaPoupanca(saldoInicial, numeroConta, titular, this, hoje); } else { return null; } } }
mit
lordmarkm/ccsi
ccsi-commons/src/main/java/com/ccsi/commons/dto/tenant/BaseCcsiInfo.java
595
package com.ccsi.commons.dto.tenant; /** * @author mbmartinez */ public class BaseCcsiInfo { protected Long id; protected String name; protected String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
mit
RadishSystems/choiceview-webapi-avaya-demo
RadishTest/WEB-INF/src/flow/IProjectVariables.java
6735
package flow; /** * This interface is used to define the name of variables that are * declared in the call flow. All variables are defined as * <code>public static final String</code>, which allows user-defined * code to reference variable names by the Java variable name. * Last generated by Orchestration Designer at: 2013-FEB-03 08:27:04 PM */ public interface IProjectVariables { //{{START:PROJECT:VARIABLES /** * This is a reserved block of variable name definitions. * The variable names defined here can be used as the key * to get the <code>com.avaya.sce.runtime.Variable</code> * from the <code>SCESession</code> at runtime.<br> * * For example, given a variable name <code>phoneNum</code>, * user-defined code should access the variable in this format:<PRE> * Variable phNum = mySession.getVariable(IProjectVariables.PHONE_NUM); * if ( phNum != null ) { * // do something with the variable * }</PRE> * * This block of code is generated automatically by Orchestration Designer and should not * be manually edited as changes may be overwritten by future code generation. * Last generated by Orchestration Designer at: 2013-JUN-19 09:09:36 PM */ public static final String MAIN_MENU = "MainMenu"; public static final String BLIND_TRANSFER = "BlindTransfer"; public static final String TIME = "time"; public static final String REDIRECTINFO = "redirectinfo"; public static final String MAIN_MENU_TEXT = "MainMenuText"; public static final String SESSION = "session"; public static final String DD_LAST_EXCEPTION = "ddLastException"; public static final String DATE = "date"; public static final String SHAREDUUI = "shareduui"; //}}END:PROJECT:VARIABLES //{{START:PROJECT:VARIABLEFIELDS public static final String MAIN_MENU_FIELD_COLUMN_0 = "Column0"; public static final String MAIN_MENU_FIELD_CONFIDENCE = "confidence"; public static final String MAIN_MENU_FIELD_INPUTMODE = "inputmode"; public static final String MAIN_MENU_FIELD_INTERPRETATION = "interpretation"; public static final String MAIN_MENU_FIELD_NOINPUTCOUNT = "noinputcount"; public static final String MAIN_MENU_FIELD_NOMATCHCOUNT = "nomatchcount"; public static final String MAIN_MENU_FIELD_UTTERANCE = "utterance"; public static final String MAIN_MENU_FIELD_VALUE = "value"; public static final String TIME_FIELD_AUDIO = "audio"; public static final String TIME_FIELD_HOUR = "hour"; public static final String TIME_FIELD_MILLISECOND = "millisecond"; public static final String TIME_FIELD_MINUTE = "minute"; public static final String TIME_FIELD_SECOND = "second"; public static final String TIME_FIELD_TIMEZONE = "timezone"; public static final String REDIRECTINFO_FIELD_PRESENTATIONINFO = "presentationinfo"; public static final String REDIRECTINFO_FIELD_REASON = "reason"; public static final String REDIRECTINFO_FIELD_SCREENINGINFO = "screeninginfo"; public static final String REDIRECTINFO_FIELD_URI = "uri"; public static final String SESSION_FIELD_AAI = "aai"; public static final String SESSION_FIELD_ANI = "ani"; public static final String SESSION_FIELD_CALLTAG = "calltag"; public static final String SESSION_FIELD_CHANNEL = "channel"; public static final String SESSION_FIELD_CONVERSEFIRST = "conversefirst"; public static final String SESSION_FIELD_CONVERSESECOND = "conversesecond"; public static final String SESSION_FIELD_CURRENTLANGUAGE = "currentlanguage"; public static final String SESSION_FIELD_DNIS = "dnis"; public static final String SESSION_FIELD_EXIT_CUSTOMER_ID = "exitCustomerId"; public static final String SESSION_FIELD_EXIT_INFO_1 = "exitInfo1"; public static final String SESSION_FIELD_EXIT_INFO_2 = "exitInfo2"; public static final String SESSION_FIELD_EXIT_PREFERRED_PATH = "exitPreferredPath"; public static final String SESSION_FIELD_EXIT_REASON = "exitReason"; public static final String SESSION_FIELD_EXIT_TOPIC = "exitTopic"; public static final String SESSION_FIELD_LASTERROR = "lasterror"; public static final String SESSION_FIELD_MEDIATYPE = "mediatype"; public static final String SESSION_FIELD_MESSAGE_TYPE = "messageType"; public static final String SESSION_FIELD_PROTOCOLNAME = "protocolname"; public static final String SESSION_FIELD_PROTOCOLVERSION = "protocolversion"; public static final String SESSION_FIELD_SESSIONID = "sessionid"; public static final String SESSION_FIELD_SESSIONLABEL = "sessionlabel"; public static final String SESSION_FIELD_SHAREDMODE = "sharedmode"; public static final String SESSION_FIELD_UCID = "ucid"; public static final String SESSION_FIELD_UUI = "uui"; public static final String SESSION_FIELD_VIDEOBITRATE = "videobitrate"; public static final String SESSION_FIELD_VIDEOCODEC = "videocodec"; public static final String SESSION_FIELD_VIDEOENABLED = "videoenabled"; public static final String SESSION_FIELD_VIDEOFARFMTP = "videofarfmtp"; public static final String SESSION_FIELD_VIDEOFORMAT = "videoformat"; public static final String SESSION_FIELD_VIDEOFPS = "videofps"; public static final String SESSION_FIELD_VIDEOHEIGHT = "videoheight"; public static final String SESSION_FIELD_VIDEONEARFMTP = "videonearfmtp"; public static final String SESSION_FIELD_VIDEOWIDTH = "videowidth"; public static final String SESSION_FIELD_VPCALLEDEXTENSION = "vpcalledextension"; public static final String SESSION_FIELD_VPCONVERSEONDATA = "vpconverseondata"; public static final String SESSION_FIELD_VPCOVERAGEREASON = "vpcoveragereason"; public static final String SESSION_FIELD_VPCOVERAGETYPE = "vpcoveragetype"; public static final String SESSION_FIELD_VPRDNIS = "vprdnis"; public static final String SESSION_FIELD_VPREPORTURL = "vpreporturl"; public static final String DD_LAST_EXCEPTION_FIELD_ERRORCODE = "errorcode"; public static final String DD_LAST_EXCEPTION_FIELD_MESSAGE = "message"; public static final String DD_LAST_EXCEPTION_FIELD_OBJECT = "object"; public static final String DD_LAST_EXCEPTION_FIELD_STACKTRACE = "stacktrace"; public static final String DD_LAST_EXCEPTION_FIELD_TYPE = "type"; public static final String DATE_FIELD_AUDIO = "audio"; public static final String DATE_FIELD_DAYOFMONTH = "dayofmonth"; public static final String DATE_FIELD_DAYOFWEEK = "dayofweek"; public static final String DATE_FIELD_DAYOFWEEKNUM = "dayofweeknum"; public static final String DATE_FIELD_DAYOFYEAR = "dayofyear"; public static final String DATE_FIELD_MONTH = "month"; public static final String DATE_FIELD_MONTHINYEAR = "monthinyear"; public static final String DATE_FIELD_YEAR = "year"; public static final String SHAREDUUI_FIELD_ID = "id"; public static final String SHAREDUUI_FIELD_VALUE = "value"; //}}END:PROJECT:VARIABLEFIELDS }
mit
haslam22/gomoku
src/main/java/piskvork/PiskvorkCommand.java
898
package piskvork; /** * Root interface for a Piskvork command. A command must provide a string to * send to the AI, and a method to validate the response. */ public interface PiskvorkCommand { /** * Get the string for this command to send to the AI. * @return String identifier of the command, e.g. TURN or MESSAGE, plus * any other parameters to send to the AI. */ String getCommandString(); /** * Return whether or not this command requires a response. * @return True by default, overridden to false if required. */ default boolean requiresResponse() { return true; } /** * Validate a response for this command. * @param response Response to validate * @return Boolean representing whether this response is valid */ default boolean validateResponse(String response) { return true; } }
mit
caadxyz/Macro-Thinking-Micro-action
experimental/gov/nasa/worldwind/render/SurfaceCircle2.java
1719
/* Copyright (C) 2001, 2008 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. */ package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.render.airspaces.*; import javax.media.opengl.*; /** * @author brownrigg * @version $Id: SurfaceCircle2.java 9230 2009-03-06 05:36:26Z dcollins $ */ public class SurfaceCircle2 extends CappedCylinder { public SurfaceCircle2(LatLon location, double radius) { super(location, radius); } public SurfaceCircle2(AirspaceAttributes shapeAttributes) { super(shapeAttributes); } public SurfaceCircle2() { super(); } protected void doRenderGeometry(DrawContext dc, String drawStyle) { beginDrawShape(dc); super.doRenderGeometry(dc, drawStyle); endDrawShape(dc); } protected void beginDrawShape(DrawContext dc) { // Modify the projection transform to shift the depth values slightly toward the camera in order to // ensure the shape is selected during depth buffering. GL gl = dc.getGL(); float[] pm = new float[16]; gl.glGetFloatv(GL.GL_PROJECTION_MATRIX, pm, 0); pm[10] *= .8; // TODO: See Lengyel 2 ed. Section 9.1.2 to compute optimal/minimal offset gl.glPushAttrib(GL.GL_TRANSFORM_BIT); gl.glMatrixMode(GL.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadMatrixf(pm, 0); } protected void endDrawShape(DrawContext dc) { GL gl = dc.getGL(); gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); gl.glPopAttrib(); } }
mit
martindisch/Lolli
app/src/main/java/com/martin/lolli/NavigationDrawerFragment.java
10019
package com.martin.lolli; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"> * design guidelines</a> for a complete explanation of the behaviors implemented here. */ public class NavigationDrawerFragment extends Fragment { /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; public NavigationDrawerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } // Select either the default item (0) or the last selected item. selectItem(mCurrentSelectedPosition, mFromSavedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position, false); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_section1), getString(R.string.title_section2), getString(R.string.title_section3), getString(R.string.title_section4) } )); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem( int position, boolean fromSavedInstanceState) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position, fromSavedInstanceState); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the global app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position, boolean fromSavedInstanceState); } }
mit
sake/bouncycastle-java
src/org/bouncycastle/asn1/cms/EncryptedData.java
2516
package org.bouncycastle.asn1.cms; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.BERSequence; import org.bouncycastle.asn1.BERTaggedObject; public class EncryptedData extends ASN1Object { private ASN1Integer version; private EncryptedContentInfo encryptedContentInfo; private ASN1Set unprotectedAttrs; public static EncryptedData getInstance(Object o) { if (o instanceof EncryptedData) { return (EncryptedData)o; } if (o != null) { return new EncryptedData(ASN1Sequence.getInstance(o)); } return null; } public EncryptedData(EncryptedContentInfo encInfo) { this(encInfo, null); } public EncryptedData(EncryptedContentInfo encInfo, ASN1Set unprotectedAttrs) { this.version = new ASN1Integer((unprotectedAttrs == null) ? 0 : 2); this.encryptedContentInfo = encInfo; this.unprotectedAttrs = unprotectedAttrs; } private EncryptedData(ASN1Sequence seq) { this.version = ASN1Integer.getInstance(seq.getObjectAt(0)); this.encryptedContentInfo = EncryptedContentInfo.getInstance(seq.getObjectAt(1)); if (seq.size() == 3) { this.unprotectedAttrs = ASN1Set.getInstance(seq.getObjectAt(2)); } } public ASN1Integer getVersion() { return version; } public EncryptedContentInfo getEncryptedContentInfo() { return encryptedContentInfo; } public ASN1Set getUnprotectedAttrs() { return unprotectedAttrs; } /** * <pre> * EncryptedData ::= SEQUENCE { * version CMSVersion, * encryptedContentInfo EncryptedContentInfo, * unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL } * </pre> * @return a basic ASN.1 object representation. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(version); v.add(encryptedContentInfo); if (unprotectedAttrs != null) { v.add(new BERTaggedObject(false, 1, unprotectedAttrs)); } return new BERSequence(v); } }
mit
jackrosenhauer/web-server
src/Main.java
983
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * Created by jackrosenhauer on 5/5/15. */ public class Main { public static void main(String[] args){ final int DEFAULT_PORT = 8080; // For security reasons, only root can use ports < 1024. int portNumber = args.length > 1 ? Integer.parseInt(args[0]) : DEFAULT_PORT; ServerSocket serverSocket; int threadsCreated = 0; try{ serverSocket = new ServerSocket(portNumber); while (true) { Thread t = new Worker(serverSocket); t.start(); threadsCreated++; System.out.println("Threads Created & Processed: " + threadsCreated); } } catch (IOException e) { System.err.println("Oops! " + e); } catch (Exception e){ System.out.println("Something else went terribly wrong"); e.printStackTrace(); } } }
mit
agamemnus/cordova-plugin-admob
src/android/AdMob.java
20788
package com.agamemnus.cordova.plugin; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.mediation.admob.AdMobExtras; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.os.Bundle; import java.util.Iterator; import java.util.Random; import android.provider.Settings; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.util.Log; public class AdMob extends CordovaPlugin { // Common tag used for logging statements. private static final String LOGTAG = "AdMob"; private static final boolean CORDOVA_4 = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) >= 4; // Cordova Actions. private static final String ACTION_SET_OPTIONS = "setOptions"; private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView"; private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView"; private static final String ACTION_REQUEST_AD = "requestAd"; private static final String ACTION_SHOW_AD = "showAd"; private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView"; private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd"; private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd"; // Options. private static final String OPT_AD_ID = "adId"; private static final String OPT_AD_SIZE = "adSize"; private static final String OPT_BANNER_AT_TOP = "bannerAtTop"; private static final String OPT_OVERLAP = "overlap"; private static final String OPT_OFFSET_TOPBAR = "offsetTopBar"; private static final String OPT_IS_TESTING = "isTesting"; private static final String OPT_AD_EXTRAS = "adExtras"; private static final String OPT_AUTO_SHOW = "autoShow"; // The adView to display to the user. private ViewGroup parentView; private AdView adView; // If the user wants banner view overlap webview, we will need this layout. private RelativeLayout adViewLayout = null; // The interstitial ad to display to the user. private InterstitialAd interstitialAd; private AdSize adSize = AdSize.SMART_BANNER; private String adId = ""; private boolean bannerAtTop = false; private boolean bannerOverlap = false; private boolean offsetTopBar = false; private boolean isTesting = false; private boolean bannerShow = true; private boolean autoShow = true; private boolean autoShowBanner = true; private boolean autoShowInterstitial = true; private boolean bannerVisible = false; private boolean isGpsAvailable = false; private JSONObject adExtras = null; @Override public void initialize (CordovaInterface cordova, CordovaWebView webView) { super.initialize (cordova, webView); isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS); Log.w (LOGTAG, String.format("isGooglePlayServicesAvailable: %s", isGpsAvailable ? "true" : "false")); } // This is the main method for the AdMob plugin. All API calls go through here. // This method determines the action, and executes the appropriate call. // // @param action The action that the plugin should execute. // @param inputs The input parameters for the action. // @param callbackContext The callback context. // @return A PluginResult representing the result of the provided action. // A status of INVALID_ACTION is returned if the action is not recognized. @Override public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException { PluginResult result = null; if (ACTION_SET_OPTIONS.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeSetOptions(options, callbackContext); } else if (ACTION_CREATE_BANNER_VIEW.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeCreateBannerView(options, callbackContext); } else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeCreateInterstitialView(options, callbackContext); } else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) { result = executeDestroyBannerView(callbackContext); } else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeRequestInterstitialAd(options, callbackContext); } else if (ACTION_REQUEST_AD.equals(action)) { JSONObject options = inputs.optJSONObject(0); result = executeRequestAd(options, callbackContext); } else if (ACTION_SHOW_AD.equals(action)) { boolean show = inputs.optBoolean(0); result = executeShowAd(show, callbackContext); } else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) { boolean show = inputs.optBoolean(0); result = executeShowInterstitialAd(show, callbackContext); } else { Log.d (LOGTAG, String.format("Invalid action passed: %s", action)); result = new PluginResult(Status.INVALID_ACTION); } if (result != null) callbackContext.sendPluginResult (result); return true; } private PluginResult executeSetOptions (JSONObject options, CallbackContext callbackContext) { Log.w (LOGTAG, "executeSetOptions"); this.setOptions (options); callbackContext.success (); return null; } private void setOptions (JSONObject options) { if (options == null) return; if (options.has(OPT_AD_ID)) this.adId = options.optString (OPT_AD_ID); if (options.has(OPT_AD_SIZE)) this.adSize = adSizeFromString (options.optString(OPT_AD_SIZE)); if (options.has(OPT_BANNER_AT_TOP)) this.bannerAtTop = options.optBoolean (OPT_BANNER_AT_TOP); if (options.has(OPT_OVERLAP)) this.bannerOverlap = options.optBoolean (OPT_OVERLAP); if (options.has(OPT_OFFSET_TOPBAR)) this.offsetTopBar = options.optBoolean (OPT_OFFSET_TOPBAR); if (options.has(OPT_IS_TESTING)) this.isTesting = options.optBoolean (OPT_IS_TESTING); if (options.has(OPT_AD_EXTRAS)) this.adExtras = options.optJSONObject (OPT_AD_EXTRAS); if (options.has(OPT_AUTO_SHOW)) this.autoShow = options.optBoolean (OPT_AUTO_SHOW); } // Parses the create banner view input parameters and runs the create banner // view action on the UI thread. If this request is successful, the developer // should make the requestAd call to request an ad for the banner. // // @param inputs The JSONArray representing input parameters. This function // expects the first object in the array to be a JSONObject with the input parameters. // @return A PluginResult representing whether or not the banner was created successfully. private PluginResult executeCreateBannerView (JSONObject options, final CallbackContext callbackContext) { this.setOptions (options); autoShowBanner = autoShow; cordova.getActivity().runOnUiThread (new Runnable() { @Override public void run () { boolean adViewWasNull = (adView == null); if (adView == null) { adView = new AdView (cordova.getActivity()); adView.setAdUnitId (adId); adView.setAdSize (adSize); } if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView); if (adViewLayout == null) { adViewLayout = new RelativeLayout(cordova.getActivity()); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); if (CORDOVA_4) { ((ViewGroup) webView.getView().getParent()).addView(adViewLayout, params); } else { ((ViewGroup) webView).addView(adViewLayout, params); } } bannerVisible = false; adView.loadAd (buildAdRequest()); if (adViewWasNull) adView.setAdListener (new BannerListener()); if (autoShowBanner) executeShowAd (true, null); callbackContext.success (); } }); return null; } private PluginResult executeDestroyBannerView (CallbackContext callbackContext) { Log.w (LOGTAG, "executeDestroyBannerView"); final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread (new Runnable() { @Override public void run () { if (adView != null) { ViewGroup parentView = (ViewGroup)adView.getParent(); if (parentView != null) parentView.removeView(adView); adView.destroy (); adView = null; } bannerVisible = false; delayCallback.success (); } }); return null; } // Parses the create interstitial view input parameters and runs the create interstitial // view action on the UI thread. If this request is successful, the developer should make the requestAd call to request an ad for the banner. // // @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters. // @return A PluginResult representing whether or not the banner was created successfully. private PluginResult executeCreateInterstitialView (JSONObject options, CallbackContext callbackContext) { this.setOptions (options); autoShowInterstitial = autoShow; final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread (new Runnable(){ @Override public void run () { interstitialAd = new InterstitialAd(cordova.getActivity()); interstitialAd.setAdUnitId (adId); interstitialAd.loadAd (buildAdRequest()); interstitialAd.setAdListener (new InterstitialListener()); delayCallback.success (); } }); return null; } private AdRequest buildAdRequest () { AdRequest.Builder request_builder = new AdRequest.Builder(); if (isTesting) { // This will request test ads on the emulator and deviceby passing this hashed device ID. String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); String deviceId = md5(ANDROID_ID).toUpperCase(); request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR); } Bundle bundle = new Bundle(); bundle.putInt("cordova", 1); if (adExtras != null) { Iterator<String> it = adExtras.keys(); while (it.hasNext()) { String key = it.next(); try { bundle.putString(key, adExtras.get(key).toString()); } catch (JSONException exception) { Log.w (LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage())); } } } AdMobExtras adextras = new AdMobExtras (bundle); request_builder = request_builder.addNetworkExtras (adextras); AdRequest request = request_builder.build (); return request; } // Parses the request ad input parameters and runs the request ad action on // the UI thread. // // @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters. // @return A PluginResult representing whether or not an ad was requested succcessfully. // Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see if an ad was successfully retrieved. private PluginResult executeRequestAd (JSONObject options, CallbackContext callbackContext) { this.setOptions (options); if (adView == null) { callbackContext.error ("adView is null, call createBannerView first"); return null; } final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread (new Runnable() { @Override public void run () { adView.loadAd (buildAdRequest()); delayCallback.success (); } }); return null; } private PluginResult executeRequestInterstitialAd (JSONObject options, CallbackContext callbackContext) { this.setOptions (options); if (adView == null) { callbackContext.error ("interstitialAd is null: call createInterstitialView first."); return null; } final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread (new Runnable() { @Override public void run () { interstitialAd.loadAd (buildAdRequest()); delayCallback.success (); } }); return null; } // Parses the show ad input parameters and runs the show ad action on the UI thread. // // @param inputs The JSONArray representing input parameters. This function // expects the first object in the array to be a JSONObject with the // input parameters. // @return A PluginResult representing whether or not an ad was requested // succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd() // callbacks to see if an ad was successfully retrieved. private PluginResult executeShowAd (final boolean show, final CallbackContext callbackContext) { bannerShow = show; if (adView == null) return new PluginResult (Status.ERROR, "adView is null: call createBannerView first."); cordova.getActivity().runOnUiThread (new Runnable(){ @Override public void run () { if(bannerVisible == bannerShow) { // No change. } else if (bannerShow) { if (adView.getParent() != null) { ((ViewGroup)adView.getParent()).removeView(adView); } if (bannerOverlap) { RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params2.addRule(bannerAtTop ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM); adViewLayout.addView(adView, params2); adViewLayout.bringToFront(); } else { if (CORDOVA_4) { ViewGroup wvParentView = (ViewGroup) webView.getView().getParent(); if (parentView == null) { parentView = new LinearLayout(webView.getContext()); } if (wvParentView != null && wvParentView != parentView) { wvParentView.removeView(webView.getView()); ((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL); parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F)); webView.getView().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F)); parentView.addView(webView.getView()); cordova.getActivity().setContentView(parentView); } } else { parentView = (ViewGroup) ((ViewGroup) webView).getParent(); } if (bannerAtTop) { parentView.addView (adView, 0); } else { parentView.addView (adView); } parentView.bringToFront (); parentView.requestLayout(); } adView.setVisibility (View.VISIBLE); bannerVisible = true; } else { adView.setVisibility (View.GONE); bannerVisible = false; } if (callbackContext != null) callbackContext.success (); } }); return null; } private PluginResult executeShowInterstitialAd (final boolean show, final CallbackContext callbackContext) { if (interstitialAd == null) return new PluginResult(Status.ERROR, "interstitialAd is null: call createInterstitialView first."); cordova.getActivity().runOnUiThread (new Runnable () { @Override public void run () { if (interstitialAd.isLoaded()) interstitialAd.show (); if (callbackContext != null) callbackContext.success (); } }); return null; } // This class implements the AdMob ad listener events. It forwards the events to the JavaScript layer. To listen for these events, use: // document.addEventListener ('onReceiveAd' , function()); // document.addEventListener ('onFailedToReceiveAd', function(data){}); // document.addEventListener ('onPresentAd' , function()); // document.addEventListener ('onDismissAd' , function()); // document.addEventListener ('onLeaveToAd' , function()); public class BasicListener extends AdListener { @Override public void onAdFailedToLoad (int errorCode) { webView.loadUrl (String.format( "javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': %d, 'reason':'%s' });", errorCode, getErrorReason(errorCode)) ); } } private class BannerListener extends BasicListener { @Override public void onAdLoaded () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveAd');");} @Override public void onAdOpened () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentAd');");} @Override public void onAdClosed () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissAd');");} @Override public void onAdLeftApplication () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToAd');");} } private class InterstitialListener extends BasicListener { @Override public void onAdLoaded () { Log.w ("AdMob", "InterstitialAdLoaded"); webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveInterstitialAd');"); if (autoShowInterstitial) executeShowInterstitialAd (true, null); } @Override public void onAdOpened () { webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentInterstitialAd');"); } @Override public void onAdClosed () { webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissInterstitialAd');"); interstitialAd = null; } @Override public void onAdLeftApplication () { webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToInterstitialAd');"); interstitialAd = null; } } @Override public void onPause (boolean multitasking) { if (adView != null) adView.pause (); super.onPause (multitasking); } @Override public void onResume (boolean multitasking) { super.onResume (multitasking); isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS); if (adView != null) adView.resume (); } @Override public void onDestroy () { if (adView != null) { adView.destroy (); adView = null; } if (adViewLayout != null) { ViewGroup parentView = (ViewGroup)adViewLayout.getParent(); if(parentView != null) { parentView.removeView(adViewLayout); } adViewLayout = null; } super.onDestroy (); } /** * Gets an AdSize object from the string size passed in from JavaScript. * Returns null if an improper string is provided. * * @param size The string size representing an ad format constant. * @return An AdSize object used to create a banner. */ public static AdSize adSizeFromString (String size) { if ("BANNER".equals(size)) { return AdSize.BANNER; } else if ("IAB_MRECT".equals(size)) { return AdSize.MEDIUM_RECTANGLE; } else if ("IAB_BANNER".equals(size)) { return AdSize.FULL_BANNER; } else if ("IAB_LEADERBOARD".equals(size)) { return AdSize.LEADERBOARD; } else if ("SMART_BANNER".equals(size)) { return AdSize.SMART_BANNER; } else { return null; } } /** Gets a string error reason from an error code. */ public String getErrorReason (int errorCode) { String errorReason = ""; switch(errorCode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: errorReason = "Internal error"; break; case AdRequest.ERROR_CODE_INVALID_REQUEST: errorReason = "Invalid request"; break; case AdRequest.ERROR_CODE_NETWORK_ERROR: errorReason = "Network Error"; break; case AdRequest.ERROR_CODE_NO_FILL: errorReason = "No fill"; break; } return errorReason; } public static final String md5 (final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance ("MD5"); digest.update (s.getBytes()); byte messageDigest[] = digest.digest (); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append (h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } }
mit
osmoossi/tapsudraft
src/main/java/fi/ozzi/tapsudraft/service/PlayerFetchService.java
3834
package fi.ozzi.tapsudraft.service; import com.google.common.collect.ImmutableMap; import fi.ozzi.tapsudraft.model.Player; import fi.ozzi.tapsudraft.model.Position; import fi.ozzi.tapsudraft.repository.PlayerRepository; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class PlayerFetchService { private static final Logger LOG = LoggerFactory.getLogger(PlayerFetchService.class); @Value("${service.playerfetch.baseUrl}") private String baseUrl; @NonNull private PlayerRepository playerRepository; @Scheduled(cron = "${service.playerfetch.cron}") public void fetchPlayers() throws IOException { Map<String, String> params = ImmutableMap.<String, String>builder() .put("js", "1") .put("rand", Float.toString(new Random().nextFloat())) .put("player_team", "all") .put("player_value", "all") .put("type", "player_search") .put("phase", "0") .build(); String url = buildUrlFromMap(baseUrl, params); LOG.debug(url); HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != 200) { LOG.debug("HTTP resp " + response.getStatusLine().getStatusCode()); } Document doc = Jsoup.parse(response.getEntity().getContent(), "UTF-8", url); Elements positionGroups = doc.getElementsByTag("tbody"); for (Element group : positionGroups) { Elements rows = group.getElementsByTag("tr"); for (Element row : rows) { Element nameData = row.select("td.name_data").first(); String name = nameData.text().trim(); String team = nameData.select("a.logo").first().attr("title"); team = team.substring(team.indexOf("(")+1, team.indexOf(")")); String position = nameData.select("input[name=player_position]").first().val(); String playerUid = nameData.select("input[name=player_id]").first().val(); Player player = playerRepository.findByUid(Long.parseLong(playerUid)); if (player == null) { playerRepository.save( Player.builder() .name(name) .uid(Long.parseLong(playerUid)) .position(Position.fromCharacter(position)) .build()); } String price = row.select("td[id~=.*_player_value]").first().text(); String points = row.select("td[title=IS Liigapörssi-pisteet]").first().text(); } } } private static String buildUrlFromMap(String baseUrl, Map<String, String> params) { String queryString = params.keySet().stream() .map(key -> { try { return key + "=" + URLEncoder.encode(params.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "Error: could not URL-encode value"; }).collect(Collectors.joining("&")); return baseUrl + "?" + queryString; } }
mit
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/setup/email/EmailSetupGUI.java
22577
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.sunnybat.paxchecker.setup.email; import com.github.sunnybat.commoncode.email.EmailAddress; import com.github.sunnybat.commoncode.email.account.EmailAccount; import com.github.sunnybat.commoncode.preferences.PreferenceHandler; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.LayoutStyle; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; /** * * @author SunnyBat */ public class EmailSetupGUI extends javax.swing.JFrame { private AuthenticationCallback myCallback = new AuthenticationCallback(); private AuthGmail authGmail = new AuthGmail(myCallback); private AuthSMTP authSmtp = new AuthSMTP(myCallback); private PreferenceHandler prefs; private EmailAccount finalizedEmailAccount; private boolean disableEmail = false; private List<EmailAddress> savedEmailAddresses; private boolean savedIsGmail; /** * Creates new form EmailUIWrapper * * @param prefs The Preferences to save email configuration settings to and load from */ public EmailSetupGUI(PreferenceHandler prefs) { this.prefs = prefs; initComponents(); customComponents(); } private void customComponents() { String smtpAddress = prefs.getStringPreference("EMAIL"); String emailString = prefs.getStringPreference("CELLNUM"); String emailType = prefs.getStringPreference("EMAILTYPE"); // TODO: we need to initialize everything here, including Send To // addresses and the EmailAccount we're using if (emailType != null && emailType.equalsIgnoreCase("SMTP")) { JRBSMTP.setSelected(true); setAuthPanel(authSmtp); savedIsGmail = false; if (smtpAddress != null) { authSmtp.setEmailAddress(smtpAddress); } else { System.out.println("smtpIsNull"); } authSmtp.recordCurrentFields(); } else { JRBGmail.setSelected(true); setAuthPanel(authGmail); savedIsGmail = true; if (emailType != null) { // Assumed to be Gmail authGmail.authenticate(); } authGmail.recordCurrentFields(); } if (emailString != null) { List<EmailAddress> addresses = EmailAddress.convertToList(emailString); for (EmailAddress address : addresses) { DefaultTableModel table = (DefaultTableModel) JTCellNumbers.getModel(); table.addRow(new Object[]{address.getCarrierName().equalsIgnoreCase("[Other]") ? address.getCompleteAddress() : address.getAddressBeginning(), address.getCarrierName()}); } } savedEmailAddresses = getCurrentEmails(); savedIsGmail = JRBGmail.isSelected(); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int result = JOptionPane.showConfirmDialog(null, "Would you like to save your changes?\r\nYes: Save Changes\r\nNo: Disable Email\r\nCancel: Discard changes\r\n[X] Button: Keep window open", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { saveChanges(); } else if (result == JOptionPane.NO_OPTION) { disableEmail(); } else if (result == JOptionPane.CANCEL_OPTION) { cancelChanges(); } } }); } /** * Gets the currently configured EmailAccount. This includes the email addresses currently * configured to be sent to. The EmailAccount must be successfully authenticated, otherwise null * will be returned. * * @return The EmailAccount configured, or null if not set up */ public EmailAccount getEmailAccount() { if (disableEmail) { return null; } EmailAccount account; if (JRBGmail.isSelected() && authGmail.isAuthenticated()) { account = authGmail.getEmailAccount(); } else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) { account = authSmtp.getEmailAccount(); } else { return null; } // === Add emails to account === account.clearAllSendAddresses(); // TODO Check to make sure this is the right thing to do, or if there's a better way DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel(); if (tableModel.getRowCount() == 0) { return null; } else { for (int i = 0; i < tableModel.getRowCount(); i++) { EmailAddress toAdd; String emailBeginning = (String) tableModel.getValueAt(i, 0); String emailCarrier = (String) tableModel.getValueAt(i, 1); if (emailCarrier.equalsIgnoreCase("[Other]")) { toAdd = new EmailAddress(emailBeginning); } else { toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier)); } account.addBccEmailAddress(toAdd); } } finalizedEmailAccount = account; return finalizedEmailAccount; } public String getEmailType() { if (JRBGmail.isSelected() && authGmail.isAuthenticated()) { return "Gmail API"; } else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) { return "SMTP"; } else { return "Disabled"; } } /** * Gets the semicolon-delimited String representing all of the email addresses configured. * * @return All the configured email addresses */ public String getEmailAddressesString() { List<EmailAddress> addresses = getCurrentEmails(); StringBuilder allAddresses = new StringBuilder(); for (int i = 0; i < addresses.size(); i++) { if (i > 0) { allAddresses.append(";"); } allAddresses.append(addresses.get(i).getCompleteAddress()); } return allAddresses.toString(); } private List<EmailAddress> getCurrentEmails() { List<EmailAddress> ret = new ArrayList<>(); DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { try { EmailAddress toAdd; String emailBeginning = (String) tableModel.getValueAt(i, 0); String emailCarrier = (String) tableModel.getValueAt(i, 1); if (emailCarrier.equalsIgnoreCase("[Other]")) { toAdd = new EmailAddress(emailBeginning); } else { toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier)); } ret.add(toAdd); } catch (IllegalArgumentException iae) { System.out.println("Invalid email address: " + tableModel.getValueAt(i, 0) + tableModel.getValueAt(i, 1)); } } return ret; } private void addEmail() { String cellNumber = JTFCellNumber.getText(); String carrier = JCBCarrier.getSelectedItem().toString(); if (!cellNumber.isEmpty()) { if (cellNumber.contains("@")) { // Full email configured carrier = "[Other]"; } ((DefaultTableModel) JTCellNumbers.getModel()).addRow(new Object[]{cellNumber, carrier}); JTFCellNumber.setText(null); JCBCarrier.setSelectedIndex(0); JTFCellNumber.requestFocus(); } } private void resetChanges() { DefaultTableModel model = (DefaultTableModel) JTCellNumbers.getModel(); for (int i = model.getRowCount() - 1; i >= 0; i--) { model.removeRow(i); } if (savedEmailAddresses != null) { for (EmailAddress address : savedEmailAddresses) { model.addRow(new Object[]{address.getAddressBeginning(), EmailAddress.getProvider(address.getAddressEnding())}); } } if (savedIsGmail) { JRBGmail.setSelected(true); setAuthPanel(authGmail); } else { JRBSMTP.setSelected(true); setAuthPanel(authSmtp); } } private void setAuthPanel(JPanel toUse) { JPAuthInfo.removeAll(); JPAuthInfo.add(toUse); JPAuthInfo.revalidate(); JPAuthInfo.repaint(); pack(); } private void resetUserInputFields() { JTPComponents.setSelectedIndex(0); JTFCellNumber.setText(null); JCBCarrier.setSelectedIndex(0); } private void updatePreferences() { EmailAccount toSave = getEmailAccount(); if (!disableEmail && toSave != null) { prefs.getPreferenceObject("EMAIL").setValue(toSave.getEmailAddress()); prefs.getPreferenceObject("CELLNUM").setValue(getEmailAddressesString()); prefs.getPreferenceObject("EMAILTYPE").setValue(getEmailType()); prefs.getPreferenceObject("EMAILENABLED").setValue(true); } else { prefs.getPreferenceObject("EMAIL").setValue(null); prefs.getPreferenceObject("CELLNUM").setValue(null); prefs.getPreferenceObject("EMAILTYPE").setValue(null); prefs.getPreferenceObject("EMAILENABLED").setValue(false); } } private void saveChanges() { if (getCurrentEmails().isEmpty()) { int result = JOptionPane.showConfirmDialog(null, "You have no Send To emails configured. This means emails will still be disabled.\r\nAre you sure you want to save your changes?\r\nPress Yes to save your changes, or No to add email addresses.", "No Emails Input", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.NO_OPTION) { JTPComponents.setSelectedComponent(JPSendTo); return; } } authGmail.recordCurrentFields(); authSmtp.recordCurrentFields(); savedEmailAddresses = getCurrentEmails(); savedIsGmail = JRBGmail.isSelected(); disableEmail = false; setVisible(false); resetUserInputFields(); updatePreferences(); } private void cancelChanges() { authGmail.resetChanges(); authSmtp.resetChanges(); resetChanges(); setVisible(false); resetUserInputFields(); updatePreferences(); } private void disableEmail() { disableEmail = true; authGmail.resetChanges(); authSmtp.resetChanges(); resetChanges(); setVisible(false); resetUserInputFields(); updatePreferences(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT * modify this code. The content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { BGAuthType = new ButtonGroup(); JTPComponents = new JTabbedPane(); JPAuthentication = new JPanel(); JRBGmail = new JRadioButton(); JRBSMTP = new JRadioButton(); JPAuthInfo = new JPanel(); JPSendTo = new JPanel(); JTFCellNumber = new JTextField(); JBAddNumber = new JButton(); JCBCarrier = new JComboBox<>(); jLabel1 = new JLabel(); jScrollPane1 = new JScrollPane(); JTCellNumbers = new JTable(); JPFinish = new JPanel(); JBSaveChanges = new JButton(); JBCancelChanges = new JButton(); JBDisableEmail = new JButton(); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); setTitle("Email Setup"); setResizable(false); BGAuthType.add(JRBGmail); JRBGmail.setText("Gmail API"); JRBGmail.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with Google through your browser. Recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Used for authenticating with Google via OAuth2.<br></p>\n</html>"); JRBGmail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JRBGmailActionPerformed(evt); } }); BGAuthType.add(JRBSMTP); JRBSMTP.setText("SMTP"); JRBSMTP.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with any email service. Not recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Authenticates with any mailserver using SMTP. Issues with this have cropped up in the past, and it's hard to detect where the problem lies. My guess is ISPs or routers blocking SMTP traffic (insane), but I don't know for sure.</p>\n</html>"); JRBSMTP.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JRBSMTPActionPerformed(evt); } }); JPAuthInfo.setLayout(new BoxLayout(JPAuthInfo, BoxLayout.LINE_AXIS)); GroupLayout JPAuthenticationLayout = new GroupLayout(JPAuthentication); JPAuthentication.setLayout(JPAuthenticationLayout); JPAuthenticationLayout.setHorizontalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(JPAuthenticationLayout.createSequentialGroup() .addContainerGap() .addComponent(JRBGmail) .addGap(18, 18, 18) .addComponent(JRBSMTP) .addContainerGap(249, Short.MAX_VALUE)) .addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); JPAuthenticationLayout.setVerticalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(JPAuthenticationLayout.createSequentialGroup() .addContainerGap() .addGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(JRBGmail) .addComponent(JRBSMTP)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); JTPComponents.addTab("Authentication", JPAuthentication); JTFCellNumber.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JTFCellNumberKeyPressed(evt); } }); JBAddNumber.setText("Add Number"); JBAddNumber.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JBAddNumberActionPerformed(evt); } }); JBAddNumber.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JBAddNumberKeyPressed(evt); } }); JCBCarrier.setModel(new DefaultComboBoxModel<>(new String[] { "AT&T (MMS)", "AT&T (SMS)", "Verizon", "Sprint", "T-Mobile", "U.S. Cellular", "Bell", "Rogers", "Fido", "Koodo", "Telus", "Virgin (CAN)", "Wind", "Sasktel", "[Other]" })); JCBCarrier.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JCBCarrierKeyPressed(evt); } }); jLabel1.setText("Cell Number"); JTCellNumbers.setModel(new DefaultTableModel( new Object [][] { }, new String [] { "Cell Number", "Carrier" } ) { Class[] types = new Class [] { String.class, String.class }; boolean[] canEdit = new boolean [] { false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); JTCellNumbers.setToolTipText("Delete emails by selecting them and pressing the DEL key"); JTCellNumbers.setColumnSelectionAllowed(true); JTCellNumbers.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JTCellNumbersKeyPressed(evt); } }); jScrollPane1.setViewportView(JTCellNumbers); GroupLayout JPSendToLayout = new GroupLayout(JPSendTo); JPSendTo.setLayout(JPSendToLayout); JPSendToLayout.setHorizontalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(JPSendToLayout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(JTFCellNumber, GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(JBAddNumber)) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); JPSendToLayout.setVerticalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(GroupLayout.Alignment.TRAILING, JPSendToLayout.createSequentialGroup() .addContainerGap() .addGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(JTFCellNumber, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(JBAddNumber) .addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)) ); JTPComponents.addTab("Send To", JPSendTo); JBSaveChanges.setText("Save Changes"); JBSaveChanges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JBSaveChangesActionPerformed(evt); } }); JBCancelChanges.setText("Cancel Changes"); JBCancelChanges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JBCancelChangesActionPerformed(evt); } }); JBDisableEmail.setText("Disable Email"); JBDisableEmail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JBDisableEmailActionPerformed(evt); } }); GroupLayout JPFinishLayout = new GroupLayout(JPFinish); JPFinish.setLayout(JPFinishLayout); JPFinishLayout.setHorizontalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(JPFinishLayout.createSequentialGroup() .addContainerGap() .addGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(JBSaveChanges, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JBCancelChanges, GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE) .addComponent(JBDisableEmail, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); JPFinishLayout.setVerticalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(GroupLayout.Alignment.TRAILING, JPFinishLayout.createSequentialGroup() .addContainerGap() .addComponent(JBSaveChanges) .addGap(18, 18, 18) .addComponent(JBCancelChanges) .addGap(18, 18, 18) .addComponent(JBDisableEmail) .addContainerGap(56, Short.MAX_VALUE)) ); JTPComponents.addTab("Finish", JPFinish); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(JTPComponents) ); layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(JTPComponents) ); pack(); }// </editor-fold>//GEN-END:initComponents private void JRBGmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBGmailActionPerformed setAuthPanel(authGmail); }//GEN-LAST:event_JRBGmailActionPerformed private void JRBSMTPActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBSMTPActionPerformed setAuthPanel(authSmtp); }//GEN-LAST:event_JRBSMTPActionPerformed private void JBAddNumberActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBAddNumberActionPerformed addEmail(); }//GEN-LAST:event_JBAddNumberActionPerformed private void JTCellNumbersKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTCellNumbersKeyPressed if (evt.getKeyCode() == KeyEvent.VK_DELETE) { int[] selectedIndeces = JTCellNumbers.getSelectedRows(); for (int i = selectedIndeces.length - 1; i >= 0; i--) { // Iterate from the bottom up ((DefaultTableModel) JTCellNumbers.getModel()).removeRow(selectedIndeces[i]); } } else if (evt.getKeyCode() == KeyEvent.VK_TAB) { this.transferFocus(); evt.consume(); } }//GEN-LAST:event_JTCellNumbersKeyPressed private void JTFCellNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTFCellNumberKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { addEmail(); } }//GEN-LAST:event_JTFCellNumberKeyPressed private void JCBCarrierKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JCBCarrierKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { addEmail(); } }//GEN-LAST:event_JCBCarrierKeyPressed private void JBAddNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JBAddNumberKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { addEmail(); } }//GEN-LAST:event_JBAddNumberKeyPressed private void JBSaveChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBSaveChangesActionPerformed saveChanges(); }//GEN-LAST:event_JBSaveChangesActionPerformed private void JBCancelChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBCancelChangesActionPerformed cancelChanges(); }//GEN-LAST:event_JBCancelChangesActionPerformed private void JBDisableEmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBDisableEmailActionPerformed disableEmail(); }//GEN-LAST:event_JBDisableEmailActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private ButtonGroup BGAuthType; private JButton JBAddNumber; private JButton JBCancelChanges; private JButton JBDisableEmail; private JButton JBSaveChanges; private JComboBox<String> JCBCarrier; private JPanel JPAuthInfo; private JPanel JPAuthentication; private JPanel JPFinish; private JPanel JPSendTo; private JRadioButton JRBGmail; private JRadioButton JRBSMTP; private JTable JTCellNumbers; private JTextField JTFCellNumber; private JTabbedPane JTPComponents; private JLabel jLabel1; private JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables private class AuthenticationCallback implements Runnable { private boolean nextEnabledState = false; public void run() { JBSaveChanges.setEnabled(nextEnabledState); JBCancelChanges.setEnabled(nextEnabledState); JBDisableEmail.setEnabled(nextEnabledState); JRBGmail.setEnabled(nextEnabledState); JRBSMTP.setEnabled(nextEnabledState); nextEnabledState = !nextEnabledState; // Invert } } }
mit
cybersonic/org.cfeclipse.cfml
src/org/cfeclipse/cfml/parser/cfscript/ParseException.java
6569
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */ package org.cfeclipse.cfml.parser.cfscript; /** * This exception is thrown when parse errors are encountered. * You can explicitly create objects of this exception type by * calling the method generateParseException in the generated * parser. * * You can modify this class to customize your error reporting * mechanisms so long as you retain the public fields. */ public class ParseException extends Exception { /** * This constructor is used by the method "generateParseException" * in the generated parser. Calling this constructor generates * a new object of this type with the fields "currentToken", * "expectedTokenSequences", and "tokenImage" set. The boolean * flag "specialConstructor" is also set to true to indicate that * this constructor was used to create this object. * This constructor calls its super class with the empty string * to force the "toString" method of parent class "Throwable" to * print the error message in the form: * ParseException: <result of getMessage> */ public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal ) { super(""); specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /** * The following constructors are for use by you for whatever * purpose you can think of. Constructing the exception in this * manner makes the exception behave in the normal way - i.e., as * documented in the class "Throwable". The fields "errorToken", * "expectedTokenSequences", and "tokenImage" do not contain * relevant information. The JavaCC generated code does not use * these constructors. */ public ParseException() { super(); specialConstructor = false; } public ParseException(String message) { super(message); specialConstructor = false; } /** * This variable determines which constructor was used to create * this object and thereby affects the semantics of the * "getMessage" method (see below). */ protected boolean specialConstructor; /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token * followng this token will (therefore) be the first error token. */ public Token currentToken; /** * Each entry in this array is an array of integers. Each array * of integers represents a sequence of tokens (by their ordinal * values) that is expected at this point of the parse. */ public int[][] expectedTokenSequences; /** * This is a reference to the "tokenImage" array of the generated * parser within which the parse error occurred. This array is * defined in the generated ...Constants interface. */ public String[] tokenImage; /** * This method has the standard behavior when this object has been * created using the standard constructors. Otherwise, it uses * "currentToken" and "expectedTokenSequences" to generate a parse * error message and returns it. If this object has been created * due to a parse error, and you do not catch it (it gets thrown * from the parser), then this method is called during the printing * of the final stack trace, and hence the correct error message * gets displayed. */ public String getMessage() { if (!specialConstructor) { return super.getMessage(); } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; } /** * The end of line string for this machine. */ protected String eol = System.getProperty("line.separator", "\n"); /** * Used to convert raw characters to their escaped version * when these raw version cannot be used as part of an ASCII * string literal. */ protected String add_escapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } }
mit
r24mille/IesoPublicReportBindings
src/main/java/ca/ieso/reports/schema/iomspublicplannedoutageday/ConfidentialityClass.java
1298
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.12.23 at 08:29:00 AM CST // package ca.ieso.reports.schema.iomspublicplannedoutageday; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ConfidentialityClass. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ConfidentialityClass"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="PUB"/> * &lt;enumeration value="CNF"/> * &lt;enumeration value="HCNF"/> * &lt;enumeration value="INT"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ConfidentialityClass") @XmlEnum public enum ConfidentialityClass { PUB, CNF, HCNF, INT; public String value() { return name(); } public static ConfidentialityClass fromValue(String v) { return valueOf(v); } }
mit
jwiesel/sfdcCommander
sfdcCommander/src/main/java/com/sforce/soap/partner/FieldLevelSearchMetadata.java
5935
/** * FieldLevelSearchMetadata.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.sforce.soap.partner; public class FieldLevelSearchMetadata implements java.io.Serializable { private java.lang.String label; private java.lang.String name; private java.lang.String type; public FieldLevelSearchMetadata() { } public FieldLevelSearchMetadata( java.lang.String label, java.lang.String name, java.lang.String type) { this.label = label; this.name = name; this.type = type; } /** * Gets the label value for this FieldLevelSearchMetadata. * * @return label */ public java.lang.String getLabel() { return label; } /** * Sets the label value for this FieldLevelSearchMetadata. * * @param label */ public void setLabel(java.lang.String label) { this.label = label; } /** * Gets the name value for this FieldLevelSearchMetadata. * * @return name */ public java.lang.String getName() { return name; } /** * Sets the name value for this FieldLevelSearchMetadata. * * @param name */ public void setName(java.lang.String name) { this.name = name; } /** * Gets the type value for this FieldLevelSearchMetadata. * * @return type */ public java.lang.String getType() { return type; } /** * Sets the type value for this FieldLevelSearchMetadata. * * @param type */ public void setType(java.lang.String type) { this.type = type; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof FieldLevelSearchMetadata)) return false; FieldLevelSearchMetadata other = (FieldLevelSearchMetadata) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.label==null && other.getLabel()==null) || (this.label!=null && this.label.equals(other.getLabel()))) && ((this.name==null && other.getName()==null) || (this.name!=null && this.name.equals(other.getName()))) && ((this.type==null && other.getType()==null) || (this.type!=null && this.type.equals(other.getType()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getLabel() != null) { _hashCode += getLabel().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } if (getType() != null) { _hashCode += getType().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(FieldLevelSearchMetadata.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "FieldLevelSearchMetadata")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("label"); elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "label")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("name"); elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "name")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("type"); elemField.setXmlName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "type")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
mit
lightofanima/GameDevelopmentTutorial
Pong/core/src/sprites/Enemy.java
564
package sprites; public class Enemy extends Paddle { public Enemy(int x, int y) { super(x,y); } int updateFrameCounter = 0; float moveDirection = 0; public void update(float dt, Ball ball) { //if(++updateFrameCounter%3==0) //{ updateFrameCounter = 0; if(position.y < ball.position.y) moveDirection = 1; else if (position.y > ball.position.y) moveDirection = -1; else moveDirection = 0; //} setVVelocity(moveDirection, dt); position.add(velocity.x, velocity.y); bounds.setPosition(position.x, position.y); } }
mit
mcisb/SuBliMinaLToolbox
src/main/java/org/mcisb/subliminal/metacyc/MetaCycExtracter.java
7913
/******************************************************************************* * Manchester Centre for Integrative Systems Biology * University of Manchester * Manchester M1 7ND * United Kingdom * * Copyright (C) 2008 University of Manchester * * This program is released under the Academic Free License ("AFL") v3.0. * (http://www.opensource.org/licenses/academic.php) *******************************************************************************/ package org.mcisb.subliminal.metacyc; import java.io.*; import java.util.*; import org.mcisb.subliminal.*; import org.mcisb.subliminal.model.*; import org.mcisb.subliminal.sbml.*; import org.sbml.jsbml.*; /** * @author Neil Swainston */ public class MetaCycExtracter extends Extracter { /** * */ private final static String COMPARTMENT_SUFFIX = "_CCO_"; //$NON-NLS-1$ /** * */ private final static String MXN_REF_PREFIX = "metacyc:"; //$NON-NLS-1$ /** * * @param taxonomyId * @param outFile * @param metaCycDirectory * @throws Exception */ public static void run( final String taxonomyId, final File outFile, final File metaCycDirectory ) throws Exception { final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId ); if( taxonomyName == null ) { throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$ } final SBMLDocument document = initDocument( taxonomyId ); run( taxonomyId, taxonomyName, document, metaCycDirectory, false ); XmlFormatter.getInstance().write( document, outFile ); SbmlFactory.getInstance().unregister(); } /** * * @param taxonomyId * @param outFile * @throws Exception */ public static void run( final String taxonomyId, final File outFile ) throws Exception { final SBMLDocument document = initDocument( taxonomyId ); run( taxonomyId, document ); XmlFormatter.getInstance().write( document, outFile ); SbmlFactory.getInstance().unregister(); } /** * * @param taxonomyId * @param document * @throws Exception */ public static void run( final String taxonomyId, final SBMLDocument document ) throws Exception { final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId ); if( taxonomyName == null ) { throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$ } final File tempDirectory = new File( System.getProperty( "java.io.tmpdir" ) ); //$NON-NLS-1$ run( taxonomyId, taxonomyName, document, new File( tempDirectory, taxonomyName ), true ); } /** * * @param taxonomyId * @param document * @param metaCycDirectory * @throws Exception */ private static void run( final String taxonomyId, final String taxonomyName, final SBMLDocument document, final File metaCycDirectory, final boolean deleteSource ) throws Exception { try { final File metaCycSource = MetaCycDownloader.getMetaCycSource( metaCycDirectory, taxonomyName ); final File sbml = SubliminalUtils.find( metaCycSource, "metabolic-reactions.sbml" ); //$NON-NLS-1$ if( sbml != null ) { System.out.println( "MetaCyc: " + taxonomyName ); //$NON-NLS-1$ final MetaCycFactory metaCycFactory = initFactory( metaCycSource ); final SBMLDocument inDocument = new SBMLReader().readSBML( sbml ); final Model inModel = inDocument.getModel(); for( int l = 0; l < inModel.getNumReactions(); l++ ) { final Reaction inReaction = inModel.getReaction( l ); final Reaction outReaction = addReaction( document.getModel(), inReaction, taxonomyId, metaCycFactory ); if( inReaction.isSetReversible() ) { outReaction.setReversible( inReaction.getReversible() ); } } final Collection<Object[]> resources = new ArrayList<>(); resources.add( new Object[] { "http://identifiers.org/biocyc/" + metaCycFactory.getOrganismId(), CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$ resources.add( new Object[] { "http://identifiers.org/pubmed/10592180", CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$ addResources( inModel, resources ); } if( deleteSource ) { SubliminalUtils.delete( metaCycSource ); } } catch( FileNotFoundException e ) { e.printStackTrace(); } } /** * * @param source * @return MetaCycReactionsParser */ private static MetaCycFactory initFactory( final File source ) { final File versionFile = SubliminalUtils.find( source, "version.dat" ); //$NON-NLS-1$ final File reactionsFile = SubliminalUtils.find( source, "reactions.dat" ); //$NON-NLS-1$ final File enzymesFile = SubliminalUtils.find( source, "enzymes.col" ); //$NON-NLS-1$ return new MetaCycFactory( versionFile, reactionsFile, enzymesFile ); } /** * * @param outModel * @param inReaction * @param taxonomyId * @param metaCycEnzymeFactory * @param resources * @return Reaction * @throws Exception */ private static Reaction addReaction( final Model outModel, final Reaction inReaction, final String taxonomyId, final MetaCycFactory metaCycEnzymeFactory ) throws Exception { final String inReactionId = inReaction.getId(); Reaction outReaction = addReaction( outModel, getId( inReactionId ), DEFAULT_COMPARTMENT_ID ); if( outReaction == null ) { outReaction = outModel.createReaction(); outReaction.setId( inReactionId ); outReaction.setName( inReaction.getName() ); for( int l = 0; l < inReaction.getNumReactants(); l++ ) { final SpeciesReference inReactant = inReaction.getReactant( l ); final SpeciesReference outReactant = outReaction.createReactant(); final String speciesId = inReactant.getSpecies(); final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL ); outReactant.setSpecies( outSpecies.getId() ); outReactant.setStoichiometry( inReactant.getStoichiometry() ); } for( int l = 0; l < inReaction.getNumProducts(); l++ ) { final SpeciesReference inProduct = inReaction.getProduct( l ); final SpeciesReference outProduct = outReaction.createProduct(); final String speciesId = inProduct.getSpecies(); final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL ); outProduct.setSpecies( outSpecies.getId() ); outProduct.setStoichiometry( inProduct.getStoichiometry() ); } } final Map<String,Integer> enzymes = metaCycEnzymeFactory.getEnzymes( inReactionId ); final String[] enzymeIds = enzymes.keySet().toArray( new String[ enzymes.keySet().size() ] ); for( String enzymeId : enzymeIds ) { final String formattedEnzymeId = "MetaCyc:" + MetaCycUtils.unencode( enzymeId ); //$NON-NLS-1$ final List<String[]> results = SubliminalUtils.searchUniProt( SubliminalUtils.encodeUniProtSearchTerm( formattedEnzymeId ) + "+AND+taxonomy:" + taxonomyId );//$NON-NLS-1$ addEnzymes( outReaction, results, SubliminalUtils.getNormalisedId( formattedEnzymeId ), enzymeId, new ArrayList<Object[]>() ); } return outReaction; } /** * * @param id * @return String */ private static String getId( final String id ) { String formattedId = id; if( formattedId.contains( COMPARTMENT_SUFFIX ) ) { formattedId = formattedId.substring( 0, id.indexOf( COMPARTMENT_SUFFIX ) ); } return MXN_REF_PREFIX + MetaCycUtils.unencode( formattedId ); } /** * @param args * @throws Exception */ public static void main( String[] args ) throws Exception { if( args.length == 2 ) { MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ) ); } else if( args.length == 3 ) { MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ), new File( args[ 2 ] ) ); } } }
mit
munificent/magpie-optionally-typed
src/com/stuffwithstuff/magpie/interpreter/builtin/BuiltInCallable.java
263
package com.stuffwithstuff.magpie.interpreter.builtin; import com.stuffwithstuff.magpie.interpreter.Interpreter; import com.stuffwithstuff.magpie.interpreter.Obj; public interface BuiltInCallable { Obj invoke(Interpreter interpreter, Obj thisObj, Obj arg); }
mit
aaryn101/lol4j
src/main/java/lol4j/protocol/dto/champion/ChampionDto.java
1387
package lol4j.protocol.dto.champion; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by Aaron Corley on 12/10/13. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ChampionDto { private boolean active; private boolean botEnabled; private boolean botMmEnabled; private boolean freeToPlay; private long id; private boolean rankedPlayEnabled; public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public boolean isBotEnabled() { return botEnabled; } public void setBotEnabled(boolean botEnabled) { this.botEnabled = botEnabled; } public boolean isBotMmEnabled() { return botMmEnabled; } public void setBotMmEnabled(boolean botMmEnabled) { this.botMmEnabled = botMmEnabled; } public boolean isFreeToPlay() { return freeToPlay; } public void setFreeToPlay(boolean freeToPlay) { this.freeToPlay = freeToPlay; } public long getId() { return id; } public void setId(long id) { this.id = id; } public boolean isRankedPlayEnabled() { return rankedPlayEnabled; } public void setRankedPlayEnabled(boolean rankedPlayEnabled) { this.rankedPlayEnabled = rankedPlayEnabled; } }
mit
GarciaPL/BankNow
src/main/java/pl/garciapl/banknow/service/TransactionService.java
703
package pl.garciapl.banknow.service; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import pl.garciapl.banknow.model.Transaction; import pl.garciapl.banknow.service.exceptions.GenericBankNowException; import pl.garciapl.banknow.service.exceptions.InsufficientFundsException; /** * TransactionService - interface for TransactionServiceImpl * * @author lukasz */ public interface TransactionService { List<Transaction> getAllTransactions(); void makeDeposit(BigInteger account, BigDecimal amount); void makeTransfer(BigInteger sender, BigInteger recipient, BigDecimal amount) throws InsufficientFundsException, GenericBankNowException; }
mit
Eadgyth/Java-Programming-Editor
src/eg/utils/SystemParams.java
1846
package eg.utils; import java.io.File; import java.awt.Toolkit; /** * Static system properties */ public class SystemParams { /** * True if the OS is Windows, false otherwise */ public static final boolean IS_WINDOWS; /** * The Java version */ public static final String JAVA_VERSION; /** * True if the Java version is higher than 8, false otherwise */ public static final boolean IS_JAVA_9_OR_HIGHER; /** * True if the Java version is 13 or higher, false otherwise */ public static final boolean IS_JAVA_13_OR_HIGHER; /** * The modifier mask for menu shortcuts */ public static final int MODIFIER_MASK; /** * The path to the '.eadgyth' directory in the user home * directory */ public static final String EADGYTH_DATA_DIR; static { String os = System.getProperty("os.name").toLowerCase(); IS_WINDOWS = os.contains("win"); String userHome = System.getProperty("user.home"); EADGYTH_DATA_DIR = userHome + File.separator + ".eadgyth"; JAVA_VERSION = System.getProperty("java.version"); IS_JAVA_9_OR_HIGHER = !JAVA_VERSION.startsWith("1.8"); IS_JAVA_13_OR_HIGHER = IS_JAVA_9_OR_HIGHER && "13".compareTo(JAVA_VERSION) <= 0; // // up to Java 9: MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); // // as of Java 10: //MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); } /** * Returns if the Eadgyth data directory '.eadgyth' exists * in the user home directory * * @return true if the directory exists, false otherwise * @see #EADGYTH_DATA_DIR */ public static boolean existsEadgythDataDir() { return new File(EADGYTH_DATA_DIR).exists(); } // //--private--/ // private SystemParams() {} }
mit
UCT-White-Lab/provisioning-jig
fw_update/ST_decrypt.java
22664
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; // import org.apache.commons.cli.*; class Dumper { private static FileOutputStream fstream; public Dumper(String filename) { try { fstream = new FileOutputStream(filename); } catch (FileNotFoundException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } /** * Dump byte array to a file * * @param dump byte array * @param filename */ static void dump(byte[] dump, String filename) { if (dump == null) { return; } FileOutputStream fos = null; try { fos = new FileOutputStream(filename); } catch (FileNotFoundException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } try { fos.write(dump, 0, dump.length); fos.flush(); fos.close(); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } void append(byte[] b) { try { fstream.write(b); } catch (IOException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } void close() { try { fstream.close(); } catch (IOException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } } class Crypto { private static int d(final int n) { final long n2 = n & 0xFFFFFFFFL; return (int) ((n2 & 0x7F7F7F7FL) << 1 ^ ((n2 & 0xFFFFFFFF80808080L) >> 7) * 27L); } private static int a(final int n, final int n2) { final long n3 = n & 0xFFFFFFFFL; return (int) (n3 >> n2 * 8 | n3 << 32 - n2 * 8); } static int polynom2(int n) { final int d3; final int d2; final int d = d(d2 = d(d3 = d(n))); n ^= d; return d3 ^ (d2 ^ d ^ a(d3 ^ n, 3) ^ a(d2 ^ n, 2) ^ a(n, 1)); } static int polynom(int n) { return (d(n) ^ a(n ^ d(n), 3) ^ a(n, 2) ^ a(n, 1)); } } public class ST_decrypt { /** * Encrypt or decrypt input file */ private static boolean encrypt; private static String encryptionKey; private static Dumper dumper; public static void main(String[] args) { // CommandLineParser parser = new DefaultParser(); // Options options = new Options(); // String help = "st_decrypt.jar [-e] -k <key> -i <input> -o <output>"; // options.addOption("k", "key", true, "encryption key"); // options.addOption("e", "encrypt", false, "encrypt binary"); // options.addOption("i", "input", true, "input file"); // options.addOption("o", "output", true, "output file"); // HelpFormatter formatter = new HelpFormatter(); // CommandLine opts = null; // try { // opts = parser.parse(options, args); // if (opts.hasOption("key") // && opts.hasOption("input") // && opts.hasOption("output")) { // encryptionKey = opts.getOptionValue("key"); // } else { // formatter.printHelp(help, options); // System.exit(1); // } // encrypt = opts.hasOption("encrypt"); // } catch (ParseException exp) { // System.out.println(exp.getMessage()); // formatter.printHelp(help, options); // System.exit(1); // } // String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin"; // String input = "/home/jonathan/stm_jig/usb_sniff/f2_5.bin"; // String output = "/home/jonathan/stm_jig/usb_sniff/16_encrypted"; // String input = "/home/jonathan/stm_jig/usb_sniff/16_unencrypted"; // String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java_enc.bin"; // String input = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin"; // encryptionKey = "I am a key, wawawa"; // // encryptionKey = unHex("496CDB76964E46637CC0237ED87B6B7F"); // // encryptionKey = unHex("E757D2F9F122DEB3FB883ECC1AF4C688"); // // encryptionKey = unHex("8DBDA2460CD8069682D3E9BB755B7FB9"); // encryptionKey = unHex("5F4946053BD9896E8F4CE917A6D2F21A"); // encrypt=true; encryptionKey = "best performance"; int dataLength = 30720;//(int)getFileLen("/home/jonathan/stm_jig/provisioning-jig/fw_update/fw_upgrade/f2_1.bin"); byte[] fw = new byte[dataLength]; byte[] key = new byte[16];//encryptionKey.getBytes(); byte[] data = new byte[dataLength];// {0xF7, 0x72, 0x44, 0xB3, 0xFC, 0x86, 0xE0, 0xDC, 0x20, 0xE1, 0x74, 0x2D, 0x3A, 0x29, 0x0B, 0xD2}; str_to_arr(encryptionKey, key); readFileIntoArr(System.getProperty("user.dir") + "/f2_1.bin", data); decrypt(data, fw, key, dataLength); System.out.println(dataLength); System.out.println(toHexStr(fw).length()); // Write out the decrypted fw for debugging String outf = "fw_decrypted.bin"; dumper = new Dumper(outf); dumper.dump(fw, outf); dumper.close(); // fw now contains our decrypted firmware // Make a key from the first 4 and last 12 bytes returned by f308 encryptionKey = "I am key, wawawa"; byte[] newKey = new byte[16]; byte[] f308 = new byte[16]; str_to_arr(encryptionKey, key); readFileIntoArr("f303_bytes_4_12.bin", f308); encrypt(f308, newKey, key, 16); System.out.print("Using key: "); System.out.println(toHexStr(newKey)); System.out.print("From bytes: "); System.out.println(toHexStr(f308)); byte[] enc_fw = new byte[dataLength]; encrypt(fw, enc_fw, newKey, dataLength); // System.out.println(toHexStr(enc_fw)); // Now for real String outfile = "fw_re_encrypted.bin"; dumper = new Dumper(outfile); dumper.dump(enc_fw, outfile); dumper.close(); byte[] a = new byte[16]; byte[] ans = new byte[16]; str_to_arr(unHex("ffffffffffffffffffffffffd32700a5"), a); encrypt(a, ans, newKey, 16); System.out.println("Final 16 bytes: " + toHexStr(ans)); outfile = "version_thingee_16.bin"; dumper = new Dumper(outfile); dumper.dump(ans, outfile); dumper.close(); // dumper = new Dumper(output); // dump_fw(input); // dumper.close(); // System.out.println("Done!"); } // ***************** MY Code functions ***************** JW static void readFileIntoArr(String file, byte[] data){ FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { System.out.print(file); System.out.println("Invalid file name"); System.exit(1); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) { long len = getFileLen(file); bufferedInputStream.read(data); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } static String toHexStr(byte[] B){ StringBuilder str = new StringBuilder(); for(int i = 0; i < B.length; i++){ str.append(String.format("%02x", B[i])); } return str.toString(); } static String unHex(String arg) { String str = ""; for(int i=0;i<arg.length();i+=2) { String s = arg.substring(i, (i + 2)); int decimal = Integer.parseInt(s, 16); str = str + (char) decimal; } return str; } // ******************************************************* static long getFileLen(String file) { long n2 = 0L; FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { } try { BufferedInputStream bufferedInputStream = new BufferedInputStream(fis); while (true) { int read; try { read = bufferedInputStream.read(); } catch (IOException ex) { System.out.println("Failure opening file"); read = -1; } if (read == -1) { break; } ++n2; } bufferedInputStream.close(); } catch (IOException ex3) { System.out.println("Failure getting firmware data"); } return n2; } /** * * @param array firmware byte array * @param n length * @param n2 ?? * @return */ static long encodeAndWrite(final byte[] array, long n, final int n2) { long a = 0L; final byte[] array2 = new byte[4 * ((array.length + 3) / 4)]; // Clever hack to get multiple of fourwith padding final byte[] array3 = new byte[16]; str_to_arr(encryptionKey, array3); if (encrypt) { encrypt(array, array2, array3, array.length); } else { decrypt(array, array2, array3, array.length); } /* Send chunk of data to device */ dumper.append(array2); return a; } static long writeFirmware(final BufferedInputStream bufferedInputStream, final long n) { long a = 0L; final byte[] array = new byte[3072]; long n4 = 0L; try { while (n4 < n && a == 0L) { final long n5; if ((n5 = bufferedInputStream.read(array)) != -1L) { encodeAndWrite(array, n4 + 134234112L, 3072); n4 += n5; } } } catch (IOException ex) { System.out.println("Failure reading file: " + ex.getMessage()); System.exit(1); } return a; } static void dump_fw(String file) { FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { System.out.println("Invalid file name"); System.exit(1); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) { long len = getFileLen(file); writeFirmware(bufferedInputStream, len); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } private static int pack_u32(final int n, final int n2, final int n3, final int n4) { return (n << 24 & 0xFF000000) + (n2 << 16 & 0xFF0000) + (n3 << 8 & 0xFF00) + (n4 & 0xFF); } private static int u32(final int n) { return n >>> 24; } private static int u16(final int n) { return n >> 16 & 0xFF; } private static int u8(final int n) { return n >> 8 & 0xFF; } /** * Converts the key from String to byte array * * @param s input string * @param array destination array */ public static void str_to_arr(final String s, final byte[] array) { final char[] charArray = s.toCharArray(); for (int i = 0; i < 16; ++i) { array[i] = (byte) charArray[i]; } } private static void key_decode(final byte[] array, final int[] array2) { // core.a.a(byte[], byte[]) final int[] array3 = new int[4]; for (int i = 0; i < 4; ++i) { array2[i] = (array3[i] = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * i)); } for (int j = 0; j < 10;) { array3[0] ^= (int) (pack_u32(aes_x[u16(array3[3])], aes_x[u8(array3[3])], aes_x[array3[3] & 0xFF], aes_x[u32(array3[3])]) ^ rcon[j++]); array3[1] ^= array3[0]; array3[2] ^= array3[1]; array3[3] ^= array3[2]; System.arraycopy(array3, 0, array2, 4 * j, 4); } } /** * Encrypt firmware file */ static void encrypt(final byte[] src, final byte[] dest, byte[] key, int len) { final byte[] array3 = new byte[16]; int n = 0; key_decode(key, mystery_key); while (len > 0) { key = null; int n2; if (len >= 16) { key = Arrays.copyOfRange(src, n, n + 16); n2 = 16; } else if ((n2 = len) > 0) { final byte[] array4 = new byte[16]; for (int j = 0; j < len; ++j) { array4[j] = src[n + j]; } for (int k = len; k < 16; ++k) { array4[k] = (byte) Double.doubleToLongBits(Math.random()); } key = array4; } if (len > 0) { final int[] a = mystery_key; final int[] tmp = new int[4]; int n3 = 10; int n4 = 0; for (int l = 0; l < 4; ++l) { tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 0]); } n4 += 4; do { final int a2 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]); final int a3 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]); final int a4 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]); final int a5 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]); tmp[0] = (Crypto.polynom(a2) ^ a[n4]); tmp[1] = (Crypto.polynom(a3) ^ a[n4 + 1]); tmp[2] = (Crypto.polynom(a4) ^ a[n4 + 2]); tmp[3] = (Crypto.polynom(a5) ^ a[n4 + 3]); n4 += 4; } while (--n3 != 1); final int a6 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]); final int a7 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]); final int a8 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]); final int a9 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]); final int n5 = a6 ^ a[n4]; final int n6 = a7 ^ a[n4 + 1]; final int n7 = a8 ^ a[n4 + 2]; final int n8 = a9 ^ a[n4 + 3]; ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n5); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n6); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n7); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n8); } for (int i = 0; i < 16; ++i) { dest[n + i] = array3[i]; } len -= n2; n += n2; } } /** * Decrypt firmware file * * @param src firmware file * @param dest destination array * @param key key * @param len array.length */ static void decrypt(final byte[] src, final byte[] dest, byte[] key, int len) { final byte[] array3 = new byte[16]; int n = 0; key_decode(key, mystery_key); while (len > 0) { key = null; int n2; if (len >= 16) { key = Arrays.copyOfRange(src, n, n + 16); n2 = 16; } else if ((n2 = len) > 0) { final byte[] array4 = new byte[16]; for (int j = 0; j < len; ++j) { array4[j] = src[n + j]; } for (int k = len; k < 16; ++k) { array4[k] = (byte) Double.doubleToLongBits(Math.random()); } key = array4; } if (len > 0) { final int[] a = mystery_key; final int[] tmp = new int[4]; int n3 = 10; int n4 = 40; for (int l = 0; l < 4; ++l) { tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 40]); } n4 -= 8; do { final int n5 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4]; final int n6 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5]; final int n7 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6]; final int n8 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7]; tmp[0] = Crypto.polynom2(n5); tmp[1] = Crypto.polynom2(n6); tmp[2] = Crypto.polynom2(n7); tmp[3] = Crypto.polynom2(n8); n4 -= 4; } while (--n3 != 1); final int n9 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4]; final int n10 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5]; final int n11 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6]; final int n12 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7]; ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n9); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n10); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n11); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n12); } for (int i = 0; i < n2; ++i) { dest[n + i] = array3[i]; } len -= n2; n += n2; } } static int[] mystery_key = new int[44]; static int[] aes_x = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; static int[] aes_y = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; static long[] rcon = { 0x01000000L, 0x02000000L, 0x04000000L, 0x08000000L, 0x10000000L, 0x20000000L, 0x40000000L, 0xFFFFFFFF80000000L, 0x1B000000L, 0x36000000L }; }
mit
wiselenium/wiselenium
wiselenium-elements/src/main/java/com/github/wiselenium/elements/component/MultiSelect.java
4862
/** * Copyright (c) 2013 Andre Ricardo Schaffer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.wiselenium.elements.component; import java.util.List; /** * Represents a HTML Multiple Select. * * @author Andre Ricardo Schaffer * @since 0.3.0 */ public interface MultiSelect extends Component<MultiSelect> { /** * Deselects all options. * * @return This select instance to allow chain calls. * @since 0.3.0 */ MultiSelect deselectAll(); /** * Deselects all options at the given indexes. This is done by examing the "index" attribute of * an element, and not merely by counting. * * @param indexes The option at this index will be selected. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByIndex(int... indexes); /** * Deselects all options that have a value matching the argument. That is, when given "foo" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param values The values to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByValue(String... values); /** * Deselects all options that display text matching the argument. That is, when given "Bar" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param texts The visible texts to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect deselectByVisibleText(String... texts); /** * Deselects some options of this select if not already deselected. * * @param options The options to be deselected. * @return This select instance in order to allow chain calls. * @since 0.3.0 */ MultiSelect deselectOptions(Option... options); /** * Gets the options of this select. * * @return The options of this select. * @since 0.3.0 */ List<Option> getOptions(); /** * Returns the selected options. * * @return The selected options. * @since 0.3.0 */ List<Option> getSelectedOptions(); /** * Returns the selected values. * * @return The selected values. * @since 0.3.0 */ List<String> getSelectedValues(); /** * Returns the selected visible texts. * * @return The selected visible texts. * @since 0.3.0 */ List<String> getSelectedVisibleTexts(); /** * Selects all options. * * @return This select instance to allow chain calls. * @since 0.3.0 */ MultiSelect selectAll(); /** * Selects all options at the given indexes. This is done by examing the "index" attribute of an * element, and not merely by counting. * * @param indexes The option at this index will be selected. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByIndex(int... indexes); /** * Selects all options that have a value matching the argument. That is, when given "foo" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param values The values to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByValue(String... values); /** * Selects all options that display text matching the argument. That is, when given "Bar" this * would select an option like: &lt;option value="foo"&gt;Bar&lt;/option&gt; * * @param texts The visible texts to match against. * @return This select element to allow chain calls. * @since 0.3.0 */ MultiSelect selectByVisibleText(String... texts); /** * Selects some options of this select if not already selected. * * @param options The options to be selected. * @return This select instance in order to allow chain calls. * @since 0.3.0 */ MultiSelect selectOptions(Option... options); }
mit
lexek/chat
src/main/java/lexek/wschat/db/dao/UserDao.java
8668
package lexek.wschat.db.dao; import lexek.wschat.chat.e.EntityNotFoundException; import lexek.wschat.chat.e.InvalidInputException; import lexek.wschat.db.model.DataPage; import lexek.wschat.db.model.UserData; import lexek.wschat.db.model.UserDto; import lexek.wschat.db.model.form.UserChangeSet; import lexek.wschat.util.Pages; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.jvnet.hk2.annotations.Service; import javax.inject.Inject; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static lexek.wschat.db.jooq.tables.User.USER; import static lexek.wschat.db.jooq.tables.Userauth.USERAUTH; @Service public class UserDao { private final DSLContext ctx; @Inject public UserDao(DSLContext ctx) { this.ctx = ctx; } public boolean tryChangeName(long id, String newName, boolean ignoreCheck) { try { Condition condition = USER.ID.equal(id); if (!ignoreCheck) { condition.and(USER.RENAME_AVAILABLE.equal(true)); } return ctx .update(USER) .set(USER.NAME, newName) .set(USER.RENAME_AVAILABLE, false) .where(condition) .execute() == 1; } catch (DataAccessException e) { throw new InvalidInputException("name", "NAME_TAKEN"); } } public UserDto getByNameOrEmail(String name) { Record record = ctx .select() .from(USER) .where( USER.EMAIL.isNotNull(), USER.NAME.equal(name).or(USER.EMAIL.equal(name)), USER.EMAIL_VERIFIED.isTrue() ) .fetchOne(); return UserDto.fromRecord(record); } public UserDto getByName(String name) { Record record = ctx .select() .from(USER) .where(USER.NAME.equal(name)) .fetchOne(); return UserDto.fromRecord(record); } public UserDto getById(long id) { Record record = ctx .select() .from(USER) .where(USER.ID.equal(id)) .fetchOne(); return UserDto.fromRecord(record); } public UserDto update(long id, UserChangeSet changeSet) { Map<org.jooq.Field<?>, Object> changeMap = new HashMap<>(); if (changeSet.getBanned() != null) { changeMap.put(USER.BANNED, changeSet.getBanned()); } if (changeSet.getRenameAvailable() != null) { changeMap.put(USER.RENAME_AVAILABLE, changeSet.getRenameAvailable()); } if (changeSet.getName() != null) { changeMap.put(USER.NAME, changeSet.getName()); } if (changeSet.getRole() != null) { changeMap.put(USER.ROLE, changeSet.getRole().toString()); } UserDto userDto = null; boolean success = ctx .update(USER) .set(changeMap) .where(USER.ID.equal(id)) .execute() == 1; if (success) { Record record = ctx .selectFrom(USER) .where(USER.ID.equal(id)) .fetchOne(); userDto = UserDto.fromRecord(record); } return userDto; } public void setColor(long id, String color) { ctx .update(USER) .set(USER.COLOR, color) .where(USER.ID.equal(id)) .execute(); } public DataPage<UserData> getAllPaged(int page, int pageLength) { List<UserData> data = ctx .select( USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE, USER.EMAIL, USER.EMAIL_VERIFIED, USER.CHECK_IP, DSL.groupConcat(USERAUTH.SERVICE).as("authServices"), DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames") ) .from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID))) .groupBy(USER.ID) .orderBy(USER.ID) .limit(page * pageLength, pageLength) .fetch() .stream() .map(record -> new UserData( UserDto.fromRecord(record), collectAuthServices( record.getValue("authServices", String.class), record.getValue("authNames", String.class) ) )) .collect(Collectors.toList()); return new DataPage<>(data, page, Pages.pageCount(pageLength, ctx.fetchCount(USER))); } public DataPage<UserData> searchPaged(Integer page, int pageLength, String nameParam) { List<UserData> data = ctx .select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.CHECK_IP, USER.RENAME_AVAILABLE, USER.EMAIL, USER.EMAIL_VERIFIED, DSL.groupConcat(USERAUTH.SERVICE).as("authServices"), DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames")) .from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID))) .where(USER.NAME.like(nameParam, '!')) .groupBy(USER.ID) .orderBy(USER.ID) .limit(page * pageLength, pageLength) .fetch() .stream() .map(record -> new UserData( UserDto.fromRecord(record), collectAuthServices( record.getValue("authServices", String.class), record.getValue("authNames", String.class) ) )) .collect(Collectors.toList()); return new DataPage<>(data, page, Pages.pageCount(pageLength, ctx.fetchCount(USER, USER.NAME.like(nameParam, '!')))); } public List<UserDto> searchSimple(int pageLength, String nameParam) { return ctx .selectFrom(USER) .where(USER.NAME.like(nameParam, '!')) .groupBy(USER.ID) .orderBy(USER.ID) .limit(pageLength) .fetch() .stream() .map(UserDto::fromRecord) .collect(Collectors.toList()); } public boolean delete(UserDto user) { return ctx .delete(USER) .where(USER.ID.equal(user.getId())) .execute() == 1; } public boolean checkName(String username) { return ctx .selectOne() .from(USER) .where(USER.NAME.equal(username)) .fetchOne() == null; } public UserData fetchData(long id) { UserData result = null; Record record = ctx .select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE, USER.EMAIL, USER.EMAIL_VERIFIED, USER.CHECK_IP, DSL.groupConcat(USERAUTH.SERVICE).as("authServices"), DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames")) .from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID))) .where(USER.ID.equal(id)) .groupBy(USER.ID) .fetchOne(); if (record != null) { result = new UserData( UserDto.fromRecord(record), collectAuthServices( record.getValue("authServices", String.class), record.getValue("authNames", String.class) ) ); } return result; } public List<UserDto> getAdmins() { return ctx .select() .from(USER) .where(USER.ROLE.in("ADMIN", "SUPERADMIN")) .fetch() .stream() .map(UserDto::fromRecord) .collect(Collectors.toList()); } public void setCheckIp(UserDto user, boolean value) { int rows = ctx .update(USER) .set(USER.CHECK_IP, value) .where(USER.ID.equal(user.getId())) .execute(); if (rows == 0) { throw new EntityNotFoundException("user"); } } private Map<String, String> collectAuthServices(String servicesString, String namesString) { String[] authServices = servicesString.split(",", -1); String[] authNames = namesString.split(",", -1); Map<String, String> result = new HashMap<>(); for (int i = 0; i < authServices.length; ++i) { result.put(authServices[i], authNames[i]); } return result; } }
mit
HenryHarper/Acquire-Reboot
gradle/src/model-core/org/gradle/model/internal/core/NodeBackedModelSet.java
6263
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.model.internal.core; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import groovy.lang.Closure; import org.gradle.api.Action; import org.gradle.api.internal.ClosureBackedAction; import org.gradle.api.specs.Specs; import org.gradle.model.ModelSet; import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor; import org.gradle.model.internal.manage.instance.ManagedInstance; import org.gradle.model.internal.type.ModelType; import java.util.Collection; import java.util.Iterator; import static org.gradle.model.internal.core.NodePredicate.allLinks; public class NodeBackedModelSet<T> implements ModelSet<T>, ManagedInstance { private final String toString; private final ModelType<T> elementType; private final ModelRuleDescriptor descriptor; private final MutableModelNode modelNode; private final ModelViewState state; private final ChildNodeInitializerStrategy<T> creatorStrategy; private final ModelReference<T> elementTypeReference; private Collection<T> elements; public NodeBackedModelSet(String toString, ModelType<T> elementType, ModelRuleDescriptor descriptor, MutableModelNode modelNode, ModelViewState state, ChildNodeInitializerStrategy<T> creatorStrategy) { this.toString = toString; this.elementType = elementType; this.elementTypeReference = ModelReference.of(elementType); this.descriptor = descriptor; this.modelNode = modelNode; this.state = state; this.creatorStrategy = creatorStrategy; } @Override public MutableModelNode getBackingNode() { return modelNode; } @Override public ModelType<?> getManagedType() { return ModelType.of(this.getClass()); } @Override public String toString() { return toString; } @Override public void create(final Action<? super T> action) { state.assertCanMutate(); String name = String.valueOf(modelNode.getLinkCount(ModelNodes.withType(elementType))); ModelPath childPath = modelNode.getPath().child(name); final ModelRuleDescriptor descriptor = this.descriptor.append("create()"); NodeInitializer nodeInitializer = creatorStrategy.initializer(elementType, Specs.<ModelType<?>>satisfyAll()); ModelRegistration registration = ModelRegistrations.of(childPath, nodeInitializer) .descriptor(descriptor) .action(ModelActionRole.Initialize, NoInputsModelAction.of(ModelReference.of(childPath, elementType), descriptor, action)) .build(); modelNode.addLink(registration); } @Override public void afterEach(Action<? super T> configAction) { state.assertCanMutate(); modelNode.applyTo(allLinks(), ModelActionRole.Finalize, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction)); } @Override public void beforeEach(Action<? super T> configAction) { state.assertCanMutate(); modelNode.applyTo(allLinks(), ModelActionRole.Defaults, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction)); } @Override public int size() { state.assertCanReadChildren(); return modelNode.getLinkCount(ModelNodes.withType(elementType)); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean contains(Object o) { return getElements().contains(o); } @Override public Iterator<T> iterator() { return getElements().iterator(); } @Override public Object[] toArray() { return getElements().toArray(); } @Override public <T> T[] toArray(T[] a) { return getElements().toArray(a); } @Override public boolean add(T e) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return getElements().containsAll(c); } @Override public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } // TODO - mix this in using decoration. Also validate closure parameter types, if declared public void create(Closure<?> closure) { create(ClosureBackedAction.of(closure)); } public void afterEach(Closure<?> closure) { afterEach(ClosureBackedAction.of(closure)); } public void beforeEach(Closure<?> closure) { beforeEach(ClosureBackedAction.of(closure)); } private Collection<T> getElements() { state.assertCanReadChildren(); if (elements == null) { elements = Lists.newArrayList( Iterables.transform(modelNode.getLinks(ModelNodes.withType(elementType)), new Function<MutableModelNode, T>() { @Override public T apply(MutableModelNode input) { return input.asImmutable(elementType, descriptor).getInstance(); } }) ); } return elements; } }
mit
Microsoft/vsminecraft
minecraftpkg/MekanismModSample/src/main/java/mekanism/common/transmitters/Transmitter.java
1976
package mekanism.common.transmitters; import mekanism.api.transmitters.DynamicNetwork; import mekanism.api.transmitters.IGridTransmitter; public abstract class Transmitter<A, N extends DynamicNetwork<A, N>> implements IGridTransmitter<A, N> { public N theNetwork = null; public boolean orphaned = true; @Override public N getTransmitterNetwork() { return theNetwork; } @Override public boolean hasTransmitterNetwork() { return !isOrphan() && getTransmitterNetwork() != null; } @Override public void setTransmitterNetwork(N network) { if(theNetwork == network) { return; } if(world().isRemote && theNetwork != null) { theNetwork.transmitters.remove(this); if(theNetwork.transmitters.isEmpty()) { theNetwork.deregister(); } } theNetwork = network; orphaned = theNetwork == null; if(world().isRemote && theNetwork != null) { theNetwork.transmitters.add(this); } } @Override public int getTransmitterNetworkSize() { return hasTransmitterNetwork() ? getTransmitterNetwork().getSize() : 0; } @Override public int getTransmitterNetworkAcceptorSize() { return hasTransmitterNetwork() ? getTransmitterNetwork().getAcceptorSize() : 0; } @Override public String getTransmitterNetworkNeeded() { return hasTransmitterNetwork() ? getTransmitterNetwork().getNeededInfo() : "No Network"; } @Override public String getTransmitterNetworkFlow() { return hasTransmitterNetwork() ? getTransmitterNetwork().getFlowInfo() : "No Network"; } @Override public String getTransmitterNetworkBuffer() { return hasTransmitterNetwork() ? getTransmitterNetwork().getStoredInfo() : "No Network"; } @Override public double getTransmitterNetworkCapacity() { return hasTransmitterNetwork() ? getTransmitterNetwork().getCapacity() : getCapacity(); } @Override public boolean isOrphan() { return orphaned; } @Override public void setOrphan(boolean nowOrphaned) { orphaned = nowOrphaned; } }
mit
thiagorabelo/CommentTemplate
src/commenttemplate/expressions/exceptions/FunctionWithSameNameAlreadyExistsException.java
351
package commenttemplate.expressions.exceptions; /** * * @author thiago */ // @TODO: RuntimeException? public class FunctionWithSameNameAlreadyExistsException extends RuntimeException { /** * Justa a custom mensage. * * @param msg A custom mensage. */ public FunctionWithSameNameAlreadyExistsException(String msg) { super(msg); } }
mit
curtbinder/AndroidStatus
app/src/main/java/info/curtbinder/reefangel/phone/MainActivity.java
17315
/* * The MIT License (MIT) * * Copyright (c) 2015 Curt Binder * * 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 info.curtbinder.reefangel.phone; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.List; import info.curtbinder.reefangel.wizard.SetupWizardActivity; public class MainActivity extends AppCompatActivity implements ActionBar.OnNavigationListener { // public static final int REQUEST_EXIT = 1; // public static final int RESULT_EXIT = 1024; private static final String OPENED_KEY = "OPENED_KEY"; private static final String STATE_CHECKED = "DRAWER_CHECKED"; private static final String PREVIOUS_CHECKED = "PREVIOUS"; // do not switch selected profile when restoring the application state private static boolean fRestoreState = false; public final String TAG = MainActivity.class.getSimpleName(); private RAApplication raApp; private String[] mNavTitles; private Toolbar mToolbar; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private Boolean opened = null; private int mOldPosition = -1; private Boolean fCanExit = false; private Fragment mHistoryContent = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); raApp = (RAApplication) getApplication(); raApp.raprefs.setDefaultPreferences(); // Set the Theme before the layout is instantiated //Utils.onActivityCreateSetTheme(this, raApp.raprefs.getSelectedTheme()); setContentView(R.layout.activity_main); // Check for first run if (raApp.isFirstRun()) { Intent i = new Intent(this, SetupWizardActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(i); finish(); } // Load any saved position int position = 0; if (savedInstanceState != null) { position = savedInstanceState.getInt(STATE_CHECKED, 0); Log.d(TAG, "Restore, position: " + position); if (position == 3) { // history fragment mHistoryContent = getSupportFragmentManager().getFragment(savedInstanceState, "HistoryGraphFragment"); } } setupToolbar(); setupNavDrawer(); updateActionBar(); selectItem(position); // launch a new thread to show the drawer on very first app launch new Thread(new Runnable() { @Override public void run() { opened = raApp.raprefs.getBoolean(OPENED_KEY, false); if (!opened) { mDrawerLayout.openDrawer(mDrawerList); } } }).start(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // get the checked item and subtract off one to get the actual position // the same logic applies that is used in the DrawerItemClickedListener.onItemClicked int position = mDrawerList.getCheckedItemPosition() - 1; outState.putInt(STATE_CHECKED, position); if (position == 3) { getSupportFragmentManager().putFragment(outState, "HistoryGraphFragment", mHistoryContent); } } @Override protected void onResume() { super.onResume(); fCanExit = false; fRestoreState = true; setNavigationList(); if (raApp.raprefs.isKeepScreenOnEnabled()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // last thing we do is display the changelog if necessary // TODO add in a preference check for displaying changelog on app startup raApp.displayChangeLog(this); } @Override protected void onPause() { super.onPause(); } private void setupToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitle(""); setSupportActionBar(mToolbar); } private void setupNavDrawer() { // get the string array for the navigation items mNavTitles = getResources().getStringArray(R.array.nav_items); // locate the navigation drawer items in the layout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer // opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // add in the logo header View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null); mDrawerList.addHeaderView(header, null, false); // set the adapter for the navigation list view ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, mNavTitles); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // setup the toggling for the drawer mDrawerToggle = new MyDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void setNavigationList() { // set list navigation items final ActionBar ab = getSupportActionBar(); Context context = ab.getThemedContext(); int arrayID; if (raApp.isAwayProfileEnabled()) { arrayID = R.array.profileLabels; } else { arrayID = R.array.profileLabelsHomeOnly; } ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, arrayID, R.layout.support_simple_spinner_dropdown_item); ab.setListNavigationCallbacks(list, this); ab.setSelectedNavigationItem(raApp.getSelectedProfile()); } private void updateActionBar() { // update actionbar final ActionBar ab = getSupportActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { // only switch profiles when the user changes the navigation item, // not when the navigation list state is restored if (!fRestoreState) { raApp.setSelectedProfile(itemPosition); } else { fRestoreState = false; } return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // sync the toggle state after onRestoreInstanceState has occurred mDrawerToggle.syncState(); } @Override public void onBackPressed() { /* When the back button is pressed, this function is called. If the drawer is open, check it and cancel it here. Calling super.onBackPressed() causes the BackStackChangeListener to be called */ // Log.d(TAG, "onBackPressed"); if (mDrawerLayout.isDrawerOpen(mDrawerList)) { // Log.d(TAG, "drawer open, closing"); mDrawerLayout.closeDrawer(mDrawerList); return; } if ( !fCanExit ) { Toast.makeText(this, R.string.messageExitNotification, Toast.LENGTH_SHORT).show(); fCanExit = true; Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { // Log.d(TAG, "Disabling exit flag"); fCanExit = false; } }, 2000); return; } super.onBackPressed(); } private void updateContent(int position) { if (position != mOldPosition) { // update the main content by replacing fragments Fragment fragment; switch (position) { default: case 0: fragment = StatusFragment.newInstance(); break; case 1: fragment = MemoryFragment.newInstance(raApp.raprefs.useOldPre10MemoryLocations()); break; case 2: fragment = NotificationsFragment.newInstance(); break; case 3: //fragment = HistoryFragment.newInstance(); // TODO check the restoration of the fragment content if (mHistoryContent != null ) { fragment = mHistoryContent; } else { // mHistoryContent = HistoryGraphFragment.newInstance(); mHistoryContent = HistoryMultipleGraphFragment.newInstance(); fragment = mHistoryContent; } break; case 4: fragment = ErrorsFragment.newInstance(); break; case 5: fragment = DateTimeFragment.newInstance(); break; } Log.d(TAG, "UpdateContent: " + position); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); mOldPosition = position; } } public void selectItem(int position) { // Log.d(TAG, "selectItem: " + position); updateContent(position); highlightItem(position); mDrawerLayout.closeDrawer(mDrawerList); } public void highlightItem(int position) { // Log.d(TAG, "highlightItem: " + position); // since we are using a header for the list, the first // item/position in the list is the header. our header is non-selectable // so in order for us to have the proper item in our list selected, we must // increase the position by 1. this same logic is applied to the // DrawerItemClickedListener.onItemClicked mDrawerList.setItemChecked(position + 1, true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.global, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // pass the event to ActionBarDrawerToggle, if it returns true, // then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // handle the rest of the action bar items here switch (item.getItemId()) { case R.id.action_settings: Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame); if (f instanceof StatusFragment) { // the current fragment is the status fragment Log.d(TAG, "Status Fragment is current"); ((StatusFragment) f).reloadPages(); } startActivity(new Intent(this, SettingsActivity.class)); // startActivityForResult(new Intent(this, SettingsActivity.class), REQUEST_EXIT); return true; default: return super.onOptionsItemSelected(item); } } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Log.d(TAG, "onActivityResult"); // if (requestCode == REQUEST_EXIT) { // if (resultCode == RESULT_EXIT) { // this.finish(); // } // } // } // called whenever we call invalidateOptionsMenu() @Override public boolean onPrepareOptionsMenu(Menu menu) { /* This function is called after invalidateOptionsMenu is called. This happens when the Navigation drawer is opened and closed. */ boolean open = mDrawerLayout.isDrawerOpen(mDrawerList); hideMenuItems(menu, open); return super.onPrepareOptionsMenu(menu); } private void hideMenuItems(Menu menu, boolean open) { // hide the menu item(s) when the drawer is open // Refresh button on Status page MenuItem mi = menu.findItem(R.id.action_refresh); if ( mi != null ) mi.setVisible(!open); // Add button on Notification page mi = menu.findItem(R.id.action_add_notification); if ( mi != null ) mi.setVisible(!open); // Delete button on Notification page mi = menu.findItem(R.id.action_delete_notification); if ( mi != null ) mi.setVisible(!open); // Delete button on Error page mi = menu.findItem(R.id.menu_delete); if ( mi != null ) mi.setVisible(!open); // hide buttons on History / Chart page mi = menu.findItem(R.id.action_configure_chart); if (mi != null) mi.setVisible(!open); mi = menu.findItem(R.id.action_refresh_chart); if (mi != null) mi.setVisible(!open); } private class MyDrawerToggle extends ActionBarDrawerToggle { public MyDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) { super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); // Log.d(TAG, "DrawerClosed"); invalidateOptionsMenu(); if (opened != null && !opened) { // drawer closed for the first time ever, // set that it has been closed opened = true; raApp.raprefs.set(OPENED_KEY, true); } } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // getSupportActionBar().setTitle(R.string.app_name); invalidateOptionsMenu(); } } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id) { // Perform action when a drawer item is selected // Log.d(TAG, "onDrawerItemClick: " + position); // when we have a list header, it counts as a position in the list // the first position to be exact. so we have to decrease the // position by 1 to get the proper item chosen in our list selectItem(position - 1); } } }
mit
tuura/workcraft
workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/commands/PetriToPolicyConversionCommand.java
1471
package org.workcraft.plugins.policy.commands; import org.workcraft.commands.AbstractConversionCommand; import org.workcraft.plugins.petri.Petri; import org.workcraft.plugins.petri.VisualPetri; import org.workcraft.plugins.policy.Policy; import org.workcraft.plugins.policy.PolicyDescriptor; import org.workcraft.plugins.policy.VisualPolicy; import org.workcraft.plugins.policy.tools.PetriToPolicyConverter; import org.workcraft.utils.Hierarchy; import org.workcraft.utils.DialogUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.WorkspaceEntry; import org.workcraft.utils.WorkspaceUtils; public class PetriToPolicyConversionCommand extends AbstractConversionCommand { @Override public String getDisplayName() { return "Policy Net"; } @Override public boolean isApplicableTo(WorkspaceEntry we) { return WorkspaceUtils.isApplicableExact(we, Petri.class); } @Override public ModelEntry convert(ModelEntry me) { if (Hierarchy.isHierarchical(me)) { DialogUtils.showError("Policy Net cannot be derived from a hierarchical Petri Net."); return null; } final VisualPetri src = me.getAs(VisualPetri.class); final VisualPolicy dst = new VisualPolicy(new Policy()); final PetriToPolicyConverter converter = new PetriToPolicyConverter(src, dst); return new ModelEntry(new PolicyDescriptor(), converter.getDstModel()); } }
mit
seph-lang/seph
src/test/seph/lang/TextTest.java
412
/* * See LICENSE file in distribution for copyright and licensing information. */ package seph.lang; import org.junit.Test; import static org.junit.Assert.*; /** * @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a> */ public class TextTest { @Test public void is_a_seph_object() { assertTrue("A Text should be a SephObject", new Text("foo") instanceof SephObject); } }// TextTest
mit
dianbaer/grain
mongodb/src/test/java/org/grain/mongo/MongodbManagerTest.java
2935
//package org.grain.mongo; // //import static org.junit.Assert.assertEquals; // //import java.util.ArrayList; //import java.util.List; //import java.util.UUID; // //import org.bson.conversions.Bson; //import org.junit.BeforeClass; //import org.junit.Test; // //import com.mongodb.client.model.Filters; // //public class MongodbManagerTest { // // @BeforeClass // public static void setUpBeforeClass() throws Exception { // MongodbManager.init("172.27.108.73", 27017, "test", "test", "test", null); // boolean result = MongodbManager.createCollection("test_table"); // if (!result) { // System.out.println("创建test_table失败"); // } // TestMongo testMongo = new TestMongo("111", "name"); // result = MongodbManager.insertOne("test_table", testMongo); // if (!result) { // System.out.println("插入TestMongo失败"); // } // } // // @Test // public void testCreateCollection() { // boolean result = MongodbManager.createCollection("test_table1"); // assertEquals(true, result); // } // // @Test // public void testInsertOne() { // TestMongo testMongo = new TestMongo(UUID.randomUUID().toString(), "name"); // boolean result = MongodbManager.insertOne("test_table", testMongo); // assertEquals(true, result); // } // // @Test // public void testInsertMany() { // TestMongo testMongo = new TestMongo(UUID.randomUUID().toString(), "name"); // TestMongo testMongo1 = new TestMongo(UUID.randomUUID().toString(), "name1"); // List<MongoObj> list = new ArrayList<>(); // list.add(testMongo); // list.add(testMongo1); // boolean result = MongodbManager.insertMany("test_table", list); // assertEquals(true, result); // } // // @Test // public void testFind() { // List<TestMongo> list = MongodbManager.find("test_table", null, TestMongo.class, 0, 0); // assertEquals(true, list.size() > 0); // } // // @Test // public void testDeleteById() { // TestMongo testMongo = new TestMongo("222", "name"); // boolean result = MongodbManager.insertOne("test_table", testMongo); // Bson filter = Filters.and(Filters.eq("id", "222")); // List<TestMongo> list = MongodbManager.find("test_table", filter, TestMongo.class, 0, 0); // testMongo = list.get(0); // result = MongodbManager.deleteById("test_table", testMongo); // assertEquals(true, result); // } // // @Test // public void testUpdateById() { // TestMongo testMongo = new TestMongo("333", "name"); // boolean result = MongodbManager.insertOne("test_table", testMongo); // Bson filter = Filters.and(Filters.eq("id", "333")); // List<TestMongo> list = MongodbManager.find("test_table", filter, TestMongo.class, 0, 0); // testMongo = list.get(0); // testMongo.setName("name" + UUID.randomUUID().toString()); // result = MongodbManager.updateById("test_table", testMongo); // assertEquals(true, result); // } // // @Test // public void testCount() { // long count = MongodbManager.count("test_table", null); // assertEquals(true, count > 0); // } // //}
mit
kkkon/job-strongauth-simple-plugin
src/main/java/org/jenkinsci/plugins/job_strongauth_simple/JobStrongAuthSimpleBuilder.java
31334
/** * The MIT License * * Copyright (C) 2012 KK.Kon * * 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.job_strongauth_simple; import hudson.Launcher; import hudson.Extension; import hudson.util.FormValidation; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.AbstractProject; import hudson.model.Cause; import hudson.model.Result; import hudson.model.Run; import hudson.model.User; import hudson.tasks.Builder; import hudson.tasks.BuildStepDescriptor; import hudson.triggers.TimerTrigger; import hudson.util.RunList; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.QueryParameter; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.logging.Logger; /** * Sample {@link Builder}. * * <p> * When the user configures the project and enables this builder, * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked * and a new {@link HelloWorldBuilder} is created. The created * instance is persisted to the project configuration XML by using * XStream, so this allows you to use instance fields (like {@link #name}) * to remember the configuration. * * <p> * When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)} * method will be invoked. * * @author KK.Kon */ public class JobStrongAuthSimpleBuilder extends Builder { // default expireTimeInHours private static final int DEFAULT_EXPIRE_TIME_IN_HOURS = 16; private Integer getEffectiveExpireTime( final Integer jobValue, final Integer globalValue ) { if ( null == jobValue && null == globalValue ) { return DEFAULT_EXPIRE_TIME_IN_HOURS; } Integer value = null; { if ( null != globalValue ) { value = globalValue; } if ( null != jobValue ) { value = jobValue; } } return value; } private Set<String> makeAuthUsers( final String jobUsers, final boolean useGlobalUsers, final String globalUsers ) { if ( null == jobUsers && null == globalUsers ) { return Collections.emptySet(); } Set<String> set = new HashSet<String>(); if ( null != jobUsers ) { final String[] users = jobUsers.split(","); if ( null != users ) { for ( final String userRaw : users ) { if ( null != userRaw ) { final String userTrimed = userRaw.trim(); if ( null != userTrimed ) { set.add( userTrimed ); } } } } } if ( useGlobalUsers ) { final String[] users = globalUsers.split(","); if ( null != users ) { for ( final String userRaw : users ) { if ( null != userRaw ) { final String userTrimed = userRaw.trim(); if ( null != userTrimed ) { set.add( userTrimed ); } } } } } return set; } private String getUserNameFromCause( final Cause cause ) { // UserCause deprecated 1.428 Class<?> clazz = null; Object retval = null; { Method method = null; try { clazz = Class.forName("hudson.model.Cause$UserIdCause"); } catch ( ClassNotFoundException e ) { } if ( null != clazz ) { try { method = cause.getClass().getMethod( "getUserName", new Class<?>[]{} ); } catch ( SecurityException e) { } catch ( NoSuchMethodException e ) { } if ( null != method ) { try { retval = method.invoke( cause, new Object[]{} ); } catch ( IllegalAccessException e ) { } catch ( IllegalArgumentException e ) { } catch ( InvocationTargetException e ) { } } } } if ( null != retval ) { if ( retval instanceof String ) { return (String)retval; } } { Method method = null; try { clazz = Class.forName("hudson.model.Cause$UserCause"); } catch ( ClassNotFoundException e ) { } if ( null != clazz ) { try { method = cause.getClass().getMethod( "getUserName", new Class<?>[]{} ); } catch ( SecurityException e) { } catch ( NoSuchMethodException e ) { } if ( null != method ) { try { retval = method.invoke( cause, new Object[]{} ); } catch ( IllegalAccessException e ) { } catch ( IllegalArgumentException e ) { } catch ( InvocationTargetException e ) { } } } } if ( null != retval ) { if ( retval instanceof String ) { return (String)retval; } } LOGGER.severe( "unknown cause" ); return null; } private Cause getCauseFromRun( final Run run ) { if ( null == run ) { return null; } Class<?> clazz = null; { try { clazz = Class.forName("hudson.model.Cause$UserIdCause"); if ( null != clazz ) { // getCause since 1.362 final Cause cause = run.getCause( clazz ); if ( null != cause ) { return cause; } } } catch ( ClassNotFoundException e ) { } } { try { clazz = Class.forName("hudson.model.Cause$UserCause"); if ( null != clazz ) { final Cause cause = run.getCause( clazz ); if ( null != cause ) { return cause; } } } catch ( ClassNotFoundException e ) { } } return null; } private final String jobUsers; private final boolean useGlobalUsers; private final Integer jobMinAuthUserNum; private final boolean useJobExpireTime; private final Integer jobExpireTimeInHours; //private final boolean buildKickByTimerTrigger; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public JobStrongAuthSimpleBuilder( final String jobUsers , final boolean useGlobalUsers , final Integer jobMinAuthUserNum , final boolean useJobExpireTime , final Integer jobExpireTimeInHours // , final boolean buildKickByTimerTrigger ) { this.jobUsers = jobUsers; this.useGlobalUsers = useGlobalUsers; this.jobMinAuthUserNum = jobMinAuthUserNum; this.useJobExpireTime = useJobExpireTime; this.jobExpireTimeInHours = jobExpireTimeInHours; //this.buildKickByTimerTrigger = buildKickByTimerTrigger; } /** * We'll use this from the <tt>config.jelly</tt>. */ public String getJobUsers() { return jobUsers; } public boolean getUseGlobalUsers() { return useGlobalUsers; } public Integer getJobMinAuthUserNum() { return jobMinAuthUserNum; } public boolean getUseJobExpireTime() { return useJobExpireTime; } public Integer getJobExpireTimeInHours() { return jobExpireTimeInHours; } // public Integer getBuildKickByTimerTrigger() { // return buildKickByTimerTrigger; // } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { // This is where you 'build' the project. final PrintStream log = listener.getLogger(); { final String jenkinsVersion = build.getHudsonVersion(); if ( 0 < "1.374".compareTo(jenkinsVersion) ) { log.println( "jenkins version old. need 1.374 over. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.FAILURE); return false; } } { final Cause cause = getCauseFromRun( build ); if ( null == cause ) { log.println( "internal error. getCauseFromRun failed. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.FAILURE); return false; } else { final String userName = getUserNameFromCause(cause); log.println( "userName=" + userName ); if ( null == userName ) { log.println( "internal error. getUserNameFromCause failed. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.FAILURE); return false; } else { if ( 0 < userName.length() ) { if ( 0 == "anonymous".compareToIgnoreCase(userName) ) { build.setResult( Result.ABORTED ); log.println( "reject `anonymous` user's build. Caused by `" + getDescriptor().getDisplayName() + "`" ); return false; } } } } } boolean currentBuildCauseByTimerTrigger = false; { final Cause cause = build.getCause(TimerTrigger.TimerTriggerCause.class); if ( null != cause ) { if ( cause instanceof TimerTrigger.TimerTriggerCause ) { final TimerTrigger.TimerTriggerCause causeTimer = (TimerTrigger.TimerTriggerCause)cause; if ( null != causeTimer ) { currentBuildCauseByTimerTrigger = true; } } } } final Calendar calStart = Calendar.getInstance(); // This also shows how you can consult the global configuration of the builder final Integer expireTimeInHours = getEffectiveExpireTime( jobExpireTimeInHours, getDescriptor().getExpireTimeInHours() ); LOGGER.finest("expireTimeInHours="+expireTimeInHours+"."); final Set<String> authUsers = makeAuthUsers( this.jobUsers, this.useGlobalUsers, getDescriptor().getUsers() ); LOGGER.finest( "authUsers=" + authUsers ); build.setResult(Result.SUCCESS); // 1.374 457315f40fb803391f5367d1ac3d50459a6f5020 RunList runList = build.getProject().getBuilds(); LOGGER.finest( "runList=" + runList ); final int currentNumber = build.getNumber(); final Set<String> listUsers = new HashSet<String>(); Calendar calLastBuild = calStart; for ( final Object r : runList ) { if ( null == r ) { continue; } if ( r instanceof Run ) { final Run run = (Run)r; LOGGER.finest("run: " + run ); /* // skip current build if ( currentNumber <= run.getNumber() ) { log.println( "skip current." ); continue; } */ final Result result = run.getResult(); LOGGER.finest( " result: " + result ); if ( Result.SUCCESS.ordinal == result.ordinal ) { if ( run.getNumber() < currentNumber ) { break; } } final Calendar calRun = run.getTimestamp(); if ( this.getUseJobExpireTime() ) { final long lDistanceInMillis = calLastBuild.getTimeInMillis() - calRun.getTimeInMillis(); final long lDistanceInSeconds = lDistanceInMillis / (1000); final long lDistanceInMinutes = lDistanceInSeconds / (60); final long lDistanceInHours = lDistanceInMinutes / (60); LOGGER.finest( " lDistanceInHours=" + lDistanceInHours ); if ( expireTimeInHours < lDistanceInHours ) { LOGGER.finest( " expireTimeInHours=" + expireTimeInHours + ",lDistanceInHours=" + lDistanceInHours ); break; } } final Cause cause = getCauseFromRun( run ); if ( null == cause ) { log.println( "internal error. getCauseFromRun failed. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.FAILURE); return false; } else { final String userName = getUserNameFromCause(cause); LOGGER.finest( " usercause:" + userName ); if ( null == userName ) { log.println( "internal error. getUserNameFromCause failed. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.FAILURE); return false; } else { if ( 0 < userName.length() ) { if ( 0 != "anonymous".compareToIgnoreCase(userName) ) { listUsers.add( userName ); if ( authUsers.contains( userName ) ) { calLastBuild = run.getTimestamp(); } } } } } } } // for RunList LOGGER.finest( "listUsers=" + listUsers ); boolean strongAuth = false; { int count = 0; for ( Iterator<String> it = listUsers.iterator(); it.hasNext(); ) { final String user = it.next(); if ( null != user ) { if ( authUsers.contains( user ) ) { count += 1; } } } LOGGER.finest( "count=" + count ); if ( null == jobMinAuthUserNum ) { final int authUserCount = authUsers.size(); LOGGER.finest( "authUserCount=" + authUserCount ); if ( authUserCount <= count ) { strongAuth = true; } } else { LOGGER.finest( "jobMinAuthUserNum=" + jobMinAuthUserNum ); if ( jobMinAuthUserNum.intValue() <= count ) { strongAuth = true; } } } if ( strongAuth ) { boolean doBuild = false; { // if ( buildKickByTimerTrigger ) // { // if ( currentBuildCauseByTimerTrigger ) // { // // no build // } // else // { // doBuild = true; // } // } // else { doBuild = true; } } if ( doBuild ) { build.setResult(Result.SUCCESS); return true; } } log.println( "stop build. number of authed people does not satisfy. Caused by `" + getDescriptor().getDisplayName() + "`" ); build.setResult(Result.NOT_BUILT); return false; } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } /** * Descriptor for {@link JobStrongAuthSimpleBuilder}. Used as a singleton. * The class is marked as public so that it can be accessed from views. * * <p> * See <tt>src/main/resources/hudson/plugins/job_strongauth_simple/JobStrongAuthSimpleBuilder/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { /** * To persist global configuration information, * simply store it in a field and call save(). * * <p> * If you don't want fields to be persisted, use <tt>transient</tt>. */ private Integer expireTimeInHours; private String users; public DescriptorImpl() { load(); { final Collection<User> userAll = User.getAll(); for ( final User user : userAll ) { LOGGER.finest( "Id: " + user.getId() ); LOGGER.finest( "DisplayName: " + user.getDisplayName() ); LOGGER.finest( "FullName: " + user.getFullName() ); } } } /** * Performs on-the-fly validation of the form field 'users'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckUsers(@QueryParameter String value) throws IOException, ServletException { if ( 0 == value.length() ) { return FormValidation.ok(); } final String invalidUser = checkUsers( value ); if ( null != invalidUser ) { return FormValidation.error("Invalid user: " + invalidUser ); } return FormValidation.ok(); } /** * Performs on-the-fly validation of the form field 'expireTimeInHours'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckExpireTimeInHours(@QueryParameter String value) throws IOException, ServletException { // if (value.length() == 0) // return FormValidation.warning("Please set expire time"); if ( 0 == value.length() ) { return FormValidation.ok(); } try { int intValue = Integer.parseInt(value); if ( intValue < 0 ) { return FormValidation.error("Please set positive value"); } } catch ( NumberFormatException e ) { return FormValidation.error("Please set numeric value"); } return FormValidation.ok(); } /** * Performs on-the-fly validation of the form field 'jobExpireTimeInHours'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckJobExpireTimeInHours(@QueryParameter String value) throws IOException, ServletException { // if (value.length() == 0) // return FormValidation.warning("Please set expire time"); if ( 0 == value.length() ) { return FormValidation.ok(); } try { int intValue = Integer.parseInt(value); if ( intValue < 0 ) { return FormValidation.error("Please set positive value"); } } catch ( NumberFormatException e ) { return FormValidation.error("Please set numeric value"); } return FormValidation.ok(); } /** * Performs on-the-fly validation of the form field 'jobUsers'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckJobUsers(@QueryParameter String value) throws IOException, ServletException { if ( 0 == value.length() ) { return FormValidation.ok(); } final String invalidUser = checkUsers( value ); if ( null != invalidUser ) { return FormValidation.error("Invalid user@job: " + invalidUser ); } return FormValidation.ok(); } /** * Performs on-the-fly validation of the form field 'jobMinAuthUserNum'. * * @param value * This parameter receives the value that the user has typed. * @return * Indicates the outcome of the validation. This is sent to the browser. */ public FormValidation doCheckJobMinAuthUserNum(@QueryParameter String value) throws IOException, ServletException { if ( 0 == value.length() ) { return FormValidation.ok(); } try { int intValue = Integer.parseInt(value); if ( intValue < 0 ) { return FormValidation.error("Please set positive value"); } } catch ( NumberFormatException e ) { return FormValidation.error("Please set numeric value"); } return FormValidation.ok(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen on job. */ public String getDisplayName() { return "StrongAuthSimple for Job"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). //expireTimeInHours = formData.getInt("expireTimeInHours"); // invoke 500 error if ( formData.containsKey("expireTimeInHours") ) { final String value = formData.getString("expireTimeInHours"); if ( null != value ) { if ( 0 < value.length() ) { try { expireTimeInHours = Integer.parseInt(value); } catch ( NumberFormatException e ) { LOGGER.warning( e.toString() ); return false; } } } } if ( formData.containsKey("users") ) { users = formData.getString("users"); } // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setUseFrench) save(); return super.configure(req,formData); } /** * This method returns true if the global configuration says we should speak French. * * The method name is bit awkward because global.jelly calls this method to determine * the initial state of the checkbox by the naming convention. */ public Integer getExpireTimeInHours() { return expireTimeInHours; } public String getUsers() { return users; } public String checkUsers( final String value ) { if ( null == value ) { return null; } final Collection<User> userAll = User.getAll(); String invalidUser = null; if ( null != userAll ) { final String[] inputUsers = value.split(","); if ( null == inputUsers ) { final String userTrimed = value.trim(); boolean validUser = false; for ( final User user : userAll ) { if ( null != user ) { final String dispName = user.getDisplayName(); if ( null != dispName ) { if ( 0 == userTrimed.compareTo(dispName) ) { validUser = true; break; } } } } // for userAll if ( validUser ) { // nothing } else { invalidUser = userTrimed; } } else { for ( final String userRaw : inputUsers ) { if ( null != userRaw ) { final String userTrimed = userRaw.trim(); boolean validUser = false; for ( final User user : userAll ) { if ( null != user ) { final String dispName = user.getDisplayName(); if ( null != dispName ) { if ( 0 == userTrimed.compareTo(dispName) ) { validUser = true; break; } } } } // for userAll if ( validUser ) { // nothing } else { invalidUser = userTrimed; } if ( null != invalidUser ) { break; } } } } } return invalidUser; } } private static final Logger LOGGER = Logger.getLogger(JobStrongAuthSimpleBuilder.class.getName()); }
mit
lutana-de/easyflickrbackup
src/main/java/de/lutana/easyflickrbackup/ImageSizes.java
2063
/* * The MIT License * * Copyright 2016 Matthias. * * 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 de.lutana.easyflickrbackup; import com.flickr4java.flickr.photos.Size; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class ImageSizes { private Map<Integer,String> suffix; public ImageSizes() { suffix = new HashMap<>(); suffix.put(Size.SQUARE, "_s"); suffix.put(Size.SQUARE_LARGE, "_q"); suffix.put(Size.THUMB, "_t"); suffix.put(Size.SMALL, "_m"); suffix.put(Size.SMALL_320, "_n"); suffix.put(Size.MEDIUM, ""); suffix.put(Size.MEDIUM_640, "_z"); suffix.put(Size.MEDIUM_800, "_c"); suffix.put(Size.LARGE, "_b"); suffix.put(Size.LARGE_1600, "_h"); suffix.put(Size.LARGE_2048, "_k"); suffix.put(Size.ORIGINAL, "_o"); } public String getSuffix(int size) { try { return suffix.get(size); } catch(Exception e) { return null; } } }
mit
pdd/mongoj
test/src/java/custom/com/example/demo/model/impl/RegisteredDriverImpl.java
2066
/** * Copyright (c) 2011 Prashant Dighe * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.example.demo.model.impl; import java.util.HashMap; import java.util.Map; import com.example.demo.model.RegisteredDriver; /** * * @author Prashant Dighe * */ public class RegisteredDriverImpl implements RegisteredDriver { public RegisteredDriverImpl() {} public RegisteredDriverImpl(Map<String, Object> map) { _name = (String)map.get("name"); _age = (Integer)map.get("age"); } @Override public String getName() { return _name; } @Override public void setName(String name) { _name = name; } @Override public int getAge() { return _age; } @Override public void setAge(int age) { _age = age; } public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", _name); map.put("age", _age); return map; } private String _name = null; private int _age = 0; private static final long serialVersionUID = 1L; }
mit
rnentjes/Simple-jdbc-statistics
test/nl/astraeus/jdbc/JdbcStatisticTest.java
246
package nl.astraeus.jdbc; import org.junit.Assert; import org.junit.Test; /** * User: rnentjes * Date: 4/13/12 * Time: 10:55 PM */ public class JdbcStatisticTest { @Test public void test() { Assert.assertTrue(true); } }
mit
samagra14/Shush
app/src/main/java/com/mdg/droiders/samagra/shush/MainActivity.java
10861
package com.mdg.droiders.samagra.shush; import android.Manifest; import android.app.NotificationManager; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.location.places.ui.PlacePicker; import com.mdg.droiders.samagra.shush.data.PlacesContract; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LoaderManager.LoaderCallbacks<Cursor>{ //constants private static final String LOG_TAG = "MainActivity"; private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111; private static final int PLACE_PICKER_REQUEST = 1; //member variables private PlaceListAdapter mAdapter; private RecyclerView mRecyclerView; private Button addPlaceButton; private GoogleApiClient mClient; private Geofencing mGeofencing; private boolean mIsEnabled; private CheckBox mRingerPermissionCheckBox; /** * Called when the activity is starting. * * @param savedInstanceState Bundle that contains the data provided to onSavedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new PlaceListAdapter(this,null); mRecyclerView.setAdapter(mAdapter); mRingerPermissionCheckBox = (CheckBox) findViewById(R.id.ringer_permissions_checkbox); mRingerPermissionCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onRingerPermissionsClicked(); } }); Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch); mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled),false); onOffSwitch.setChecked(mIsEnabled); onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(getString(R.string.setting_enabled),isChecked); editor.commit(); if (isChecked) mGeofencing.registerAllGeofences(); else mGeofencing.unRegisterAllGeofences(); } }); addPlaceButton = (Button) findViewById(R.id.add_location_button); addPlaceButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAddPlaceButtonClicked(); } }); mClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .enableAutoManage(this,this) .build(); mGeofencing = new Geofencing(mClient,this); } /** * Button click event handler for the add place button. */ private void onAddPlaceButtonClicked() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){ Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, getString(R.string.location_permissions_granted_message), Toast.LENGTH_SHORT).show(); try { PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); Intent placePickerIntent = builder.build(this); startActivityForResult(placePickerIntent,PLACE_PICKER_REQUEST); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); } } /*** * Called when the Place Picker Activity returns back with a selected place (or after canceling) * * @param requestCode The request code passed when calling startActivityForResult * @param resultCode The result code specified by the second activity * @param data The Intent that carries the result data. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode==PLACE_PICKER_REQUEST&&resultCode==RESULT_OK){ Place place = PlacePicker.getPlace(this,data); if (place==null){ Log.i(LOG_TAG,"No place selected"); return; } String placeName = place.getName().toString(); String placeAddress = place.getAddress().toString(); String placeId = place.getId(); ContentValues values = new ContentValues(); values.put(PlacesContract.PlaceEntry.COLUMN_PLACE_ID,placeId); getContentResolver().insert(PlacesContract.PlaceEntry.CONTENT_URI,values); refreshPlacesData(); } } @Override protected void onResume() { super.onResume(); //initialise location permissions checkbox CheckBox locationPermissionsCheckBox = (CheckBox) findViewById(R.id.location_permission_checkbox); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ locationPermissionsCheckBox.setChecked(false); } else { locationPermissionsCheckBox.setChecked(true); locationPermissionsCheckBox.setEnabled(false); } NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT>=24 && !notificationManager.isNotificationPolicyAccessGranted()){ mRingerPermissionCheckBox.setChecked(false); } else { mRingerPermissionCheckBox.setChecked(true); mRingerPermissionCheckBox.setEnabled(false); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Called when the google API client is successfully connected. * @param bundle Bundle of data provided to the clients by google play services. */ @Override public void onConnected(@Nullable Bundle bundle) { Log.i(LOG_TAG,"Api connection successful"); Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show(); refreshPlacesData(); } /** * Called when the google API client is suspended * @param cause The reason for the disconnection. Defined by the constant CAUSE_*. */ @Override public void onConnectionSuspended(int cause) { Log.i(LOG_TAG,"API Client connection suspended."); } /** * Called when the google API client failed to connect to the PlayServices. * @param connectionResult A coonectionResult that can be used to solve the error. */ @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.i(LOG_TAG,"API Connection client suspended."); Toast.makeText(this, "onConectionFailed", Toast.LENGTH_SHORT).show(); } public void refreshPlacesData(){ Uri uri = PlacesContract.PlaceEntry.CONTENT_URI; Cursor dataCursor = getContentResolver().query(uri, null, null, null,null,null); if (dataCursor==null||dataCursor.getCount()==0) return; List<String> placeIds = new ArrayList<String>(); while (dataCursor.moveToNext()){ placeIds.add(dataCursor.getString(dataCursor.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_PLACE_ID))); } PendingResult<PlaceBuffer> placeBufferPendingResult = Places.GeoDataApi.getPlaceById(mClient, placeIds.toArray(new String[placeIds.size()])); placeBufferPendingResult.setResultCallback(new ResultCallback<PlaceBuffer>() { @Override public void onResult(@NonNull PlaceBuffer places) { mAdapter.swapPlaces(places); mGeofencing.updateGeofencesList(places); if (mIsEnabled) mGeofencing.registerAllGeofences(); } }); } private void onRingerPermissionsClicked(){ Intent intent = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS); } startActivity(intent); } public void onLocationPermissionClicked (View view){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_FINE_LOCATION); } }
mit
martinda/http-request-plugin
src/main/java/jenkins/plugins/http_request/HttpRequest.java
15118
package jenkins.plugins.http_request; import static com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import com.cloudbees.plugins.credentials.common.AbstractIdCredentialsListBoxModel; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import com.google.common.base.Strings; import com.google.common.collect.Range; import com.google.common.collect.Ranges; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.init.InitMilestone; import hudson.init.Initializer; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Item; import hudson.model.Items; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.ListBoxModel.Option; import jenkins.plugins.http_request.auth.BasicDigestAuthentication; import jenkins.plugins.http_request.auth.FormAuthentication; import jenkins.plugins.http_request.util.HttpClientUtil; import jenkins.plugins.http_request.util.HttpRequestNameValuePair; /** * @author Janario Oliveira */ public class HttpRequest extends Builder { private @Nonnull String url; private Boolean ignoreSslErrors = DescriptorImpl.ignoreSslErrors; private HttpMode httpMode = DescriptorImpl.httpMode; private String httpProxy = DescriptorImpl.httpProxy; private Boolean passBuildParameters = DescriptorImpl.passBuildParameters; private String validResponseCodes = DescriptorImpl.validResponseCodes; private String validResponseContent = DescriptorImpl.validResponseContent; private MimeType acceptType = DescriptorImpl.acceptType; private MimeType contentType = DescriptorImpl.contentType; private String outputFile = DescriptorImpl.outputFile; private Integer timeout = DescriptorImpl.timeout; private Boolean consoleLogResponseBody = DescriptorImpl.consoleLogResponseBody; private Boolean quiet = DescriptorImpl.quiet; private String authentication = DescriptorImpl.authentication; private String requestBody = DescriptorImpl.requestBody; private List<HttpRequestNameValuePair> customHeaders = DescriptorImpl.customHeaders; @DataBoundConstructor public HttpRequest(@Nonnull String url) { this.url = url; } @Nonnull public String getUrl() { return url; } public Boolean getIgnoreSslErrors() { return ignoreSslErrors; } @DataBoundSetter public void setIgnoreSslErrors(Boolean ignoreSslErrors) { this.ignoreSslErrors = ignoreSslErrors; } public HttpMode getHttpMode() { return httpMode; } @DataBoundSetter public void setHttpMode(HttpMode httpMode) { this.httpMode = httpMode; } public String getHttpProxy() { return httpProxy; } @DataBoundSetter public void setHttpProxy(String httpProxy) { this.httpProxy = httpProxy; } public Boolean getPassBuildParameters() { return passBuildParameters; } @DataBoundSetter public void setPassBuildParameters(Boolean passBuildParameters) { this.passBuildParameters = passBuildParameters; } @Nonnull public String getValidResponseCodes() { return validResponseCodes; } @DataBoundSetter public void setValidResponseCodes(String validResponseCodes) { this.validResponseCodes = validResponseCodes; } public String getValidResponseContent() { return validResponseContent; } @DataBoundSetter public void setValidResponseContent(String validResponseContent) { this.validResponseContent = validResponseContent; } public MimeType getAcceptType() { return acceptType; } @DataBoundSetter public void setAcceptType(MimeType acceptType) { this.acceptType = acceptType; } public MimeType getContentType() { return contentType; } @DataBoundSetter public void setContentType(MimeType contentType) { this.contentType = contentType; } public String getOutputFile() { return outputFile; } @DataBoundSetter public void setOutputFile(String outputFile) { this.outputFile = outputFile; } public Integer getTimeout() { return timeout; } @DataBoundSetter public void setTimeout(Integer timeout) { this.timeout = timeout; } public Boolean getConsoleLogResponseBody() { return consoleLogResponseBody; } @DataBoundSetter public void setConsoleLogResponseBody(Boolean consoleLogResponseBody) { this.consoleLogResponseBody = consoleLogResponseBody; } public Boolean getQuiet() { return quiet; } @DataBoundSetter public void setQuiet(Boolean quiet) { this.quiet = quiet; } public String getAuthentication() { return authentication; } @DataBoundSetter public void setAuthentication(String authentication) { this.authentication = authentication; } public String getRequestBody() { return requestBody; } @DataBoundSetter public void setRequestBody(String requestBody) { this.requestBody = requestBody; } public List<HttpRequestNameValuePair> getCustomHeaders() { return customHeaders; } @DataBoundSetter public void setCustomHeaders(List<HttpRequestNameValuePair> customHeaders) { this.customHeaders = customHeaders; } @Initializer(before = InitMilestone.PLUGINS_STARTED) public static void xStreamCompatibility() { Items.XSTREAM2.aliasField("logResponseBody", HttpRequest.class, "consoleLogResponseBody"); Items.XSTREAM2.aliasField("consoleLogResponseBody", HttpRequest.class, "consoleLogResponseBody"); Items.XSTREAM2.alias("pair", HttpRequestNameValuePair.class); } protected Object readResolve() { if (customHeaders == null) { customHeaders = DescriptorImpl.customHeaders; } if (validResponseCodes == null || validResponseCodes.trim().isEmpty()) { validResponseCodes = DescriptorImpl.validResponseCodes; } if (ignoreSslErrors == null) { //default for new job false(DescriptorImpl.ignoreSslErrors) for old ones true to keep same behavior ignoreSslErrors = true; } if (quiet == null) { quiet = false; } return this; } private List<HttpRequestNameValuePair> createParams(EnvVars envVars, AbstractBuild<?, ?> build, TaskListener listener) throws IOException { Map<String, String> buildVariables = build.getBuildVariables(); if (buildVariables.isEmpty()) { return Collections.emptyList(); } PrintStream logger = listener.getLogger(); logger.println("Parameters: "); List<HttpRequestNameValuePair> l = new ArrayList<>(); for (Map.Entry<String, String> entry : buildVariables.entrySet()) { String value = envVars.expand(entry.getValue()); logger.println(" " + entry.getKey() + " = " + value); l.add(new HttpRequestNameValuePair(entry.getKey(), value)); } return l; } String resolveUrl(EnvVars envVars, AbstractBuild<?, ?> build, TaskListener listener) throws IOException { String url = envVars.expand(getUrl()); if (Boolean.TRUE.equals(getPassBuildParameters()) && getHttpMode() == HttpMode.GET) { List<HttpRequestNameValuePair> params = createParams(envVars, build, listener); if (!params.isEmpty()) { url = HttpClientUtil.appendParamsToUrl(url, params); } } return url; } List<HttpRequestNameValuePair> resolveHeaders(EnvVars envVars) { final List<HttpRequestNameValuePair> headers = new ArrayList<>(); if (contentType != null && contentType != MimeType.NOT_SET) { headers.add(new HttpRequestNameValuePair("Content-type", contentType.getContentType().toString())); } if (acceptType != null && acceptType != MimeType.NOT_SET) { headers.add(new HttpRequestNameValuePair("Accept", acceptType.getValue())); } for (HttpRequestNameValuePair header : customHeaders) { String headerName = envVars.expand(header.getName()); String headerValue = envVars.expand(header.getValue()); boolean maskValue = headerName.equalsIgnoreCase("Authorization") || header.getMaskValue(); headers.add(new HttpRequestNameValuePair(headerName, headerValue, maskValue)); } return headers; } String resolveBody(EnvVars envVars, AbstractBuild<?, ?> build, TaskListener listener) throws IOException { String body = envVars.expand(getRequestBody()); if (Strings.isNullOrEmpty(body) && Boolean.TRUE.equals(getPassBuildParameters())) { List<HttpRequestNameValuePair> params = createParams(envVars, build, listener); if (!params.isEmpty()) { body = HttpClientUtil.paramsToString(params); } } return body; } FilePath resolveOutputFile(EnvVars envVars, AbstractBuild<?,?> build) { if (outputFile == null || outputFile.trim().isEmpty()) { return null; } String filePath = envVars.expand(outputFile); FilePath workspace = build.getWorkspace(); if (workspace == null) { throw new IllegalStateException("Could not find workspace to save file outputFile: " + outputFile); } return workspace.child(filePath); } @Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { EnvVars envVars = build.getEnvironment(listener); for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) { envVars.put(e.getKey(), e.getValue()); } HttpRequestExecution exec = HttpRequestExecution.from(this, envVars, build, this.getQuiet() ? TaskListener.NULL : listener); launcher.getChannel().call(exec); return true; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public static final boolean ignoreSslErrors = false; public static final HttpMode httpMode = HttpMode.GET; public static final String httpProxy = ""; public static final Boolean passBuildParameters = false; public static final String validResponseCodes = "100:399"; public static final String validResponseContent = ""; public static final MimeType acceptType = MimeType.NOT_SET; public static final MimeType contentType = MimeType.NOT_SET; public static final String outputFile = ""; public static final int timeout = 0; public static final Boolean consoleLogResponseBody = false; public static final Boolean quiet = false; public static final String authentication = ""; public static final String requestBody = ""; public static final List <HttpRequestNameValuePair> customHeaders = Collections.<HttpRequestNameValuePair>emptyList(); public DescriptorImpl() { load(); } @SuppressWarnings("rawtypes") @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } @Override public String getDisplayName() { return "HTTP Request"; } public ListBoxModel doFillHttpModeItems() { return HttpMode.getFillItems(); } public ListBoxModel doFillAcceptTypeItems() { return MimeType.getContentTypeFillItems(); } public ListBoxModel doFillContentTypeItems() { return MimeType.getContentTypeFillItems(); } public ListBoxModel doFillAuthenticationItems(@AncestorInPath Item project, @QueryParameter String url) { return fillAuthenticationItems(project, url); } public static ListBoxModel fillAuthenticationItems(Item project, String url) { if (project == null || !project.hasPermission(Item.CONFIGURE)) { return new StandardListBoxModel(); } List<Option> options = new ArrayList<>(); for (BasicDigestAuthentication basic : HttpRequestGlobalConfig.get().getBasicDigestAuthentications()) { options.add(new Option("(deprecated - use Jenkins Credentials) " + basic.getKeyName(), basic.getKeyName())); } for (FormAuthentication formAuthentication : HttpRequestGlobalConfig.get().getFormAuthentications()) { options.add(new Option(formAuthentication.getKeyName())); } AbstractIdCredentialsListBoxModel<StandardListBoxModel, StandardCredentials> items = new StandardListBoxModel() .includeEmptyValue() .includeAs(ACL.SYSTEM, project, StandardUsernamePasswordCredentials.class, URIRequirementBuilder.fromUri(url).build()); items.addMissing(options); return items; } public static List<Range<Integer>> parseToRange(String value) { List<Range<Integer>> validRanges = new ArrayList<Range<Integer>>(); String[] codes = value.split(","); for (String code : codes) { String[] fromTo = code.trim().split(":"); checkArgument(fromTo.length <= 2, "Code %s should be an interval from:to or a single value", code); Integer from; try { from = Integer.parseInt(fromTo[0]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Invalid number "+fromTo[0]); } Integer to = from; if (fromTo.length != 1) { try { to = Integer.parseInt(fromTo[1]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Invalid number "+fromTo[1]); } } checkArgument(from <= to, "Interval %s should be FROM less than TO", code); validRanges.add(Ranges.closed(from, to)); } return validRanges; } public FormValidation doCheckValidResponseCodes(@QueryParameter String value) { return checkValidResponseCodes(value); } public static FormValidation checkValidResponseCodes(String value) { if (value == null || value.trim().isEmpty()) { return FormValidation.ok(); } try { parseToRange(value); } catch (IllegalArgumentException iae) { return FormValidation.error("Response codes expected is wrong. "+iae.getMessage()); } return FormValidation.ok(); } } }
mit
VerkhovtsovPavel/BSUIR_Labs
Labs/ADB/ADB-2/src/by/bsuir/verkpavel/adb/data/DataProvider.java
4665
package by.bsuir.verkpavel.adb.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import by.bsuir.verkpavel.adb.data.entity.Account; import by.bsuir.verkpavel.adb.data.entity.Client; import by.bsuir.verkpavel.adb.data.entity.Deposit; import by.bsuir.verkpavel.adb.data.entity.TransactionsInfo; //MAYBE Remove this facade and use separate class or add three getInstance methods public class DataProvider { private static DataProvider instance; private Connection connection; private ClientProvider clientProvider; private DepositProvider depositProvider; private AccountProvider accountProvider; private static final String DB_PATH = "jdbc:mysql://localhost:3306/bank_users?useUnicode=true&characterEncoding=utf8"; private static final String DB_USER_NAME = "root"; private static final String DB_PASSWORD = "123456"; private DataProvider() { try { Class.forName("com.mysql.jdbc.Driver"); this.connection = DriverManager.getConnection(DB_PATH, DB_USER_NAME, DB_PASSWORD); this.clientProvider = ClientProvider.getInstance(connection); this.depositProvider = DepositProvider.getInstance(connection); this.accountProvider = AccountProvider.getInstance(connection); } catch (ClassNotFoundException e) { System.out.println("DB driver not found"); e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }; public static DataProvider getInstance() { if (instance == null) { instance = new DataProvider(); } return instance; } public ArrayList<String> getCityList() { return clientProvider.getCityList(); } public ArrayList<String> getFamilyStatuses() { return clientProvider.getFamilyStatuses(); } public ArrayList<String> getNationalitys() { return clientProvider.getNationalitys(); } public ArrayList<String> getDisabilitys() { return clientProvider.getDisabilitys(); } public String saveClient(Client client) { return clientProvider.saveClient(client); } public String updateClient(Client client) { return clientProvider.updateClient(client); } public ArrayList<Client> getAllClients() { return clientProvider.getAllClients(); } public void deleteClient(Client client) { clientProvider.deleteClient(client); } public ArrayList<String> getUserFullNames() { return clientProvider.getUserFullNames(); } public ArrayList<String> getCurrency() { return depositProvider.getCurrency(); } public ArrayList<String> getDepositTypeList() { return depositProvider.getDepositTypeList(); } public String saveDeposit(Deposit deposit) { return depositProvider.saveDeposit(deposit); } public ArrayList<Deposit> getAllDeposits() { return depositProvider.getAllDeposits(); } public void updateDepositEndDate(Deposit deposit, String newDate) { depositProvider.updateDepositEndDate(deposit, newDate); } public ArrayList<Account> getAllAccounts() { return accountProvider.getAllAccounts(); } public void addTransaction(Account from, Account to, double sum, int currency) { try { accountProvider.addTransaction(from, to, sum, currency); } catch (SQLException e) { e.printStackTrace(); } } public void addMonoTransaction(Account from, Account to, double sum, int currency) { try { accountProvider.addMonoTransaction(from, to, sum, currency); } catch (SQLException e) { e.printStackTrace(); } } public Account[] getAccountByDeposit(Deposit deposit) { return accountProvider.getAccountByDeposit(deposit); } public Account getCashBoxAccount() { return accountProvider.getCashBoxAccount(); } public void createAccountsByDeposit(Deposit deposit) { accountProvider.createAccountByDeposit(deposit); } public Account getFDBAccount() { return accountProvider.getFDBAccount(); } public ArrayList<TransactionsInfo> getTransatcionsByAccount(Account account) { return accountProvider.getTransactionByAccount(account); } public ArrayList<Deposit> getAllActiveDeposits() { return depositProvider.getAllActiveDeposits(); } public void disableDeposit(Deposit deposit) { depositProvider.disableDeposit(deposit); } }
mit
Sonnydch/dzwfinal
AndroidFinal/engine/src/main/java/com/lfk/justweengine/Utils/tools/SpUtils.java
8126
package com.lfk.justweengine.Utils.tools; import android.content.Context; import android.content.SharedPreferences; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * 简化Sp存储的工具类 * * @author liufengkai */ public class SpUtils { public SpUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * Sp文件名 */ public static final String FILE_NAME = "share_data"; /** * 保存数据的方法,添加具体数据类型 * * @param context * @param key * @param object */ public static void put(Context context, String key, Object object) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); // 判断数据类型 if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, object.toString()); } SharedPreferencesCompat.apply(editor); } /** * 获取保存数据的方法,添加具体数据类型 * * @param context * @param key * @param defaultObject * @return object */ public static Object get(Context context, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } return null; } /** * 存放数组 * * @param context * @param list * @param key */ public static void putList(Context context, List list, String key) { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < list.size(); i++) { JSONObject object = new JSONObject(); try { object.put(i + "", list.get(i)); jsonArray.put(object); } catch (JSONException e) { e.printStackTrace(); } } put(context, key, jsonArray.toString()); } /** * 获取数组 * * @param context * @param key * @return list */ public static List getList(Context context, String key) { List list = new ArrayList(); try { JSONArray jsonArray = new JSONArray((String) get(context, key, "")); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); list.add(i, object.getString(i + "")); } } catch (JSONException e) { e.printStackTrace(); } return list; } /** * 存入哈希表 * * @param context * @param map * @param key */ public static void putMap(Context context, Map<?, ?> map, String key) { JSONArray jsonArray = new JSONArray(); Set set = map.entrySet(); Iterator iterator = set.iterator(); for (int i = 0; i < map.size(); i++) { Map.Entry mapEntry = (Map.Entry) iterator.next(); try { JSONObject object = new JSONObject(); object.put("key", mapEntry.getKey()); object.put("value", mapEntry.getValue()); jsonArray.put(object); } catch (JSONException e) { e.printStackTrace(); } } put(context, key, jsonArray.toString()); } /** * 读取哈希表 * * @param context * @param key * @return map */ public static Map getMap(Context context, String key) { Map map = new HashMap(); try { JSONArray jsonArray = new JSONArray((String) get(context, key, "")); for (int i = 0; i < jsonArray.length(); i++) { try { JSONObject object = jsonArray.getJSONObject(i); map.put(object.getString("key"), object.getString("value")); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } return map; } /** * 移除某个key值已经对应的值 * * @param context * @param key */ public static void remove(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); } /** * 清除所有数据 * * @param context */ public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); } /** * 查询某个key是否存在 * * @param context * @param key * @return */ public static boolean contains(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.contains(key); } /** * 返回所有的键值对 * * @param context * @return map */ public static Map<String, ?> getAll(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.getAll(); } /** * 解决SharedPreferencesCompat.apply方法的兼容类 * * @author liufengkai */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 * * @return method */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Method findApplyMethod() { try { Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } /** * 如果找到则使用apply执行,否则使用commit * * @param editor */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } editor.commit(); } } }
mit
joseflamas/zet
variaciones/antesFestival/ANTES01/build-tmp/source/ANTES01.java
11561
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import ddf.minim.spi.*; import ddf.minim.signals.*; import ddf.minim.*; import ddf.minim.analysis.*; import ddf.minim.ugens.*; import ddf.minim.effects.*; import codeanticode.syphon.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class ANTES01 extends PApplet { // ////////// // // WRAP // Syphon/minim/fun000 // // V.00 paraelfestival"ANTES" // feelGoodSoftwareporGuillermoGonz\u00e1lezIrigoyen // ////////// // //VARIABLES DE CONFIGURACI\u00d3N //Tama\u00f1o de la pantalla , proporciones y tweak boolean pCompleta = false; //salidas a proyector 1024X768 boolean pCambiable= true; int pPantalla = 4; int pP,pW,pH; //Syphon SyphonServer server; String nombreServer = "ANTES01"; //Audio Minim minim; AudioInput in0; // // ... //LINEA Linea lin,lin1; int[] coloresAntes = { 0xff2693FF, 0xffEF3B63 , 0xffFFFFFB, 0xff000000}; int numColor = 1; boolean hay; int alfa = 255; boolean moverL = false; boolean moverH = false; int xIL = 0; int yIL = 10; int intA = 50; int sepLR = 5; int anchoL = 0; int anchoR = 0; int anchoS = 1; int distMov = 1; //FONDO boolean fondo = true; boolean textura = true; boolean sinCuadricula = true; int R = 85; int G = 85; int B = 85; int A = 10; //CONTROLES boolean sumar = true; int paso = 2; //##SETUP## // public void setup() { //CANVAS pP = (pCompleta == true)? 1 : pPantalla; size(displayWidth/pP, displayHeight/pP, P3D); pW=width;pH=height; frame.setResizable(pCambiable); //SYPHON SERVER server = new SyphonServer(this, nombreServer); //AUDIO minim = new Minim(this); in0 = minim.getLineIn(); // // ... yIL = height/2; lin = new Linea(xIL, yIL, coloresAntes[numColor], alfa); lin1 = new Linea(xIL, yIL-50, coloresAntes[numColor+1], alfa); } //##DRAW## // public void draw() { pW=width; pH=height; if(fondo){ background(coloresAntes[2]); } int normi; pushMatrix(); for(int i = 0; i < pW; i++) { normi=i; if(i>1024||i==1024){ normi = PApplet.parseInt(norm(i,0,1024)); } lin.conectarHorizontal(i, normi, intA, sepLR, anchoL, anchoR, anchoS, coloresAntes[numColor], alfa); } if(moverL==true){ lin.moverVertical(moverL, distMov, moverH); lin1.moverVertical(moverL, distMov, moverH); } popMatrix(); //fondo if(textura){ pushMatrix(); fondodePapel(R,G,B,A,sinCuadricula); popMatrix(); } //SYPHON SERVER server.sendScreen(); } // //##CONTROLES## // public void keyPressed() { char k = key; switch(k) { //////////////////////////////////////////// //////////////////////////////////////////// //controles// case '<': sumar = !sumar; print("sumar :",sumar,"\n"); print("paso :",paso,"\n"); print("___________________\n"); break; case '0': break; case '1': fondo=!fondo; print("fondo :",fondo,"\n"); print("___________________\n"); break; case '2': sinCuadricula=!sinCuadricula; print("sinCuadricula :",sinCuadricula,"\n"); print("___________________\n"); break; case '3': textura=!textura; print("textura :",textura,"\n"); print("___________________\n"); break; case 'z': paso--; paso = (paso>255)?255:paso; paso = (paso<0)?0:paso; print("paso :",paso,"\n"); print("___________________\n"); break; case 'x': paso++; paso = (paso>255)?255:paso; paso = (paso<0)?0:paso; print("paso :",paso,"\n"); print("___________________\n"); break; //////////////////////////////////////////// //////////////////////////////////////////// //fondo// case 'q': if(sumar==true) { R+=paso; R = (R>255)?255:R; R = (R<0)?0:R; } else { R-=paso; R = (R>255)?255:R; R = (R<0)?0:R; } print("Rojo :",R,"\n"); print("___________________\n"); break; case 'w': if(sumar==true) { G+=paso; G = (G>255)?255:G; G = (G<0)?0:G; } else { G-=paso; G = (G>255)?255:G; G = (G<0)?0:G; } print("Verde :",G,"\n"); print("___________________\n"); break; case 'e': if(sumar==true) { B+=paso; B = (B>255)?255:B; B = (B<0)?0:B; } else { B-=paso; B = (B>255)?255:B; B = (B<0)?0:B; } print("Azul :",B,"\n"); print("___________________\n"); break; case 'a': if(sumar==true) { A+=paso; A = (A>255)?255:A; A = (A<0)?0:A; } else { A-=paso; A = (A>255)?255:A; A = (A<0)?0:A; } print("Grano Papel :",A,"\n"); print("___________________\n"); break; case 's': break; //////////////////////////////////////////// //////////////////////////////////////////// //Linea// case 'r': numColor+=1; hay = (numColor > coloresAntes.length || numColor == coloresAntes.length)? false : true; numColor = (hay)? numColor : 0; print("numColor :",numColor,"\n"); print("___________________\n"); break; case 't': if(sumar==true) { anchoL+=paso; anchoL = (anchoL>1000)?1000:anchoL; anchoL = (anchoL<0)?0:anchoL; } else { anchoL-=paso; anchoL = (anchoL>1000)?1000:anchoL; anchoL = (anchoL<0)?0:anchoL; } print("Ancho canal izquierdo :",anchoL,"\n"); print("___________________\n"); break; case 'y': if(sumar==true) { anchoR+=paso; anchoR = (anchoR>1000)?1000:anchoR; anchoR = (anchoR<0)?0:anchoR; } else { anchoR-=paso; anchoR = (anchoR>1000)?1000:anchoR; anchoR = (anchoR<0)?0:anchoR; } print("Ancho canal derecho :",anchoR,"\n"); print("___________________\n"); break; case 'f': moverL = !moverL; print("Mover Linea :",moverL,"\n"); print("___________________\n"); break; case 'g': moverH = !moverH; print("Mover distancia horizontal :",moverH,"\n"); print("___________________\n"); break; case 'h': if(sumar==true) { sepLR+=paso; sepLR = (anchoR>1000)?1000:sepLR; sepLR = (anchoR<0)?0:sepLR; } else { sepLR-=paso; sepLR = (anchoR>1000)?1000:sepLR; sepLR = (anchoR<0)?10:anchoR; } print("Separaci\u00f3n canales :",sepLR,"\n"); print("___________________\n"); break; case 'v': if(sumar==true) { intA+=paso; intA = (intA>1000)?1000:intA; intA = (intA<0)?0:intA; } else { intA-=paso; intA = (intA>1000)?1000:intA; intA = (intA<0)?0:intA; } print("intencidad respuesta input :",intA,"\n"); print("___________________\n"); break; case 'b': if(sumar==true) { distMov+=paso; distMov = (distMov>1000)?1000:distMov; distMov = (distMov<0)?0:distMov; } else { distMov-=paso; distMov = (distMov>1000)?1000:distMov; distMov = (distMov<0)?0:distMov; } print("distMov :",distMov,"\n"); print("___________________\n"); break; case 'n': if(sumar==true) { anchoS+=paso; anchoS = (anchoS>1000)?1000:anchoS; anchoS = (anchoS<0)?0:anchoS; } else { anchoS-=paso; anchoS = (anchoS>1000)?1000:anchoS; anchoS = (anchoS<0)?0:anchoS; } print("distMov :",anchoS,"\n"); print("___________________\n"); break; //////////////////////////////////////////// //////////////////////////////////////////// //RESETS 7 8 9// case '9': numColor = 1; alfa = 255; moverL = false; moverH = false; xIL = 0; yIL = 10; intA = 50; sepLR = 5; anchoL = 0; anchoR = 0; anchoS = 1; distMov = 1; fondo = true; textura = true; sinCuadricula = true; R = 85; G = 85; B = 85; A = 10; break; case '8': numColor = 1; alfa = 255; moverL = false; moverH = false; xIL = 0; yIL = 10; intA = 50; sepLR = 5; anchoL = 0; anchoR = 0; anchoS = 1; distMov = 1; break; case '7': fondo = false; textura = true; sinCuadricula = true; R = 85; G = 85; B = 85; A = 10; break; // //DEFAULT default: break; } } // //##FONDO // public void fondodePapel(int R, int G, int B, int A, boolean sinCuadricula) { if(sinCuadricula){ noStroke(); } for (int i = 0; i<width; i+=2) { for (int j = 0; j<height; j+=2) { fill(random(R-10, R+10),random(G-10, G+10),random(B-10, B+10), random(A*2.5f,A*3)); rect(i, j, 2, 2); } } for (int i = 0; i<30; i++) { fill(random(R/2, R+R/2), random(A*2.5f, A*3)); rect(random(0, width-2), random(0, height-2), random(1, 3), random(1, 3)); } } // //##OVER## // public boolean sketchFullScreen() { return pCompleta; } class Linea { int x, y, largo, colorLinea, a; Linea(int X, int Y, int COLORLINEA, int A) { x=X; y=Y; colorLinea=COLORLINEA; a=A; } public void conectarHorizontal(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A) { stroke(COLORLINEA, A); strokeWeight(GROSLIN); line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1); line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I+1); } public void conectarVertical(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A) { stroke(COLORLINEA, A); strokeWeight(GROSLIN); line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1); line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I+1, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I); } public void moverVertical(boolean MOVER, int CUANTO, boolean WIDTH) { if(MOVER == true) { y+=CUANTO; int distancia = (WIDTH == true) ? width : height; if(y>distancia) { y=0; } } } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "ANTES01" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
mit
Stephen-Cameron-Data-Services/isis-agri
dom/src/main/java/au/com/scds/agric/dom/simple/SimpleObjectRepository.java
2086
/* * 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 au.com.scds.agric.dom.simple; import java.util.List; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.query.QueryDefault; import org.apache.isis.applib.services.registry.ServiceRegistry2; import org.apache.isis.applib.services.repository.RepositoryService; @DomainService( nature = NatureOfService.DOMAIN, repositoryFor = SimpleObject.class ) public class SimpleObjectRepository { public List<SimpleObject> listAll() { return repositoryService.allInstances(SimpleObject.class); } public List<SimpleObject> findByName(final String name) { return repositoryService.allMatches( new QueryDefault<>( SimpleObject.class, "findByName", "name", name)); } public SimpleObject create(final String name) { final SimpleObject object = new SimpleObject(name); serviceRegistry.injectServicesInto(object); repositoryService.persist(object); return object; } @javax.inject.Inject RepositoryService repositoryService; @javax.inject.Inject ServiceRegistry2 serviceRegistry; }
mit
Sarwat/GeoSpark
viz/src/main/java/org/datasyslab/geosparkviz/utils/S3Operator.java
3664
/* * FILE: S3Operator * Copyright (c) 2015 - 2019 GeoSpark Development Team * * 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.datasyslab.geosparkviz.utils; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3Object; import org.apache.log4j.Logger; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class S3Operator { private AmazonS3 s3client; public final static Logger logger = Logger.getLogger(S3Operator.class); public S3Operator(String regionName, String accessKey, String secretKey) { Regions region = Regions.fromName(regionName); BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey); s3client = AmazonS3ClientBuilder.standard().withRegion(region).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build(); logger.info("[GeoSparkViz][Constructor] Initialized a S3 client"); } public boolean createBucket(String bucketName) { Bucket bucket = s3client.createBucket(bucketName); logger.info("[GeoSparkViz][createBucket] Created a bucket: " + bucket.toString()); return true; } public boolean deleteImage(String bucketName, String path) { s3client.deleteObject(bucketName, path); logger.info("[GeoSparkViz][deleteImage] Deleted an image if exist"); return true; } public boolean putImage(String bucketName, String path, BufferedImage rasterImage) throws IOException { deleteImage(bucketName, path); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(rasterImage, "png", outputStream); byte[] buffer = outputStream.toByteArray(); InputStream inputStream = new ByteArrayInputStream(buffer); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(buffer.length); s3client.putObject(new PutObjectRequest(bucketName, path, inputStream, metadata)); inputStream.close(); outputStream.close(); logger.info("[GeoSparkViz][putImage] Put an image"); return true; } public BufferedImage getImage(String bucketName, String path) throws Exception { logger.debug("[GeoSparkViz][getImage] Start"); S3Object s3Object = s3client.getObject(bucketName, path); InputStream inputStream = s3Object.getObjectContent(); BufferedImage rasterImage = ImageIO.read(inputStream); inputStream.close(); s3Object.close(); logger.info("[GeoSparkViz][getImage] Got an image"); return rasterImage; } }
mit
pttravis/ds-armor
src/pttravis/ScoreElementalDef.java
726
package pttravis; import java.util.List; public class ScoreElementalDef implements ScoreItems { public ScoreElementalDef() { } @Override public String getName() { return "Elemental Def"; } @Override public float score(List<Item> items) { if( items == null ) return 0; float score = 0; for( Item item : items ){ if( item != null){ score += item.getFire() + item.getLightning() + item.getMagic(); } } return score; } @Override public float score(Item[] items) { if( items == null || items.length < 6 ) return 0; float score = 0; for( Item item : items ){ if( item != null){ score += item.getFire() + item.getLightning() + item.getMagic(); } } return score; } }
mit
ZornTaov/ReploidCraft
src/main/java/zornco/reploidcraft/network/MessageRideArmor.java
2840
package zornco.reploidcraft.network; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; import zornco.reploidcraft.ReploidCraft; import zornco.reploidcraft.entities.EntityRideArmor; import zornco.reploidcraft.utils.RiderState; import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; public class MessageRideArmor implements IMessage, IMessageHandler<MessageRideArmor, IMessage> { public float moveForward = 0.0F; public float moveStrafe = 0.0F; public boolean jump = false; public boolean sneak = false; public boolean dash = false; public boolean punch = false; public int ID = 0; public int dimension = 0; public MessageRideArmor() {} public MessageRideArmor(EntityRideArmor rideArmor, Entity entity) { if(rideArmor != null && entity != null){ RiderState rs = ReploidCraft.proxy.getRiderState(entity); if (null != rs) { moveStrafe = rs.getMoveStrafe(); moveForward = rs.getMoveForward(); jump = rs.isJump(); sneak = rs.isSneak(); } ID = rideArmor.getEntityId(); dimension = rideArmor.dimension; } } @Override public IMessage onMessage(MessageRideArmor message, MessageContext ctx) { RiderState rs = new RiderState(); rs.setMoveForward(message.moveForward); rs.setMoveStrafe(message.moveStrafe); rs.setJump(message.jump); rs.setSneak(message.sneak); Entity armor = getEntityByID(message.ID, message.dimension); if( armor != null && armor instanceof EntityRideArmor) { ((EntityRideArmor)armor).setRiderState(rs); } return null; } @Override public void fromBytes(ByteBuf buf) { moveForward = buf.readFloat(); moveStrafe = buf.readFloat(); jump = buf.readBoolean(); sneak = buf.readBoolean(); dash = buf.readBoolean(); punch = buf.readBoolean(); ID = buf.readInt(); dimension = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeFloat(moveForward); buf.writeFloat(moveStrafe); buf.writeBoolean(jump); buf.writeBoolean(sneak); buf.writeBoolean(dash); buf.writeBoolean(punch); buf.writeInt(ID); buf.writeInt(dimension); } public Entity getEntityByID(int entityId, int dimension) { Entity targetEntity = null; if (Side.SERVER == FMLCommonHandler.instance().getEffectiveSide()) { WorldServer worldserver = MinecraftServer.getServer().worldServerForDimension(dimension); targetEntity = worldserver.getEntityByID(entityId); } if ((null != targetEntity) && ((targetEntity instanceof EntityRideArmor))) { return (EntityRideArmor)targetEntity; } return null; } }
mit
bati11/otameshi-webapp
spring4+dbflute/src/main/java/info/bati11/otameshi/dbflute/allcommon/ImplementedCommonColumnAutoSetupper.java
1934
package info.bati11.otameshi.dbflute.allcommon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.dbflute.Entity; import org.dbflute.hook.CommonColumnAutoSetupper; /** * The basic implementation of the auto set-upper of common column. * @author DBFlute(AutoGenerator) */ public class ImplementedCommonColumnAutoSetupper implements CommonColumnAutoSetupper { // ===================================================================================== // Definition // ========== /** The logger instance for this class. (NotNull) */ private static final Logger _log = LoggerFactory.getLogger(ImplementedCommonColumnAutoSetupper.class); // ===================================================================================== // Set up // ====== /** {@inheritDoc} */ public void handleCommonColumnOfInsertIfNeeds(Entity targetEntity) { } /** {@inheritDoc} */ public void handleCommonColumnOfUpdateIfNeeds(Entity targetEntity) { } // ===================================================================================== // Logging // ======= protected boolean isInternalDebugEnabled() { return DBFluteConfig.getInstance().isInternalDebug() && _log.isDebugEnabled(); } protected void logSettingUp(EntityDefinedCommonColumn entity, String keyword) { _log.debug("...Setting up column columns of " + entity.asTableDbName() + " before " + keyword); } }
mit
sodash/open-code
winterwell.depot/test/com/winterwell/depot/ESStoreTest.java
1093
package com.winterwell.depot; import java.util.Map; import org.junit.Test; import com.winterwell.depot.merge.Merger; import com.winterwell.es.client.ESConfig; import com.winterwell.es.client.ESHttpClient; import com.winterwell.gson.FlexiGson; import com.winterwell.utils.Dep; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.ArrayMap; public class ESStoreTest { @Test public void testSimple() { Dep.setIfAbsent(FlexiGson.class, new FlexiGson()); Dep.setIfAbsent(Merger.class, new Merger()); Dep.setIfAbsent(ESConfig.class, new ESConfig()); ESConfig esconfig = Dep.get(ESConfig.class); if ( ! Dep.has(ESHttpClient.class)) Dep.setSupplier(ESHttpClient.class, false, ESHttpClient::new); Dep.setIfAbsent(DepotConfig.class, new DepotConfig()); ArrayMap artifact = new ArrayMap("a", "apple", "b", "bee"); Desc desc = new Desc("test-simple", Map.class); ESDepotStore store = new ESDepotStore(); store.init(); store.put(desc, artifact); Utils.sleep(1500); Object got = store.get(desc); assert Utils.equals(artifact, got) : got; } }
mit
gvnn/slackcast
app/src/main/java/it/gvnn/slackcast/search/PodcastDataResponse.java
129
package it.gvnn.slackcast.search; import java.util.ArrayList; public class PodcastDataResponse extends ArrayList<Podcast> { }
mit
iyzico/iyzipay-java
src/main/java/com/iyzipay/model/subscription/enumtype/SubscriptionUpgradePeriod.java
302
package com.iyzipay.model.subscription.enumtype; public enum SubscriptionUpgradePeriod { NOW(1), NEXT_PERIOD(2); private final Integer value; SubscriptionUpgradePeriod(Integer value) { this.value = value; } public Integer getValue() { return value; } }
mit
iamlisa0526/bolianeducation-child
app/src/main/java/bolianeducation/bolianchild/view/ReplyActivity.java
11068
package bolianeducation.bolianchild.view; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.andview.refreshview.XRefreshView; import com.google.gson.reflect.TypeToken; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import bolianeducation.bolianchild.R; import bolianeducation.bolianchild.adapter.ReplyAdapter; import bolianeducation.bolianchild.api.BLService; import bolianeducation.bolianchild.camera.CameraActivity; import bolianeducation.bolianchild.camera.PopupWindowHelper; import bolianeducation.bolianchild.custom.ProgressDialog; import bolianeducation.bolianchild.manager.ActivityManage; import bolianeducation.bolianchild.manager.InfoManager; import bolianeducation.bolianchild.modle.CommentResponse; import bolianeducation.bolianchild.modle.PageEntity; import bolianeducation.bolianchild.modle.ReplyEntity; import bolianeducation.bolianchild.modle.ResponseEntity; import bolianeducation.bolianchild.utils.GsonUtils; import bolianeducation.bolianchild.utils.LogManager; import bolianeducation.bolianchild.utils.ToastUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static bolianeducation.bolianchild.KeyList.IKEY_REPLY_ENTITY; import static bolianeducation.bolianchild.KeyList.IKEY_TITLE; /** * Created by admin on 2017/8/10. * 某个评论的所有回复页 */ public class ReplyActivity extends CameraActivity { @BindView(R.id.recycler_view) RecyclerView recyclerView; @BindView(R.id.xrefreshview) XRefreshView xRefreshView; @BindView(R.id.tv_right) TextView tvRight; @BindView(R.id.et_content) EditText etContent; List<ReplyEntity> replyList = new ArrayList(); int pageNo = 1; int pageSize = 15; ReplyAdapter adapter; CommentResponse.Comment taskReply; String title; private ProgressDialog mDialog; PopupWindowHelper popupWindowHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reply); ButterKnife.bind(this); if (getIntent() != null) { taskReply = (CommentResponse.Comment) getIntent().getSerializableExtra(IKEY_REPLY_ENTITY); title = getIntent().getStringExtra(IKEY_TITLE); } init(); } @Override public void onPicture(File pictureFile, String picturePath, Bitmap pictureBitmap) { if (picturePath == null) return; requestUploadImg(pictureFile); } //定义Handler对象 private Handler handler = new Handler() { @Override //当有消息发送出来的时候就执行Handler的这个方法 public void handleMessage(Message msg) { super.handleMessage(msg); //处理UI requestAddReply((List) msg.obj); } }; ArrayList<String> imgIds = new ArrayList<>(); /** * 上传图片 */ private void requestUploadImg(final File file) { mDialog.show(); imgIds.clear(); new Thread() { @Override public void run() { //你要执行的方法 Call<ResponseEntity> uploadImg = BLService.getHeaderService().uploadImg(BLService.createFilePart("imgFile", file)); try { ResponseEntity body = uploadImg.execute().body(); if (body != null) { imgIds.add(body.getEntityId()); } LogManager.e("tag", GsonUtils.toJson(body)); } catch (IOException e) { e.printStackTrace(); } //执行完毕后给handler发送消息 Message message = new Message(); message.obj = imgIds; handler.sendMessage(message); } }.start(); } private void init() { //前个页面携带 setTitle(title); setTvBackVisible(true); tvRight.setVisibility(View.VISIBLE); tvRight.setText(R.string.report); mDialog = ProgressDialog.createDialog(context, "正在上传图片"); initPopupWindow(); xRefreshView.setAutoRefresh(true); xRefreshView.setPullLoadEnable(true); xRefreshView.setAutoLoadMore(false); xRefreshView.setPinnedTime(500); xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() { @Override public void onRefresh(boolean isPullDown) { pageNo = 1; requestAllReplyList(); } @Override public void onLoadMore(boolean isSilence) { // if (pageNo >= dataBeanX.getTotalPages()) { // return; // } pageNo++; requestAllReplyList(); } }); recyclerView.setLayoutManager(new LinearLayoutManager(this)); replyList.add(new ReplyEntity());//占位头部 adapter = new ReplyAdapter(context, taskReply, replyList); recyclerView.setAdapter(adapter); } /** * 初始化点击头像后的PopupWindow */ public void initPopupWindow() { popupWindowHelper = new PopupWindowHelper(context); popupWindowHelper.initPopup(); //拍照 popupWindowHelper.setOnTakePhotoListener(new View.OnClickListener() { @Override public void onClick(View v) { openCamera(); } }); //从相册选择 popupWindowHelper.setTakeAlbumListener(new View.OnClickListener() { @Override public void onClick(View v) { openAlbum(); } }); } PageEntity pageEntity; //请求某条评论的所有回复 private void requestAllReplyList() { Call<ResponseEntity> commentList = BLService.getHeaderService().getAllReplyById(taskReply.getId(), pageNo, pageSize); commentList.enqueue(new Callback<ResponseEntity>() { @Override public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) { ResponseEntity body = response.body(); LogManager.e("tag", GsonUtils.toJson(body)); if (body == null) return; pageEntity = GsonUtils.fromJson(GsonUtils.toJson(body.getData()), new TypeToken<PageEntity<ReplyEntity>>() { }.getType()); updateUI(); } @Override public void onFailure(Call<ResponseEntity> call, Throwable t) { runOnUiThread(new Runnable() { @Override public void run() { if (pageNo > 1) { pageNo--; } onLoadComplete(); } }); } }); } //更新UI private void updateUI() { runOnUiThread(new Runnable() { @Override public void run() { //设置刷新 // if (pageNo >= dataBeanX.getTotalPages()) { // xRefreshView.setPullLoadEnable(true); // } else { // xRefreshView.setPullLoadEnable(false); // } if (pageNo == 1) { replyList.clear(); replyList.add(new ReplyEntity());//占位头部 } onLoadComplete(); if (pageEntity.getData() == null) return; replyList.addAll(pageEntity.getData()); adapter.notifyDataSetChanged(); } }); } //加载完毕 protected void onLoadComplete() { new Handler().postDelayed(new Runnable() { @Override public void run() { // ToastUtil.showToast(CommunityWelfareActivity.this, "刷新首页数据了啊。。。"); xRefreshView.stopRefresh(); xRefreshView.stopLoadMore(); } }, 500); } String content; @OnClick({R.id.iv_send, R.id.tv_send, R.id.tv_right}) void onClick(View v) { switch (v.getId()) { case R.id.iv_send: if (popupWindowHelper.isShowing()) { popupWindowHelper.dismiss(); } else { popupWindowHelper.show(v); } break; case R.id.tv_send: content = etContent.getText().toString(); if (TextUtils.isEmpty(content)) { ToastUtil.showToast(this, "请输入回复内容"); return; } requestAddReply(null); break; case R.id.tv_right: //举报 ActivityManage.startReportActivity(this, taskReply.getId()); break; } } /** * 请求添加评论 */ private void requestAddReply(List<String> imgs) { final ReplyEntity replyEntity = new ReplyEntity(); replyEntity.setTaskActionId(taskReply.getId()); replyEntity.setReplyTime(System.currentTimeMillis()); replyEntity.setContent(content); replyEntity.setUserId(InfoManager.getUserId()); replyEntity.setAttachmentList(imgs); Call<ResponseEntity> addReply = BLService.getHeaderService().addReply(replyEntity); addReply.enqueue(new Callback<ResponseEntity>() { @Override public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) { mDialog.dismiss(); ResponseEntity body = response.body(); if (body == null) return; ToastUtil.showToast(ReplyActivity.this, body.getErrorMessage()); pageNo = 1; requestAllReplyList();//刷新数据 etContent.setText(""); hideKeyBoard(); } @Override public void onFailure(Call<ResponseEntity> call, Throwable t) { mDialog.dismiss(); ToastUtil.showToast(context, t.getMessage()); } }); } @Override public void onDestroy() { super.onDestroy(); if (mDialog != null) { mDialog.dismiss(); } if (popupWindowHelper != null) { popupWindowHelper.dismiss(); } } }
mit
lekster/devicehive-java
client/src/main/java/com/devicehive/client/impl/rest/providers/JsonRawProvider.java
3161
package com.devicehive.client.impl.rest.providers; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.devicehive.client.impl.Constants; import com.devicehive.client.impl.json.GsonFactory; import com.devicehive.client.impl.util.Messages; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.Charset; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; /** * Provider that converts hive entity to JSON and JSON to hive entity */ @Provider public class JsonRawProvider implements MessageBodyWriter<JsonObject>, MessageBodyReader<JsonObject> { @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType .APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype()); } @Override public JsonObject readFrom(Class<JsonObject> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { JsonElement element = new JsonParser().parse(new InputStreamReader(entityStream, Charset.forName(Constants.CURRENT_CHARSET))); if (element.isJsonObject()) { return element.getAsJsonObject(); } throw new IOException(Messages.NOT_A_JSON); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType .APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype()); } @Override public long getSize(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; } @Override public void writeTo(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Gson gson = GsonFactory.createGson(); Writer writer = null; try { writer = new OutputStreamWriter(entityStream, Charset.forName(Constants.CURRENT_CHARSET)); gson.toJson(jsonObject, writer); } finally { if (writer != null) { writer.flush(); } } } }
mit
ed-george/Lumber
src/uk/co/edgeorgedev/lumber/Stump.java
294
package uk.co.edgeorgedev.lumber; /** * Root of Logging interface * @author edgeorge * @version 1.0 * @since 2014-06-23 */ public interface Stump { /** Log a verbose message */ void v(Class<?> clazz, String message); void v(Class<?> clazz, Throwable th); //v,d,i,w,e,wtf }
mit
eamonfoy/trello-to-markdown
src/main/java/br/eti/mertz/wkhtmltopdf/wrapper/params/Params.java
982
package br.eti.mertz.wkhtmltopdf.wrapper.params; import java.util.ArrayList; import java.util.List; public class Params { private List<Param> params; public Params() { this.params = new ArrayList<Param>(); } public void add(Param param) { params.add(param); } public void add(Param... params) { for (Param param : params) { add(param); } } public List<String> getParamsAsStringList() { List<String> commandLine = new ArrayList<String>(); for (Param p : params) { commandLine.add(p.getKey()); String value = p.getValue(); if (value != null) { commandLine.add(p.getValue()); } } return commandLine; } public String toString() { StringBuilder sb = new StringBuilder(); for (Param param : params) { sb.append(param); } return sb.toString(); } }
mit
jonathonadler/ziplet-base64-test
src/main/java/uk/co/lucelle/Controller.java
256
package uk.co.lucelle; import org.springframework.web.bind.annotation.*; @RestController public class Controller { @RequestMapping("/") public @ResponseBody String index(@RequestBody String data) { // echo return data; } }
mit
311labs/SRL
java/src/jsrl/net/JavaPing.java
5558
/* * Created on Apr 28, 2005 */ package jsrl.net; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.InetAddress; import java.net.UnknownHostException; import jsrl.LoadLibrary; /** * JavaPing * Java Bindings for the SRL Library's Ping Logic */ public class JavaPing implements Runnable, PingListener { public static final int ECHO_REPLY = 0; public static final int DESTINATION_UNREACHABLE = 3; // local listener protected PingListener _listener = null; protected boolean _is_running = false; private static JavaPing __javaping_singleton = null; protected boolean _has_rawsockets = false; static { LoadLibrary.Load(); __javaping_singleton = new JavaPing(); } /** returns an instance of the Java Ping Utility * @throws SocketException */ public static JavaPing getInstance() { return __javaping_singleton; } private JavaPing() { _has_rawsockets = begin(); } public synchronized void startListening(PingListener listener) throws SocketException { if (!_has_rawsockets) throw new SocketException("permission denied attempting to create raw socket!"); _listener = listener; new Thread(this).start(); } public synchronized void stopListening() { _is_running = false; } public boolean isListening() { return _is_running; } protected int counter = 0; public int receivedCount() { return counter; } /** main method for performing reads */ public void run() { counter = 0; _is_running = true; while (_is_running) { try { _listener.ping_result(pong(100)); ++counter; } catch (SocketTimeoutException e) { } catch (SocketException e) { } } _listener = null; } static final PingResult DUMMY_RESULT = new PingResult(); public void clearIncoming() { _pong(0, DUMMY_RESULT); } public PingResult pingpong(String address, int seq, int msg_size, int time_out) throws SocketTimeoutException { return pingpong(address, seq, msg_size, time_out, 200); } public PingResult pingpong(String address, int seq, int msg_size, int time_out, int ttl) throws SocketTimeoutException { PingResult result = new PingResult(); if (!_pingpong(address, seq, msg_size, time_out, ttl, result)) { throw new java.net.SocketTimeoutException("receiving echo reply timed out after " + time_out); } return result; } public synchronized void ping(String address, int seq, int msg_size) { ping(address, seq, msg_size, 200); } /** send a ICMP Echo Request to the specified ip */ public native void ping(String address, int seq, int msg_size, int ttl); /**pthread * recv a ICMP Echo Reply * @param time_out in milliseconds * @throws SocketTimeoutException */ public PingResult pong(int time_out) throws SocketException, SocketTimeoutException { if (!_has_rawsockets) throw new SocketException("permission denied attempting to create raw socket!"); PingResult result = new PingResult(); if (!_pong(time_out, result)) { throw new java.net.SocketTimeoutException("receiving echo reply timeout after " + time_out); } return result; } /** closes the Java Ping utility free resources */ public void close() { synchronized (JavaPing.class) { if (__javaping_singleton != null) { end(); __javaping_singleton = null; } } } /** initialize our cpp code */ private native boolean begin(); /** native call for ping reply */ private native boolean _pong(int timeout, PingResult result); /** native call that will use ICMP.dll on windows */ private native boolean _pingpong(String address, int seq, int msg_size, int timeout, int ttl, PingResult result); /** free pinger resources */ public native void end(); public void ping_result(PingResult result) { if (result.type == ECHO_REPLY) { System.out.println("Reply from: " + result.from + " icmp_seq=" + result.seq + " bytes: " + result.bytes + " time=" + result.rtt + " TTL=" + result.ttl); } else if (result.type == DESTINATION_UNREACHABLE) { System.out.println("DESTINATION UNREACHABLE icmp_seq=" + result.seq); } else { System.out.println("unknown icmp packet received"); } } public static void main(String[] args) throws InterruptedException, UnknownHostException, SocketTimeoutException { if (args.length == 0) { System.out.println("usage: ping host [options]"); return; } String address = "127.0.0.1"; int count = 5; int size = 56; int delay = 1000; for (int i = 0; i < args.length; ++i) { if (args[i].compareToIgnoreCase("-c") == 0) { ++i; if (i < args.length) count = Integer.parseInt(args[i]); } else if (args[i].compareToIgnoreCase("-s") == 0) { ++i; if (i < args.length) size = Integer.parseInt(args[i]); } else if (args[i].compareToIgnoreCase("-d") == 0) { ++i; if (i < args.length) delay = Integer.parseInt(args[i]); } else { address = args[i]; } } System.out.println("count: " + count + " size: " + size + " delay: " + delay); address = InetAddress.getByName(address).getHostAddress(); JavaPing pingman; pingman = getInstance(); //pingman.startListening(pingman); //Thread.sleep(100); for (int i = 0; i < count; ++i) { pingman.ping_result(pingman.pingpong(address, i, size, 500)); Thread.sleep(delay); } if (pingman.receivedCount() < count) System.out.println("DID NOT RECEIVE REPLIES FOR SOME PACKETS!"); pingman.end(); } }
mit
anhnguyenbk/XCODE-MOBILE-APPS-DEV
SmileAlarm/app/src/main/java/com/xcode/mobile/smilealarm/alarmpointmanager/RisingPlanHandler.java
7754
package com.xcode.mobile.smilealarm.alarmpointmanager; import android.content.Context; import java.io.IOException; import java.sql.Date; import java.sql.Time; import java.util.Calendar; import java.util.HashMap; import com.xcode.mobile.smilealarm.DataHelper; import com.xcode.mobile.smilealarm.DateTimeHelper; import com.xcode.mobile.smilealarm.R; public class RisingPlanHandler { private static final int VALID_CODE = 1; private static final int INVALID_CODE_EXP = 2; private static final int INVALID_CODE_EXP_SOONER_AVG = 3; private static final int INVALID_CODE_EXP_AVG_TOO_FAR = 4; private static final int INVALID_CODE_EXP_AVG_TOO_NEAR = 5; private static final int INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW = 6; private static final int[] ListOfDescreasingMinutes = new int[]{-1, 2, 5, 10, 15, 18, 20}; private HashMap<Date, AlarmPoint> _risingPlan; private int _currentStage; private Date _theDateBefore; private Time _theWakingTimeBefore; private Time _expWakingTime; private int _checkCode; public static int Connect(Context ctx) { AlarmPointListHandler aplh_RisingPlan = new AlarmPointListHandler(true); AlarmPointListHandler aplh_AlarmPoint = new AlarmPointListHandler(false); return aplh_AlarmPoint.overwriteAlarmPointList(aplh_RisingPlan.getCurrentList(), ctx); } public int createRisingPlan(Time avgWakingTime, Time expWakingTime, Date startDate, Context ctx) throws IOException { _checkCode = checkParameters(avgWakingTime, expWakingTime, startDate); if (_checkCode != VALID_CODE) return _checkCode; _risingPlan = new HashMap<Date, AlarmPoint>(); _currentStage = 1; _theDateBefore = new Date(DateTimeHelper.GetTheDateBefore(startDate)); _theWakingTimeBefore = avgWakingTime; _expWakingTime = expWakingTime; AlarmPoint ap0 = new AlarmPoint(_theDateBefore); ap0.setColor(); _risingPlan.put(ap0.getSQLDate(), ap0); while (DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore, _expWakingTime) >= ListOfDescreasingMinutes[_currentStage]) { generateRisingPlanInCurrentStage(); _currentStage++; } generateTheLastAlarmPoint(); DataHelper.getInstance().saveAlarmPointListToData(true, _risingPlan); return ReturnCode.OK; } public String getNotificationFromErrorCode(Context ctx) { switch (_checkCode) { case INVALID_CODE_EXP: return ctx.getString(R.string.not_ExpTime); case INVALID_CODE_EXP_SOONER_AVG: return ctx.getString(R.string.not_AvgTime); case INVALID_CODE_EXP_AVG_TOO_FAR: return ctx.getString(R.string.not_AvgExpTooLong); case INVALID_CODE_EXP_AVG_TOO_NEAR: return ctx.getString(R.string.not_AvgExpTooShort); case INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW: return ctx.getString(R.string.not_StrDate); default: return "invalid Code"; } } private int checkParameters(Time avgTime, Time expTime, Date startDate) { if (!isAfterTomorrow(startDate)) return INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW; if (DateTimeHelper.CompareTo(avgTime, expTime) < 0) return INVALID_CODE_EXP_SOONER_AVG; Time BeginExpTime = new Time(DateTimeHelper.GetSQLTime(5, 0)); Time EndExpTime = new Time(DateTimeHelper.GetSQLTime(8, 0)); if (DateTimeHelper.CompareTo(expTime, BeginExpTime) < 0 || DateTimeHelper.CompareTo(expTime, EndExpTime) > 0) { return INVALID_CODE_EXP; } int maxMinutes = 875; int minMinutes = 20; if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) > maxMinutes) return INVALID_CODE_EXP_AVG_TOO_FAR; if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) < minMinutes) return INVALID_CODE_EXP_AVG_TOO_NEAR; return VALID_CODE; } private void generateRisingPlanInCurrentStage() { int daysInStage = 10; if (ListOfDescreasingMinutes[_currentStage] == 15) daysInStage = 15; for (int i = 0; i < daysInStage && DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore, _expWakingTime) >= ListOfDescreasingMinutes[_currentStage]; i++) { // WakingTime Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore)); AlarmPoint ap = new AlarmPoint(currentDate); ap.setColor(); Time currentWakingTime = DateTimeHelper.GetSQLTime(_theWakingTimeBefore, -(ListOfDescreasingMinutes[_currentStage])); ap.setTimePoint(currentWakingTime, 1); // SleepingTime Time sleepingTimeBefore = getSleepingTime(currentWakingTime); AlarmPoint apBefore = _risingPlan.get(_theDateBefore); apBefore.setTimePoint(sleepingTimeBefore, 2); // put _risingPlan.put(apBefore.getSQLDate(), apBefore); _risingPlan.put(ap.getSQLDate(), ap); // reset before _theDateBefore = currentDate; _theWakingTimeBefore = currentWakingTime; } } private void generateTheLastAlarmPoint() { // WakingTime Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore)); AlarmPoint ap = new AlarmPoint(currentDate); ap.setColor(); Time currentWakingTime = _expWakingTime; ap.setTimePoint(currentWakingTime, 1); // SleepingTime Time sleepingTimeBefore = getSleepingTime(currentWakingTime); AlarmPoint apBefore = _risingPlan.get(_theDateBefore); apBefore.setTimePoint(sleepingTimeBefore, 2); // put _risingPlan.put(apBefore.getSQLDate(), apBefore); _risingPlan.put(ap.getSQLDate(), ap); // reset before _theDateBefore = currentDate; _theWakingTimeBefore = currentWakingTime; } private Time getSleepingTime(Time wakingTime) { // wakingTime - 11 PM of thedaybefore > 8 hours => 11 PM // <=> if wakingTime >= 7 AM // or wakingTime >= 7AM => 11PM // 6AM <= wakingTime < 7AM => 10:30 PM // 5AM <= wakingTime < 6AM => 10 PM Time SevenAM = new Time(DateTimeHelper.GetSQLTime(7, 0)); Time SixAM = new Time(DateTimeHelper.GetSQLTime(6, 0)); Time FiveAM = new Time(DateTimeHelper.GetSQLTime(5, 0)); Time EleventPM = new Time(DateTimeHelper.GetSQLTime(23, 0)); Time Ten30PM = new Time(DateTimeHelper.GetSQLTime(22, 30)); Time TenPM = new Time(DateTimeHelper.GetSQLTime(22, 0)); if (DateTimeHelper.CompareTo(wakingTime, SevenAM) >= 0) { return EleventPM; } if (DateTimeHelper.CompareTo(wakingTime, SevenAM) < 0 && DateTimeHelper.CompareTo(wakingTime, SixAM) >= 0) { return Ten30PM; } if (DateTimeHelper.CompareTo(wakingTime, SixAM) < 0 && DateTimeHelper.CompareTo(wakingTime, FiveAM) >= 0) { return TenPM; } return null; } private Boolean isAfterTomorrow(Date startDate) { Date today = new Date(Calendar.getInstance().getTimeInMillis()); Date tomorrow = new Date(DateTimeHelper.GetTheNextDate(today)); return (DateTimeHelper.CompareTo(startDate, tomorrow) > 0); } }
mit
Naoki-Yatsu/FX-AlgorithmTrading
ats/src/main/java/ny2/ats/model/tool/TradeConditionOperator.java
1710
package ny2.ats.model.tool; import java.util.function.BiPredicate; /** * 取引条件計算の演算子のクラスです */ public enum TradeConditionOperator { EQUAL((d1, d2) -> Double.compare(d1, d2) == 0, null, "="), LESS((d1, d2) -> d1 < d2, null, "<"), LESS_EQUAL((d1, d2) -> d1 <= d2, null, "<="), GRATER((d1, d2) -> d1 > d2, null, ">"), GRATER_EQUAL((d1, d2) -> d1 >= d2, null, ">="), BETWEEN((d1, d2) -> d1 >= d2, (d1, d2) -> d1 <= d2, " between "), WITHOUT((d1, d2) -> d1 < d2, (d1, d2) -> d1 > d2, " without "); // ////////////////////////////////////// // Field // ////////////////////////////////////// private BiPredicate<Double, Double> biPredicate; private BiPredicate<Double, Double> biPredicate2; private String expression; private TradeConditionOperator(BiPredicate<Double, Double> biPredicate, BiPredicate<Double, Double> biPredicate2, String expression) { this.biPredicate = biPredicate; this.expression = expression; } // ////////////////////////////////////// // Method // ////////////////////////////////////// /** * 2種類のBiPredicateを持つかどうかを返します<br> * BETWEEN, WITHOUT のみtrueを返します * @return */ public boolean hasTwoPredicate() { if (biPredicate2 != null) { return true; } else { return false; } } public BiPredicate<Double, Double> getBiPredicate() { return biPredicate; } public BiPredicate<Double, Double> getBiPredicate2() { return biPredicate2; } public String getExpression() { return expression; } }
mit
Pinablink/FragMobile
FragMobile/app/src/test/java/com/fragmobile/ExampleUnitTest.java
408
package com.fragmobile; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
team-compilers/compilers
MiniJava/results/SamplesCorrect/LinkedList/code.java
6548
class LinkedList { public static void main(String[] a) { System.out.println(new LL().Start()); } } class Element { int Age; int Salary; boolean Married; public boolean Init(int v_Age, int v_Salary, boolean v_Married) { Age = v_Age; Salary = v_Salary; Married = v_Married; return true; } public int GetAge() { return Age; } public int GetSalary() { return Salary; } public boolean GetMarried() { return Married; } public boolean Equal(Element other) { boolean ret_val; int aux01; int aux02; int nt; ret_val = true; aux01 = other.GetAge(); if (!(this.Compare(aux01, Age))) ret_val = false; else { aux02 = other.GetSalary(); if (!(this.Compare(aux02, Salary))) ret_val = false; else if (Married) if (!(other.GetMarried())) ret_val = false; else nt = 0; else if (other.GetMarried()) ret_val = false; else nt = 0; } return ret_val; } public boolean Compare(int num1, int num2) { boolean retval; int aux02; retval = false; aux02 = num2 + 1; if (num1 < num2) retval = false; else if (!(num1 < aux02)) retval = false; else retval = true; return retval; } } class List { Element elem; List next; boolean end; public boolean Init() { end = true; return true; } public boolean InitNew(Element v_elem, List v_next, boolean v_end) { end = v_end; elem = v_elem; next = v_next; return true; } public List Insert(Element new_elem) { boolean ret_val; List aux03; List aux02; aux03 = this; aux02 = new List(); ret_val = aux02.InitNew(new_elem, aux03, false); return aux02; } public boolean SetNext(List v_next) { next = v_next; return true; } public List Delete(Element e) { List my_head; boolean ret_val; boolean aux05; List aux01; List prev; boolean var_end; Element var_elem; int aux04; int nt; my_head = this; ret_val = false; aux04 = 0 - 1; aux01 = this; prev = this; var_end = end; var_elem = elem; while (!(var_end) && !(ret_val)) { if (e.Equal(var_elem)) { ret_val = true; if (aux04 < 0) { my_head = aux01.GetNext(); } else { System.out.println(0 - 555); aux05 = prev.SetNext(aux01.GetNext()); System.out.println(0 - 555); } } else nt = 0; if (!(ret_val)) { prev = aux01; aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); aux04 = 1; } else nt = 0; } return my_head; } public int Search(Element e) { int int_ret_val; List aux01; Element var_elem; boolean var_end; int nt; int_ret_val = 0; aux01 = this; var_end = end; var_elem = elem; while (!(var_end)) { if (e.Equal(var_elem)) { int_ret_val = 1; } else nt = 0; aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); } return int_ret_val; } public boolean GetEnd() { return end; } public Element GetElem() { return elem; } public List GetNext() { return next; } public boolean Print() { List aux01; boolean var_end; Element var_elem; aux01 = this; var_end = end; var_elem = elem; while (!(var_end)) { System.out.println(var_elem.GetAge()); aux01 = aux01.GetNext(); var_end = aux01.GetEnd(); var_elem = aux01.GetElem(); } return true; } } class LL { public int Start() { List head; List last_elem; boolean aux01; Element el01; Element el02; Element el03; last_elem = new List(); aux01 = last_elem.Init(); head = last_elem; aux01 = head.Init(); aux01 = head.Print(); el01 = new Element(); aux01 = el01.Init(25, 37000, false); head = head.Insert(el01); aux01 = head.Print(); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(39, 42000, true); el02 = el01; head = head.Insert(el01); aux01 = head.Print(); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(22, 34000, false); head = head.Insert(el01); aux01 = head.Print(); el03 = new Element(); aux01 = el03.Init(27, 34000, false); System.out.println(head.Search(el02)); System.out.println(head.Search(el03)); System.out.println(10000000); el01 = new Element(); aux01 = el01.Init(28, 35000, false); head = head.Insert(el01); aux01 = head.Print(); System.out.println(2220000); head = head.Delete(el02); aux01 = head.Print(); System.out.println(33300000); head = head.Delete(el01); aux01 = head.Print(); System.out.println(44440000); return 0; } }
mit
Daniel12321/NPCs
src/main/java/me/mrdaniel/npcs/actions/ActionGoto.java
1403
package me.mrdaniel.npcs.actions; import javax.annotation.Nonnull; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import me.mrdaniel.npcs.catalogtypes.actiontype.ActionTypes; import me.mrdaniel.npcs.io.NPCFile; import me.mrdaniel.npcs.managers.ActionResult; import ninja.leaping.configurate.ConfigurationNode; public class ActionGoto extends Action { private int next; public ActionGoto(@Nonnull final ConfigurationNode node) { this(node.getNode("Next").getInt(0)); } public ActionGoto(final int next) { super(ActionTypes.GOTO); this.next = next; } public void setNext(final int next) { this.next = next; } @Override public void execute(final Player p, final NPCFile file, final ActionResult result) { result.setNextAction(this.next); } @Override public void serializeValue(final ConfigurationNode node) { node.getNode("Next").setValue(this.next); } @Override public Text getLine(final int index) { return Text.builder().append(Text.of(TextColors.GOLD, "Goto: "), Text.builder().append(Text.of(TextColors.AQUA, this.next)) .onHover(TextActions.showText(Text.of(TextColors.YELLOW, "Change"))) .onClick(TextActions.suggestCommand("/npc action edit " + index + " goto <goto>")).build()).build(); } }
mit
parambirs/binaryedu
src/main/java/com/binaryedu/web/controllers/SignUpSuccessController.java
782
package com.binaryedu.web.controllers; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class SignUpSuccessController implements Controller { protected final Log logger = LogFactory.getLog(this.getClass()); public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Returning Sign Up Success View"); return new ModelAndView("signupSuccess"); } }
mit
Playtika/testcontainers-spring-boot
embedded-dynamodb/src/test/java/com/playtika/test/dynamodb/DisableDynamoDBTest.java
1055
package com.playtika.test.dynamodb; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.testcontainers.containers.Container; public class DisableDynamoDBTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( EmbeddedDynamoDBBootstrapConfiguration.class, EmbeddedDynamoDBDependenciesAutoConfiguration.class)); @Test public void contextLoads() { contextRunner .withPropertyValues( "embedded.dynamodb.enabled=false" ) .run((context) -> Assertions.assertThat(context) .hasNotFailed() .doesNotHaveBean(Container.class) .doesNotHaveBean("dynamodbDependencyPostProcessor")); } }
mit