repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
peterlharding/PDQ
java/src/com/perfdynamics/pdq/Systat.java
480
/* * Created on 17/02/2004 * */ package com.perfdynamics.pdq; /** * @author plh * */ public class Systat { public double response = 0.0; public double thruput = 0.0; public double residency = 0.0; public double physmem = 0.0; public double highwater = 0.0; public double malloc = 0.0; public double mpl = 0.0; public double maxN = 0.0; public double maxTP = 0.0; public double minRT = 0.0; public static void main(String[] args) { } }
mit
johan-gorter/Instantlogic
webapps/presence/src/main/java/org/instantlogic/engine/message/StartMessage.java
1815
package org.instantlogic.engine.message; import org.instantlogic.engine.presence.Presence; import org.instantlogic.engine.presence.Traveler; import org.instantlogic.fabric.Instance; import org.instantlogic.interaction.Application; import org.instantlogic.interaction.util.FlowContext; import org.instantlogic.interaction.util.FlowEventOccurrence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StartMessage extends Message { private static final Logger logger = LoggerFactory.getLogger(StartMessage.class); private final String location; public StartMessage(String location) { this.location= location; } @Override public void execute(Application application, Traveler traveler, Presence presence, Instance theCase) { FlowEventOccurrence eventOccurrence; FlowContext flowContext = FlowContext.create(application, location, theCase, presence.getCaseName(), traveler.getTravelerInfo()); if (location!=null) { logger.info("Traveler {}-{} starting at {}", new Object[]{traveler.getTravelerInfo().getAuthenticatedUsername(), traveler.getTravelerInfo().getTravelerId(), location}); eventOccurrence = flowContext.getPage().enter(flowContext); } else { logger.info("Traveler {}-{} starting", new Object[]{traveler.getTravelerInfo().getAuthenticatedUsername(), traveler.getTravelerInfo().getTravelerId()}); if (application.getStartPlace()!=null) { eventOccurrence = new FlowEventOccurrence(application.getStartPlace()); } else { throw new RuntimeException("No start place was defined"); } } while (eventOccurrence!=null) { eventOccurrence = flowContext.step(eventOccurrence); } traveler.getPresence().enter(traveler, flowContext.toPath()); } @Override public String toString() { return "StartMessage [location=" + location + "]"; } }
mit
Grinch/SpongeCommon
src/main/java/org/spongepowered/common/event/tracking/phase/generation/GenerationContext.java
2680
/* * 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.event.tracking.phase.generation; import net.minecraft.world.WorldServer; import org.spongepowered.api.world.World; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.interfaces.world.IMixinWorldServer; public class GenerationContext<G extends GenerationContext<G>> extends PhaseContext<G> { private World world; GenerationContext(IPhaseState<? extends G> state) { super(state); } @SuppressWarnings("unchecked") public G world(net.minecraft.world.World world) { this.world = (World) world; return (G) this; } @SuppressWarnings("unchecked") public G world(World world) { this.world = world; return (G) this; } @SuppressWarnings("unchecked") public G world(IMixinWorldServer world) { this.world = world.asSpongeWorld(); return (G) this; } @SuppressWarnings("unchecked") public G world(WorldServer worldServer) { this.world = (World) worldServer; return (G) this; } public World getWorld() { return this.world; } @Override public PrettyPrinter printCustom(PrettyPrinter printer) { return super.printCustom(printer) .add(" - %s: %s", "World", this.world); } }
mit
3DRealms/jrpg
dominio/src/main/java/habilidad/HabilidadInstance.java
222
package habilidad; import personaje.Personaje; public class HabilidadInstance extends Habilidad { public HabilidadInstance(){ } @Override public void afectar(Personaje personaje, int estado, int ataque) { } }
mit
daniellavoie/Kubik
kubik/kubik-server/src/main/java/com/cspinformatique/kubik/server/domain/sales/exception/InvalidTransactionStatus.java
471
package com.cspinformatique.kubik.server.domain.sales.exception; import com.braintreegateway.Transaction; public class InvalidTransactionStatus extends RuntimeException { private static final long serialVersionUID = 8332170708014584814L; private final Transaction transaction; public InvalidTransactionStatus(final Transaction transaction){ this.transaction = transaction; } public Transaction getTransaction() { return transaction; } }
mit
SlickJava/SmokeyHotel
SmokeyHotels/src/com/awesome/db/StatementSetter.java
257
package com.awesome.db; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author InsaneAboutTNT * */ public interface StatementSetter { public void prepareStatement(PreparedStatement statement) throws SQLException; }
mit
indiependente/jfasta
src/jFasta/DiagonalRun.java
1704
package jFasta; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class DiagonalRun { private int id; private int i, j; private int score; private List<HotSpot> hotSpostList; public List<HotSpot> getHotSpostList() { return hotSpostList; } public DiagonalRun(int i, int j) { this.id = i - j; this.i = i; this.j = j; this.score = 0; hotSpostList = new ArrayList<HotSpot>(); } public void finalize() { hotSpostList.clear(); hotSpostList = null; } public int getId() { return id; } @Override public String toString() { return "DiagonalRun [id=" + id + ", i=" + i + ", j=" + j + ", hotSpostList=" + hotSpostList + "]"; } public int getI() { return i; } public int getJ() { return j; } public void sort() { Collections.sort(hotSpostList); } public void addHotSpot(HotSpot hs){ sort(); hotSpostList.add(hs); } public HotSpot getHotSpotAt(int i){ return hotSpostList.get(i); } public HotSpot getLastHotSpot(){ return hotSpostList.size()>0 ? hotSpostList.get(hotSpostList.size()-1) : null; } public HotSpot getFirstHotSpot(){ return hotSpostList.size()>0 ? hotSpostList.get(0) : null; } public String extractStringFromReference(String ref) { HotSpot last = getLastHotSpot(); int lastIndex = j + (last.getJ() - j + last.getK()); return ref.substring(j, lastIndex); } public String extractStringFromQuery(String qry) { HotSpot last = getLastHotSpot(); int lastIndex = i + (last.getI() - i + last.getK()); return qry.substring(i, lastIndex); } public void increaseScore(int score) { this.score += score; } public int getScore() { return score; } }
mit
cleitonpqz/jungle-s-map
app/models/VariavelInteresse.java
1265
package models; import java.util.*; import javax.persistence.*; import play.db.ebean.*; import play.data.format.*; import play.data.validation.*; import com.avaje.ebean.*; @Entity public class VariavelInteresse extends Model { @Id public Long id; @Constraints.Required(message="O campo sigla é obrigatório!") public String sigla; @Constraints.Required(message="O campo nome é obrigatório!") public String nome; public static Model.Finder<Long,VariavelInteresse> find = new Model.Finder<Long,VariavelInteresse>(Long.class, VariavelInteresse.class); public static Map<String,String> opcoes() { LinkedHashMap<String,String> opcoes = new LinkedHashMap<String,String>(); for(VariavelInteresse v: VariavelInteresse.find.orderBy("nome").findList()) { opcoes.put(v.id.toString(), v.nome +" ("+v.sigla+")"); } return opcoes; } public static Page<VariavelInteresse> page(int page, int pageSize, String sortBy, String order, String filter) { return find.where() .ilike("nome", "%" + filter + "%") .orderBy(sortBy + " " + order) .findPagingList(pageSize) .getPage(page); } }
mit
Griell/JMines
src/main/java/ch/marc/jmines/entities/Settings.java
1003
package ch.marc.jmines.entities; import java.awt.*; public class Settings { private String name; private int themeId; // 0 = Flat, 1 = Metal private Color backgroundColor; private Color buttonColor; public Settings() { this.name = "Name"; this.backgroundColor = Color.WHITE; this.buttonColor = Color.LIGHT_GRAY; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getThemeId() { return themeId; } public void setThemeId(int themeId) { this.themeId = themeId; } public Color getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; } public Color getButtonColor() { return buttonColor; } public void setButtonColor(Color buttonColor) { this.buttonColor = buttonColor; } }
mit
tpoderoso/agendaUFSCar
agenda/src/main/java/br/ufscar/web/core/service/TelefoneService.java
481
package br.ufscar.web.core.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import br.ufscar.web.core.dao.TelefoneDao; import br.ufscar.web.core.dao.EntityDao; import br.ufscar.web.core.model.Telefone; @Component public class TelefoneService extends EntityService<Telefone> { @Autowired private TelefoneDao dao; @Override protected EntityDao<Telefone> getDao() { return dao; } }
mit
FavPiggy/EasterEgg
src/main/java/edu/uw/tacoma/piggy/view/listener/MenuListener.java
1108
package edu.uw.tacoma.piggy.view.listener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import edu.uw.tacoma.piggy.view.PiggyGUI; import edu.uw.tacoma.piggy.view.PiggyViewConst; /** * The class for menu listener * @author Varik Hoang */ public class MenuListener implements ActionListener { PiggyGUI myMain; /** * The constructor * @param menu the menu */ public MenuListener(PiggyGUI theMain) { myMain = theMain; } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(PiggyViewConst.MENU_FILE_EXIT)) { // FIXME it should pop up a window to ask user if he/she really want to close System.exit(0); } else if (e.getActionCommand().equals(PiggyViewConst.MENU_HELP_ABOUT)) { // display form JOptionPane.showMessageDialog(myMain, "Kerry Ferguson: kferg9@uw.edu\n" + "Kirtwinder Gulati: gulati21@live.com\n" + "Varik Hoang: varikmp@uw.edu\n" + "Mahad Fahiye: mahadf@uw.edu\n" + "Arwain Karlin: ak99@uw.edu\n" + "Cuong Tran: cuongtr@uw.edu"); } } }
mit
heisedebaise/tephra
tephra-core/src/main/java/org/lpw/tephra/atomic/Closable.java
161
package org.lpw.tephra.atomic; /** * 可关闭事务。 * * @author lpw */ public interface Closable { /** * 关闭。 */ void close(); }
mit
beduino-project/dcaf-java
src/test/java/de/unibremen/beduino/dcaf/ClientAuthorizationManagerTest.java
2671
package de.unibremen.beduino.dcaf; import de.unibremen.beduino.dcaf.utils.Tuple; import org.junit.Test; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; /** * @author Connor Lanigan */ public class ClientAuthorizationManagerTest { @Test public void lookupNotFound() throws Exception { ClientAuthorizationManager cam = new ClientAuthorizationManager(); String samUrl = "coaps://nonexistent.example.com"; try { cam.lookup(samUrl); fail("Lookup returned an unexpected SAM"); } catch (UnsupportedOperationException e) { } ServerAuthorizationManager sam = mock(ServerAuthorizationManager.class); SamLocator locator = url -> { if (url.getHost().equals("nonexistent.example.com")) { return Optional.of(Tuple.of(1, sam)); } else { return Optional.empty(); } }; cam.registerSamLocator(locator); assertEquals(sam, cam.lookup(samUrl)); cam.unregisterSamLocator(locator); try { ServerAuthorizationManager lSam = cam.lookup(samUrl); if (sam.equals(lSam)) fail("Lookup returned old SAM"); else fail("Lookup returned an unexpected SAM"); } catch (UnsupportedOperationException e) { } } @Test public void lookupPriority() throws Exception { ClientAuthorizationManager cam = new ClientAuthorizationManager(); String samUrl = "coaps://nonexistent.example.com"; ServerAuthorizationManager sam1 = mock(ServerAuthorizationManager.class); ServerAuthorizationManager sam2 = mock(ServerAuthorizationManager.class); ServerAuthorizationManager sam3 = mock(ServerAuthorizationManager.class); SamLocator locator1 = url -> { if (url.getHost().equals("nonexistent.example.com")) { return Optional.of(Tuple.of(10, sam1)); } else { return Optional.empty(); } }; cam.registerSamLocator(locator1); assertEquals(sam1, cam.lookup(samUrl)); SamLocator locator2 = url -> { if (url.getHost().equals("nonexistent.example.com")) { return Optional.of(Tuple.of(20, sam2)); } else { return Optional.empty(); } }; cam.registerSamLocator(locator2); assertEquals(sam1, cam.lookup(samUrl)); cam.unregisterSamLocator(locator1); assertEquals(sam2, cam.lookup(samUrl)); cam.registerSamLocator(locator1); SamLocator locator3 = url -> { if (url.getHost().equals("nonexistent.example.com")) { return Optional.of(Tuple.of(5, sam3)); } else { return Optional.empty(); } }; cam.registerSamLocator(locator3); assertEquals(sam3, cam.lookup(samUrl)); cam.unregisterSamLocator(locator1); assertEquals(sam3, cam.lookup(samUrl)); } }
mit
justacoder/mica
src/model/MiPartToModel.java
3031
/* *************************************************************************** * Mica - the Java(tm) Graphics Framework * *************************************************************************** * NOTICE: Permission to use, copy, and modify this software and its * * documentation is hereby granted provided that this notice appears in * * all copies. * * * * Permission to distribute un-modified copies of this software and its * * documentation is hereby granted provided that no fee is charged and * * that this notice appears in all copies. * * * * SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE * * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT * * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * * A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE * * LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR * * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR * * DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. * * * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND * * DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * * *************************************************************************** * Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. * *************************************************************************** */ package com.swfm.mica; /**---------------------------------------------------------------------------------------------- * * @version %I% %G% * @author Michael L. Davis * @release 1.4.1 * @module %M% * @language Java (JDK 1.4) *----------------------------------------------------------------------------------------------*/ public class MiPartToModel extends MiModelEntity { private MiPart part; public MiPartToModel(MiPart part) { this.part = part; setPropertyDescriptions(part.getPropertyDescriptions()); part.appendActionHandler(this, Mi_PROPERTY_CHANGE_ACTION); } public void setPropertyValue(String name, String value) { String oldValue = getPropertyValue(name); part.setPropertyValue(name, value); MiPropertyChange event = new MiPropertyChange(this, name, value, oldValue); event.setPhase(Mi_MODEL_CHANGE_COMMIT_PHASE); dispatchPropertyChangeEvent(event); } public String getPropertyValue(String name) { return(part.getPropertyValue(name)); } }
mit
lucarin91/PAD-project
api/src/main/java/lr/api/PublicAPI.java
1529
package lr.api; import lr.core.Data; import lr.core.Exception.SendException; import lr.core.Nodes.GossipResource; import lr.core.Messages.Message.*; import lr.core.Messages.MessageRequest; import lr.core.Messages.MessageResponse; import org.springframework.web.bind.annotation.*; /** * Created by luca on 01/03/16. */ @RestController @RequestMapping("/api") public class PublicAPI { private MessageResponse<?> sendRequest(MessageRequest<?> req){ try { return GossipResource.sendRequestToRandomNode(req); } catch (SendException e) { return new MessageResponse<>(MessageResponse.MSG_STATUS.ERROR, "error"); } } @RequestMapping(method = RequestMethod.GET) public MessageResponse<?> get(@RequestParam(value = "key") String key) { return sendRequest(new MessageRequest<>(MSG_OPERATION.GET, key)); } @RequestMapping(method = RequestMethod.POST) public MessageResponse<?> add(@RequestBody Data data) { return sendRequest(new MessageRequest<>(MSG_OPERATION.ADD, data.getKey(), data.getValue())); } @RequestMapping(method = RequestMethod.DELETE) public MessageResponse<?> del(@RequestParam(value = "key") String key) { return sendRequest(new MessageRequest<>(MSG_OPERATION.DELETE, key)); } @RequestMapping(method = RequestMethod.PUT) public MessageResponse<?> update(@RequestBody Data data) { return sendRequest(new MessageRequest<>(MSG_OPERATION.UPDATE, data.getKey(), data.getValue())); } }
mit
halab4dev/mongo2j
src/test/java/com/github/halab4dev/mongo2j/mapper/DefaultMapperSimpleAttributesTests.java
5988
package com.github.halab4dev.mongo2j.mapper; import org.bson.Document; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.*; import static org.junit.jupiter.api.Assertions.*; /* * * @author halab */ public class DefaultMapperSimpleAttributesTests { Mapper mapper = new DefaultMapper(); @Test @DisplayName("Test serialize with null object") public void testSerializeNullObject() { Document document = mapper.toDocument(null); assertNull(document); } @Test @DisplayName("Test deserialize with null document") public void testDeserializeNullDocument() { Document document = null; Object object = mapper.toObject(document, Object.class); assertNull(object); } @Test @DisplayName("Test serialize with primitive attributes") public void testSerializePrimitiveAttributes() { PrimitiveAttributesExample object = new PrimitiveAttributesExample(); object.setBooleanAttribute(true); object.setByteAttribute((byte) 1); object.setShortAttribute((short) 5); object.setIntegerAttribute(10); object.setLongAttribute(20L); object.setFloatAttribute(50F); object.setDoubleAttribute(100D); object.setCharAttribute('a'); Document document = mapper.toDocument(object); assertEquals(object.isBooleanAttribute(), document.getBoolean("booleanAttribute")); assertEquals(object.getByteAttribute(), (byte) document.get("byteAttribute")); assertEquals(object.getShortAttribute(), (short) document.get("shortAttribute")); assertEquals(object.getIntegerAttribute(), document.getInteger("integerAttribute")); assertEquals(object.getLongAttribute(), document.getLong("longAttribute")); assertEquals(object.getFloatAttribute(), (float) document.get("floatAttribute")); assertEquals(object.getDoubleAttribute(), document.getDouble("doubleAttribute")); assertEquals(object.getCharAttribute(), (char) document.get("charAttribute")); } @Test @DisplayName("Test deserialize with primitive attributes") public void testDeserializePrimitiveAttributes() { Document document = new Document("booleanAttribute", true) .append("byteAttribute", (byte) 1) .append("shortAttribute", (short) 5) .append("integerAttribute", 10) .append("longAttribute", 20L) .append("floatAttribute", 50F) .append("doubleAttribute", 100D) .append("charAttribute", 'a'); PrimitiveAttributesExample object = mapper.toObject(document, PrimitiveAttributesExample.class); assertTrue(object.isBooleanAttribute()); assertEquals((byte) 1, object.getByteAttribute()); assertEquals((short) 5, object.getShortAttribute()); assertEquals(10, object.getIntegerAttribute()); assertEquals(20L, object.getLongAttribute()); assertEquals(50F, object.getFloatAttribute()); assertEquals(100D, object.getDoubleAttribute()); assertEquals('a', object.getCharAttribute()); } @Test @DisplayName("Test serialize with wrapped attributes") public void testSerializeWrappedAttributes() { PrimitiveAttributesExample object = new PrimitiveAttributesExample(); object.setBooleanAttribute(true); object.setByteAttribute((byte) 1); object.setShortAttribute((short) 5); object.setIntegerAttribute(10); object.setLongAttribute(20L); object.setFloatAttribute(50F); object.setDoubleAttribute(100D); object.setCharAttribute('a'); Document document = mapper.toDocument(object); assertEquals(object.isBooleanAttribute(), document.getBoolean("booleanAttribute")); assertEquals(object.getByteAttribute(), (byte) document.get("byteAttribute")); assertEquals(object.getShortAttribute(), (short) document.get("shortAttribute")); assertEquals(object.getIntegerAttribute(), document.getInteger("integerAttribute")); assertEquals(object.getLongAttribute(), document.getLong("longAttribute")); assertEquals(object.getFloatAttribute(), (float) document.get("floatAttribute")); assertEquals(object.getDoubleAttribute(), document.getDouble("doubleAttribute")); assertEquals(object.getCharAttribute(), (char) document.get("charAttribute")); } @Test @DisplayName("Test deserialize with wrapped attributes") public void testDeserializeWrappedAttributes() { Document document = new Document("booleanAttribute", true) .append("byteAttribute", (byte) 1) .append("shortAttribute", (short) 5) .append("integerAttribute", 10) .append("longAttribute", 20L) .append("floatAttribute", 50F) .append("doubleAttribute", 100D) .append("charAttribute", 'a'); PrimitiveAttributesExample object = mapper.toObject(document, PrimitiveAttributesExample.class); assertTrue(object.isBooleanAttribute()); assertEquals((byte) 1, object.getByteAttribute()); assertEquals((short) 5, object.getShortAttribute()); assertEquals(10, object.getIntegerAttribute()); assertEquals(20L, object.getLongAttribute()); assertEquals(50F, object.getFloatAttribute()); assertEquals(100D, object.getDoubleAttribute()); assertEquals('a', object.getCharAttribute()); } @Test @DisplayName("Test serialize with static final attributes") public void testStaticFinalAttribute() { PrimitiveAttributesExample object = new PrimitiveAttributesExample(); object.setBooleanAttribute(true); Document document = mapper.toDocument(object); assertTrue(object.isBooleanAttribute()); assertNull(document.getString("STATIC_FINAL")); } }
mit
komitoff/Java-DB-Fundamentals
spring_advanced_queries/Bookshop/src/main/java/app/service/api/CategoryService.java
168
package app.service.api; import app.entities.Category; public interface CategoryService { void save(Category category); Category findByName(String name); }
mit
kazuhira-r/infinispan-getting-started
embedded-distributed-streams/src/main/java/org/littlewings/infinispan/distributedstreams/EmbeddedDistributedStreamsParallel.java
11289
package org.littlewings.infinispan.distributedstreams; import java.io.Serializable; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.infinispan.CacheStream; import org.infinispan.stream.CacheCollectors; public class EmbeddedDistributedStreamsParallel extends EmbeddedCacheSupport { public static void main(String... args) { EmbeddedDistributedStreamsParallel eds = new EmbeddedDistributedStreamsParallel(); switch (args[0]) { case "dist-simple": eds.distSimple(); break; case "dist-parallel": eds.distParallel(); break; case "dist-parallelDistribution": eds.distParallelDistribution(); break; case "dist-sequential": eds.distSequential(); break; case "dist-sequentialDistribution": eds.distSequentialDistribution(); break; case "repl-simple": eds.replSimple(); break; case "repl-parallel": eds.replParallel(); break; case "repl-parallelDistribution": eds.replParallelDistribution(); break; default: System.out.printf("unknown option[%s].%n", args[0]); System.exit(1); } } public void distSimple() { this.<String, String>withCache("distCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void distParallel() { this.<String, String>withCache("distCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .parallel() .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void distParallelDistribution() { this.<String, String>withCache("distCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .parallelDistribution() .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void distSequential() { this.<String, String>withCache("distCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .sequential() .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void distSequentialDistribution() { this.<String, String>withCache("distCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .sequentialDistribution() .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void replSimple() { this.<String, String>withCache("replCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void replParallel() { this.<String, String>withCache("replCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } public void replParallelDistribution() { this.<String, String>withCache("replCache", cache -> { System.out.println("Cache[" + cache.getName() + "] start."); IntStream.rangeClosed(1, 10).forEach(i -> cache.put("key" + i, "value" + i)); try (CacheStream<Map.Entry<String, String>> stream = cache.entrySet().stream()) { int result = stream .map((Serializable & Function<Map.Entry<String, String>, Integer>) e -> { System.out.println("map phase Thread[" + Thread.currentThread() + "]"); return Integer.parseInt(e.getValue().substring("value".length())); }) .collect(CacheCollectors.serializableCollector(() -> Collectors.summingInt(v -> v))); System.out.println("Cache[" + cache.getName() + "] result = " + result); int expected = 55; if (result != expected) { throw new IllegalStateException("result must be [" + expected + "]"); } } }); } }
mit
murex/murex-coding-dojo
Paris/2016/2016-01-07-TextJustification-Java/src/test/java/com/murex/codingdojo/textjustification/SolutionTest.java
2950
/** * Copyright Murex S.A.S., 2003-2016. All Rights Reserved. * * This software program is proprietary and confidential to Murex S.A.S and its affiliates ("Murex") and, without limiting the generality of the foregoing reservation of rights, shall not be accessed, used, reproduced or distributed without the * express prior written consent of Murex and subject to the applicable Murex licensing terms. Any modification or removal of this copyright notice is expressly prohibited. */ package com.murex.codingdojo.textjustification; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import org.junit.Test; public class SolutionTest { //~ ---------------------------------------------------------------------------------------------------------------- //~ Methods //~ ---------------------------------------------------------------------------------------------------------------- @Test public void testFullJustify_withASingleWord() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "justification." }, 16); assertEquals(Arrays.asList("justification. "), result); } @Test public void testFullJustify_withAFullLineSingleWord() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "0123456789ABCDE." }, 16); assertEquals(Arrays.asList("0123456789ABCDE."), result); } @Test public void testFullJustify_MoreWords() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "This", "is", "an", "example", "of", "text", "justification." }, 16); assertEquals(Arrays.asList("This is an", "example of text", "justification. "), result); } @Test public void testFullJustify_SingleLetter() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "a", "b", "c" }, 1); assertEquals(Arrays.asList("a", "b", "c"), result); } @Test public void testFullJustify_LastLineHaveMoreWords() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "What", "must", "be", "shall", "be." }, 12); assertEquals(Arrays.asList("What must be", "shall be. "), result); } @Test public void testFullJustify_WithEmptyWord() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "" }, 2); assertEquals(Arrays.asList(" "), result); } @Test public void testFullJustify_WithMiddleLineContainingOnlyOneLetter() { Solution solution = new Solution(); List<String> result = solution.fullJustify(new String[] { "hello", ",", "world" }, 5); assertEquals(Arrays.asList("hello", ", ", "world"), result); } }
mit
m-wrona/gwt-medicapital
client/com/medicapital/client/pages/generic/RegisterPage.java
1817
package com.medicapital.client.pages.generic; import static com.medicapital.client.log.Tracer.tracer; import com.medicapital.client.doctor.CreateDoctorPresenter; import com.medicapital.client.doctor.DoctorFactory; import com.medicapital.client.pages.Page; import com.medicapital.client.user.CreateUserForm; import com.medicapital.client.user.CreateUserPresenter; import com.medicapital.client.user.UserFactory; final public class RegisterPage extends Page<RegisterPageForm> { public static final String PAGE_NAME = "Register"; private CreateUserPresenter registerUserPresenter; private CreateDoctorPresenter registerDoctorPresenter; @Override protected RegisterPageForm createPageView() { return new RegisterPageForm(); } @Override protected void initPage(RegisterPageForm pageView) { registerUser(); } final public void registerUser() { tracer(this).debug("Showing register user view..."); final UserFactory userFactory = new UserFactory(); CreateUserForm userView = getPageView().getUserView(); registerUserPresenter = userFactory.createCreateUserPresenter(userView, userView); getPageView().getPagePanel().clear(); getPageView().getPagePanel().add(registerUserPresenter.getEntityPresenterView().asWidget()); getPresenters().add(registerUserPresenter); } final public void registerDoctor() { tracer(this).debug("Showing register doctor view..."); final DoctorFactory doctorFactory = new DoctorFactory(); registerDoctorPresenter = doctorFactory.createCreateDoctorPresenter(getPageView().getDoctorView(), getPageView().getDoctorView()); getPageView().getPagePanel().clear(); getPageView().getPagePanel().add(registerDoctorPresenter.getEntityPresenterView().asWidget()); getPresenters().add(registerDoctorPresenter); } }
mit
fieldenms/tg
platform-pojo-bl/src/main/java/ua/com/fielden/platform/sample/domain/TgMachine.java
2489
package ua.com.fielden.platform.sample.domain; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import ua.com.fielden.platform.entity.annotation.Calculated; import ua.com.fielden.platform.entity.annotation.CompanionObject; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.MapEntityTo; import ua.com.fielden.platform.entity.annotation.MapTo; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.entity.annotation.Readonly; import ua.com.fielden.platform.entity.annotation.Title; import ua.com.fielden.platform.entity.query.model.ExpressionModel; import ua.com.fielden.platform.gis.gps.AbstractAvlMachine; /** * Master entity object. * * @author Developers * */ @CompanionObject(ITgMachine.class) @MapEntityTo public class TgMachine extends AbstractAvlMachine<TgMessage> { @IsProperty @MapTo @Title(value = "Орг. підрозділ", desc = "Організаційний підрозділ, до якого належить машина") private TgOrgUnit orgUnit; @IsProperty(linkProperty = "machine") @Readonly @Calculated @Title(value = "Останнє GPS повідомлення", desc = "Містить інформацію про останнє GPS повідомлення, отримане від GPS модуля.") private TgMessage lastMessage; private static ExpressionModel lastMessage_ = expr().model( select(TgMessage.class) .where().prop(TgMessage.MACHINE_PROP_ALIAS).eq().extProp("id") .and().notExists( select(TgMessage.class) .where().prop(TgMessage.MACHINE_PROP_ALIAS).eq().extProp(TgMessage.MACHINE_PROP_ALIAS) .and().prop("gpsTime").gt().extProp("gpsTime").model() ) .model() ).model(); @Observable public TgMachine setOrgUnit(final TgOrgUnit orgUnit) { this.orgUnit = orgUnit; return this; } public TgOrgUnit getOrgUnit() { return orgUnit; } @Override @Observable public TgMachine setLastMessage(final TgMessage lastMessage) { this.lastMessage = lastMessage; return this; } @Override public TgMessage getLastMessage() { return lastMessage; } }
mit
Qhongk/rsite
rsite-api/src/main/java/com/kza/rsite/service/LoggerService.java
305
package com.kza.rsite.service; import com.kza.common.annotations.Logged; import org.springframework.stereotype.Component; /** * Created by kza on 2015/9/17. */ @Component public class LoggerService { @Logged public String logged(String str1, String str2) { return str1 + str2; } }
mit
cmihail/WebServer
src/server/client/Client.java
388
package server.client; /** * Defines a client information. * * For now, the server doesn't need any client related information, * so this class is used only for logging. * * @author cmihail */ public class Client { private long id; public Client() { this.id = Thread.currentThread().getId(); } @Override public String toString() { return "<client" + id + ">"; } }
mit
Bryan-0/BagJek
src/enhacore/informatica/Scan.java
1385
package enhacore.informatica; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class Scan extends JFrame { public JPanel contentPane; /** * Create the frame. */ public Scan() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 390, 257); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnNewButton = new JButton("Regresar"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); btnNewButton.setBounds(275, 184, 89, 23); contentPane.add(btnNewButton); JLabel lblAnthropology = new JLabel("Scan:"); lblAnthropology.setFont(new Font("Tahoma", Font.PLAIN, 20)); lblAnthropology.setBounds(155, 24, 63, 30); contentPane.add(lblAnthropology); JLabel lblAntropologa = new JLabel("Examinar"); lblAntropologa.setFont(new Font("Tahoma", Font.PLAIN, 16)); lblAntropologa.setBounds(142, 93, 76, 23); contentPane.add(lblAntropologa); } }
mit
Palmodroid/BestBoard
app/src/main/java/org/lattilad/bestboard/webview/WebViewActivity.java
10964
package org.lattilad.bestboard.webview; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Toast; import org.lattilad.bestboard.Ignition; import org.lattilad.bestboard.R; import org.lattilad.bestboard.debug.Debug; import org.lattilad.bestboard.scribe.Scribe; import java.io.File; /** * Simple webview to show html text * https://developer.chrome.com/multidevice/webview/gettingstarted * * WebView should be retained between activity starts BUT! * WebView contains the context, so simple fragment retention will leak. * Activity should be retained. * http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/ */ public class WebViewActivity extends Activity { // Retained layout elements private WebView webView; private boolean searchBarEnabled = false; private String retainedSearchText = ""; // Changing layout elements private FrameLayout webViewFrame; private ProgressBar progressBar; private RelativeLayout searchBar; private EditText searchText; // Extra of Intents static final public String ASSET = "ASSET"; static final public String FILE = "FILE"; static final public String WORK = "WORK"; static final public String WEB = "WEB"; static final public String SEARCH = "SEARCH"; protected void initContentView( ) { Scribe.locus(Debug.WEBVIEW); setContentView(R.layout.web_view_activity); webViewFrame = (FrameLayout)findViewById(R.id.webViewFrame); progressBar = (ProgressBar) findViewById(R.id.progressBar); // default max value = 100 progressBar.setVisibility( View.GONE ); // Cannot be sure, if page is loaded, so no progress bar is shown after config change searchBar = (RelativeLayout) findViewById(R.id.searchBar); searchText = (EditText) findViewById(R.id.search); // Initialize the WebView at new starts if (webView == null) { // Create the webview webView = new WebView(this); webView.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.getSettings().setSupportZoom(true); webView.getSettings().setBuiltInZoomControls(true); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); webView.getSettings().setLoadsImagesAutomatically(true); webView.getSettings().setDefaultTextEncodingName("utf-8"); // Load the starting page String string = null; Uri uri; // extra: ASSET if ( ( string = getIntent().getStringExtra(ASSET) ) != null ) { string = "file:///android_asset/" + string; } // extra: FILE else if ( ( string = getIntent().getStringExtra(FILE) ) != null && Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED )) { string = Uri.fromFile( new File( Environment.getExternalStorageDirectory(), string ) ).toString(); } // extra: WEB else if ( ( string = getIntent().getStringExtra(WEB) ) != null ) { if (!string.startsWith("https://") && !string.startsWith("http://")) { string = "http://" + string; } } // data: uri else if ( ( uri = getIntent().getData() ) != null ) { string = uri.toString(); } // THIS IS HERE ALSO FOR THE DEFAULT HELP !! // extra: WORK or default help else if ( Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED )) { if ( (string = getIntent().getStringExtra(WORK) ) == null ) string = "help.html"; SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); String directoryName = sharedPrefs.getString( getString( R.string.descriptor_directory_key ), getString( R.string.descriptor_directory_default )); File directoryFile = new File( Environment.getExternalStorageDirectory(), directoryName ); string = Uri.fromFile( new File( directoryFile, string ) ).toString(); } // END FOR DEFAULT HELP !! if ( string != null ) { webView.loadUrl(string); } else { String customHtml = "<html><body>No uri can be found!</body></html>"; webView.loadData(customHtml, "text/html", "UTF-8"); } // extra: SEARCH if ( ( string = getIntent().getStringExtra(SEARCH) ) != null && !string.equals("") ) { retainedSearchText = string; searchBarEnabled = true; } } // Attach the WebView to its placeholder webViewFrame.addView(webView); findViewById(R.id.back).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { webView.findNext(false); // goBack(); } }); findViewById(R.id.forth).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { webView.findNext(true); // goForward(); } }); webView.setWebChromeClient( new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { progressBar.setProgress(progress); // default max value = 100 } }); webView.setWebViewClient( new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(WebViewActivity.this, description, Toast.LENGTH_SHORT).show(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Scribe.locus(Debug.WEBVIEW); progressBar.setVisibility(View.VISIBLE); } // http://stackoverflow.com/a/32720167 @Override public void onPageFinished(WebView view, String url) { Scribe.locus(Debug.WEBVIEW); progressBar.setVisibility(View.GONE); String searchText = WebViewActivity.this.searchText.getText().toString(); if (!searchText.equals("")) { webView.findAllAsync(searchText); } } }); searchText.addTextChangedListener( new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { webView.findAllAsync(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); searchBar.setVisibility(searchBarEnabled ? View.VISIBLE : View.GONE); searchText.setText( retainedSearchText ); } protected void onCreate(Bundle savedInstanceState) { Scribe.locus(Debug.WEBVIEW); // Ignition is needed at every entry points - ?? Egy köztes activity maybe ?? Ignition.start( this ); super.onCreate(savedInstanceState); initContentView(); } @Override public void onConfigurationChanged(Configuration newConfig) { Scribe.locus(Debug.WEBVIEW); if (webView != null) webViewFrame.removeView(webView); retainedSearchText = searchText.getText().toString(); super.onConfigurationChanged(newConfig); initContentView(); } @Override protected void onSaveInstanceState(Bundle outState) { Scribe.locus(Debug.WEBVIEW); super.onSaveInstanceState(outState); // Save the state of the WebView webView.saveState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Scribe.locus(Debug.WEBVIEW); super.onRestoreInstanceState(savedInstanceState); // Restore the state of the WebView webView.restoreState(savedInstanceState); } /** * BACK functions like BACK on the toolbar, but at the last step this BACK can exit */ @Override public void onBackPressed() { if(webView.canGoBack() ) { webView.goBack(); } else { super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ( keyCode == KeyEvent.KEYCODE_MENU ) { if (searchBarEnabled) { searchBarEnabled = false; searchBar.setVisibility(View.GONE); } else { searchBarEnabled = true; searchBar.setVisibility(View.VISIBLE); } return true; } return super.onKeyDown(keyCode, event); } }
mit
niromon/votvot
VoteVoteServer/src/test/java/org/deguet/tests/lab/TestLabSerial.java
1103
package org.deguet.tests.lab; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class TestLabSerial { @Test public void testDeserPoly(){ List<A> list = new ArrayList<A>(); list.add(new A()); list.add(new B()); Gson g = new GsonBuilder().setPrettyPrinting().create(); String json = g.toJson(list); System.out.println(json); List<A> recov = new Gson().fromJson(json, List.class); System.out.println("recov " +recov); for (A a : recov){ System.out.println(a.toString()); } } @Test public void testDeserPoly2(){ Collection collection = new ArrayList(); collection.add("hello"); collection.add(5); collection.add(new int[]{3,4,5}); Gson g = new GsonBuilder().setPrettyPrinting().create(); String json = g.toJson(collection); System.out.println(json); Collection things = g.fromJson(json, Collection.class); System.out.println(things); } }
mit
miky9090/Reflexx
reflexx/src/main/java/reflexx/model/weather/HourlyWeatherData.java
509
package reflexx.model.weather; public class HourlyWeatherData { private String summary; private String icon; private SimpleWeatherData[] data; public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public SimpleWeatherData[] getData() { return data; } public void setData(SimpleWeatherData[] data) { this.data = data; } }
mit
aimbrain/aimbrain-android-sdk
aimbrain/src/main/java/com/aimbrain/sdk/faceCapture/PictureManager.java
3448
package com.aimbrain.sdk.faceCapture; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.util.Base64; import com.aimbrain.sdk.Manager; import com.aimbrain.sdk.faceCapture.views.FaceFinderUtil; import com.aimbrain.sdk.models.StringListDataModel; import com.aimbrain.sdk.server.FaceActions; import com.aimbrain.sdk.util.Logger; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; public class PictureManager { public static final String TAG = PictureManager.class.getSimpleName(); public final static int MAX_PHOTO_HEIGHT = 300; public final static int COMPRESSION_RATIO = 100; public static Bitmap cropBitmap(Bitmap photo) { int photo_w = photo.getWidth(); int photo_h = photo.getHeight(); int box_w = (int) (photo_w * FaceFinderUtil.BOX_WIDTH); int box_h = (int) (FaceFinderUtil.BOX_RATIO * box_w); int p_left = (int) ((photo_w - box_w) / 2 - box_w * 0.1); int p_width = (int) (box_w * 1.2); int p_top = (int) ((photo_h - box_h) / 2 - box_h * 0.1); int p_height = (int) (box_h * 1.2); return Bitmap.createBitmap(photo, p_left, p_top, p_width, p_height); } public static Bitmap adjustSize(Bitmap photo, int maxHeight) { if(photo.getHeight() > maxHeight){ float ratio = (float)photo.getWidth() / (float)photo.getHeight(); return Bitmap.createScaledBitmap(photo, (int) (maxHeight * ratio), maxHeight, false); } return photo; } public static Bitmap rotatePhoto(Bitmap photo, int degrees){ Matrix matrix = new Matrix(); matrix.postRotate(degrees); return Bitmap.createBitmap(photo , 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); } public static StringListDataModel adjustProvidedPhotos(List<Bitmap> photos) { List<String> adjustedPhotos = new ArrayList<>(); for (Bitmap photo : photos) { photo = PictureManager.adjustSize(photo, 300); ByteArrayOutputStream compressedPhotoStream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, PictureManager.COMPRESSION_RATIO, compressedPhotoStream); adjustedPhotos.add(Base64.encodeToString(compressedPhotoStream.toByteArray(), Base64.NO_WRAP)); } StringListDataModel adjustedData = new StringListDataModel(); adjustedData.setData(adjustedPhotos); return adjustedData; } public static String getEncodedCompressedPhoto(Bitmap bmp){ ByteArrayOutputStream compressedPhotoStream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, PictureManager.COMPRESSION_RATIO, compressedPhotoStream); String encodedPhoto = Base64.encodeToString(compressedPhotoStream.toByteArray(), Base64.NO_WRAP); return encodedPhoto; } public static Bitmap getCroppedAndRotatedPhoto(Bitmap bmp) { Bitmap croppedPhoto = null; try { Bitmap adjustedPhoto = PictureManager.rotatePhoto(bmp, -90); adjustedPhoto = PictureManager.cropBitmap(adjustedPhoto); adjustedPhoto = PictureManager.adjustSize(adjustedPhoto, PictureManager.MAX_PHOTO_HEIGHT); croppedPhoto = adjustedPhoto; } catch (Exception e) { Logger.w(TAG, "crop", e); } return croppedPhoto; } }
mit
davidwoods2992/passwordcheck
passwcode.java
6873
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class Password { /** * A custom exception to implicate the requirement of making password. * */ private static class PasswordNotCombinedException extends Exception { private String hint = null; public PasswordNotCombinedException() { super(); } public PasswordNotCombinedException(String hint) { super(hint); this.hint = hint; } public String toString() { return this.hint; } } public static void main(String[] args) { System.out.print("Please enter a word: "); Scanner ss = new Scanner(System.in); String p = ss.nextLine(); Password pp = new Password(); ArrayList<String> senseword = new ArrayList<String>(); senseword.add("abc"); senseword.add("ccc"); senseword.add("222222"); try { pp.checkCombinedPassword(p, 3, senseword); } catch (PasswordNotCombinedException e) { System.out.println(e); } } private final static String[] EASY_WORDS = {"111111", "password", "123456"}; /** * Check all security level, like showed in the following, * and check specific chars that default at the beginning. * return true if the password is satisfied by rules. or false. * @param password: a password from calling method. * @throws PasswordNotCombinedException. */ public void checkCombinedPassword(String password) throws PasswordNotCombinedException { //s1. Check easy rules. Once found the breach, and then throw the exception immediately. //s2. Traversing all the chars one by one in a loop. //s3. Check all the rules with API in the loop. //s4. Once found the breach of password, and then throw the custom Exception immediately after the loop. int strLength = password.length(); if (strLength < 6) throw new PasswordNotCombinedException("The password too short!"); checkWords(password); // This function can be only used in this class. Check the password with specific words in here. mustOneNumberOneUpper(password); // This function can be only used in this class. } /** * Check specific security level * @param password: a password from calling method * @param level: what kind of security level. * 1. Must have at least one upper case letter and Must have at least one number * 2. Must be at least 6 characters * 3. Cannot be one of the specific words * 111111 * password * 123456 * @throws PasswordNotCombinedException * */ public void checkCombinedPassword(String password, int level) throws PasswordNotCombinedException { //s1. see what level do user needs. //s2. go to specific level and check the password with rules. int strLength = password.length(); switch (level) { case 2: if (strLength < 6) throw new PasswordNotCombinedException("The password too short!"); break; case 1: mustOneNumberOneUpper(password); // This function can be only used in this class. break; case 3: checkWords(password); // This function can be only used in this class. // Check the password with default specific words in here. break; default: throw new PasswordNotCombinedException("Sorry, the password is not proper!"); } } /** * Check specific security level * @param password: a password from calling method * @param level: what kind of security level. * 1. Must have at least one upper case letter and Must have at least one number * 2. Must be at least 6 characters * 3. Cannot be one of the specific words * 111111 * password * 123456 * @param specStr exclude specific words * @throws PasswordNotCombinedException * */ public void checkCombinedPassword(String password, int level, List<String> words) throws PasswordNotCombinedException { //s1. see what level do user needs. //s2. go to specific level and check the password with rules. int strLength = password.length(); switch (level) { case 2: if (strLength < 6) throw new PasswordNotCombinedException("The password too short!"); break; case 1: mustOneNumberOneUpper(password); // This function can be only used in this class. break; case 3: checkWords(password, words); // This function can be only used in this class. // Check the password with default specific words in here. break; default: throw new PasswordNotCombinedException("Sorry, the password is not proper!"); } } /** * Check specific security level * @param password: a password from calling method * @param level: what kind of security level. * 1. Must have at least one upper case letter and must have at least one number * 2. Must be at least 6 characters * 3. Cannot be one of the specific words, like * 111111 * password * 123456 * @param specStr exclude specific words * @throws PasswordNotCombinedException * */ public void checkCombinedPassword(String password, int level, String[] words) throws PasswordNotCombinedException { int strLength = password.length(); switch (level) { case 2: if (strLength < 6) throw new PasswordNotCombinedException("The password too short!"); break; case 1: mustOneNumberOneUpper(password); // This function can be only used in this class. break; case 3: checkWords(password, words); // This function can be only used in this class. // Check the password with default specific words in here. break; default: throw new PasswordNotCombinedException("Sorry, the password is not proper!"); } } private void checkWords(String p) throws PasswordNotCombinedException { for (int i = 0; i < EASY_WORDS.length; i ++) { if (p.equalsIgnoreCase(EASY_WORDS[i])) throw new PasswordNotCombinedException("The password cannot be some specific words, like 123456!"); } } private void checkWords(String p, String[] wordsGroups) throws PasswordNotCombinedException { List<String> wordsList = Arrays.asList(wordsGroups); checkWords(p, wordsList); } private void checkWords(String p, List<String> wordsGroups) throws PasswordNotCombinedException { Iterator<String> it = wordsGroups.iterator(); while (it.hasNext()) { if (p.equalsIgnoreCase(it.next())) { throw new PasswordNotCombinedException("The password cannot be some specific words, like 123456!"); } } } private void mustOneNumberOneUpper(String p) throws PasswordNotCombinedException { int hasUpperCases = 0; int hasNumbers = 0; for (int idx = 0; idx < p.length(); idx++) { hasUpperCases += Character.isUpperCase(p.charAt(idx)) ? 1 : 0; hasNumbers += Character.isDigit(p.charAt(idx)) ? 1 : 0; } // end loop. if (hasNumbers == 0 || hasUpperCases == 0) throw new PasswordNotCombinedException("Must contains one Number and one Upper case at least!"); } }
mit
maxifier/cliche-shell
cliche-shell-core/src/main/java/com/maxifier/cliche/CommandNamer.java
3005
/* * This file is part of the Cliche project, licensed under MIT License. * See LICENSE.txt file in root folder of Cliche sources. */ package com.maxifier.cliche; import java.lang.reflect.Method; import java.util.Arrays; /** * This interface is a Strategy for auto-naming commands with no name specified * based on command's method. The algorithm is isolated because it's highly * subjective and therefore subject to changes. And, if you don't like * default dash-joined naming you can completely redefine the functionality. * * It is also responsible for generating several suggested abbreviations, * one from them may later be "approved" by CommandTable. * * @author ASG */ public interface CommandNamer { /** * Generate command name and suggested abbreviation variants. * Since this method is given a Method, not a string, the algorithm can * take parameter types into account. * * @param commandMethod Command method * @return asg.cliche.CommandNamer.NamingInfo containing generated name and abbrev array. */ NamingInfo nameCommand(Method commandMethod); /** * Return value grouping structure for nameCommand(). * I decided to return name and abbreviations together because in the default * algorithm they are generated simultaneously, and I think this approach is * better than having a stateful strategy. */ public static class NamingInfo { public final String commandName; public final String[] possibleAbbreviations; public NamingInfo(String commandName, String[] possibleAbbreviations) { this.commandName = commandName; this.possibleAbbreviations = possibleAbbreviations; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NamingInfo other = (NamingInfo)obj; if ((this.commandName == null) ? (other.commandName != null) : !this.commandName.equals(other.commandName)) { return false; } if (this.possibleAbbreviations != other.possibleAbbreviations && (this.possibleAbbreviations == null || !Arrays.equals(this.possibleAbbreviations, other.possibleAbbreviations))) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 59 * hash + (this.commandName != null ? this.commandName.hashCode() : 0); hash = 59 * hash + (this.possibleAbbreviations != null ? Arrays.hashCode(this.possibleAbbreviations) : 0); return hash; } @Override public String toString() { return String.format("NamingInfo(%s, %s)", commandName, Arrays.toString(possibleAbbreviations)); } } }
mit
wslyy99/springmvc-wang
common-wang/wang-common-core/src/main/java/com/wang/common/zookeeper/ParamManaService.java
4983
/** * @Title: ParamManaService.java * @Package com.dowin.param * @Description: 从zookeeper中取出参数数据并转化成javabean存入内存 * @author administrator * @date 2016年5月23日 下午1:32:40 * @version V1.0 * Update Logs: * **************************************************** * Name: * Date: * Description: ****************************************************** */ package com.wang.common.zookeeper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.wang.common.resource.ResourcesUtils; /** * @ClassName: ParamManaService * @Description: 从zookeeper中取出参数数据并转化成javabean存入内存 * @author administrator * @param <T> * @date 2016年5月23日 下午1:32:40 * */ public class ParamManaService<T> { private org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(this.getClass()); public Map<String, List<T>> cachObject = new HashMap<String, List<T>>(); /** * @Title: ParseZookToBean * @Description: 获取zookeeper中的参数数据转换成对应的javabean然后存入内存中 * @author administrator 2016年5月21日 下午12:21:30 * @return * @throws Exception * @throws */ public Map<String, String> ParseZookToBean() throws Exception { logger.debug("1.从zookeeper中读取参数表名和参数值;2.根据表名字符串获取参数bean对象,并将相应的参数数据存入该对象"); Map<String, String> mapResult = new HashMap<String, String>();// 返回结果信息 String paramPath = ResourcesUtils.bundle_service .getString("CURATOR_WATCH_PATH");// 参数在zookeeper中的父节点 Map<String, Object> map = CuratorUtils.getChildren(paramPath);// 从zookeeper中获取参数的节点,即配置文件中table属性的名称 if (map.containsKey("FAILURE")) { mapResult.put("FAILURE", map.get("FAILURE").toString()); logger.debug(map.get("FAILURE").toString()); return mapResult; } List<String> paramNodeList = (List<String>) map.get("SUCCESS"); if (paramNodeList == null) { mapResult.put("FAILURE", "该节点下没有子节点"); logger.debug("该节点下没有子节点"); return mapResult; } System.out.println("获取到的参数包括:" + paramNodeList.toString()); ParseZookToBeanProcess(paramNodeList, paramPath); mapResult.put("SUCCESS", "解析成功"); return mapResult; } /** * @Title: ParseZookToBeanProcess * @Description: 将参数数据转换成javabean对象并存入内存 * @author administrator 2016年5月21日 下午2:17:11 * @param paramNodeList * 在zeekeeper中参数的节点 * @param paramPath * 参数在zeekeeper中的路径 * @throws Exception * @throws */ public void ParseZookToBeanProcess(List<String> paramNodeList, String paramPath) throws Exception { Map<String, List<T>> cachObject = new HashMap<String, List<T>>(); List<T> listObject = new ArrayList<T>(); String beanPackage = ResourcesUtils.bundle_service .getString("CURATOR_BEAN_PACKAGE");// 对应参数表的bean所在包名 logger .debug("遍历参数节点,根据节点名称反射到程序中对应的bean,并分别从zookeeper中取出对应的参数数据赋值给javabean"); for (String node : paramNodeList) { Class<?> className = Class.forName(beanPackage.concat(".").concat( node));// 通过参数bean所在的包名和bean的名称实例化相应的javabean对象 cachObject.put(node, (List<T>) ParseBeanGeneric(className, paramPath, node)); } this.cachObject = cachObject; } /** * @Title: ParseBeanGeneric * @Description: 读取zookee中的参数数据赋值给对应的javabean * @author administrator 2016年5月23日 下午2:47:15 * @param model * javabean实体类 * @param paramPath * 参数节点路径 * @param node * @return * @throws Exception * @throws */ public <T> List<T> ParseBeanGeneric(T model, String paramPath, String node) throws Exception { List<T> listObject = new ArrayList<T>(); String readResult = CuratorUtils.read( paramPath.concat("/").concat(node)).get("SUCCESS");// 读取参数数据 Object[] jsonArray = JSON.parseArray(readResult).toArray();// 转换成JSON数组 for (int item = 0; item < jsonArray.length; item++)// 遍历JSON数组给javabean赋值 { // System.out.println(jsonArray[item].toString()); T parseObject = (T) JSON.parseObject(jsonArray[item].toString()); listObject.add(parseObject); } return listObject; } }
mit
bartsch-dev/jabref
src/main/java/org/jabref/gui/groups/UndoableModifyGroup.java
1785
package org.jabref.gui.groups; import java.util.List; import org.jabref.gui.undo.AbstractUndoableJabRefEdit; import org.jabref.logic.l10n.Localization; import org.jabref.model.groups.AbstractGroup; import org.jabref.model.groups.GroupTreeNode; class UndoableModifyGroup extends AbstractUndoableJabRefEdit { private final GroupSelector groupSelector; private final AbstractGroup m_oldGroupBackup; private final AbstractGroup m_newGroupBackup; private final GroupTreeNode m_groupsRootHandle; private final List<Integer> m_pathToNode; /** * @param node * The node which still contains the old group. * @param newGroup * The new group to replace the one currently stored in <b>node * </b>. */ public UndoableModifyGroup(GroupSelector gs, GroupTreeNodeViewModel groupsRoot, GroupTreeNodeViewModel node, AbstractGroup newGroup) { groupSelector = gs; m_oldGroupBackup = node.getNode().getGroup().deepCopy(); m_newGroupBackup = newGroup.deepCopy(); m_pathToNode = node.getNode().getIndexedPathFromRoot(); m_groupsRootHandle = groupsRoot.getNode(); } @Override public String getPresentationName() { return Localization.lang("modify group"); } @Override public void undo() { super.undo(); //TODO: NULL m_groupsRootHandle.getDescendant(m_pathToNode).get().setGroup( m_oldGroupBackup.deepCopy()); groupSelector.revalidateGroups(); } @Override public void redo() { super.redo(); m_groupsRootHandle.getDescendant(m_pathToNode).get().setGroup( m_newGroupBackup.deepCopy()); groupSelector.revalidateGroups(); } }
mit
JCThePants/NucleusFramework
src/com/jcwhatever/nucleus/utils/observer/future/FutureResultAgent.java
14890
/* * This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.nucleus.utils.observer.future; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.observer.ISubscriber; import com.jcwhatever.nucleus.utils.observer.SubscriberAgent; import com.jcwhatever.nucleus.utils.observer.update.NamedUpdateAgents; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; /** * Used for returning asynchronous results from a method. * * @see FutureResultSubscriber * @see IFutureResult */ public class FutureResultAgent<R> extends SubscriberAgent { private final FutureResult<R> _future; private final NamedUpdateAgents _updateAgents = new NamedUpdateAgents(); private Result<R> _finalResult; private boolean _hasFutureSubscribers; /** * Create a new agent and immediately create a success result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> successResult() { return new FutureResultAgent<T>().success(); } /** * Create a new agent and immediately create a success result. * * @param result The result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> successResult(@Nullable T result) { return new FutureResultAgent<T>().success(result); } /** * Create a new agent and immediately create a success result. * * @param result The result. * @param message The result message. * @param args Optional message format arguments. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> successResult(@Nullable T result, CharSequence message, Object... args) { return new FutureResultAgent<T>().success(result, message, args); } /** * Create a new agent and immediately create a cancel result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> cancelResult() { return new FutureResultAgent<T>().cancel(); } /** * Create a new agent and immediately create a cancel result. * * @param result The result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> cancelResult(@Nullable T result) { return new FutureResultAgent<T>().cancel(result); } /** * Create a new agent and immediately create a cancel result. * * @param result The result. * @param message The result message. * @param args Optional message format arguments. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> cancelResult(@Nullable T result, CharSequence message, Object... args) { return new FutureResultAgent<T>().cancel(result, message, args); } /** * Create a new agent and immediately create an error result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> errorResult() { return new FutureResultAgent<T>().error(); } /** * Create a new agent and immediately create an error result. * * @param result The result. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> errorResult(@Nullable T result) { return new FutureResultAgent<T>().error(result); } /** * Create a new agent and immediately create an error result. * * @param result The result. * @param message The result message. * @param args Optional message format arguments. * * @param <T> The result type. * * @return The future result. */ public static <T> IFutureResult<T> errorResult(@Nullable T result, CharSequence message, Object... args) { return new FutureResultAgent<T>().error(result, message, args); } /** * Constructor. */ public FutureResultAgent() { _future = new FutureResult<>(this); } @Override public boolean hasSubscribers() { return _hasFutureSubscribers || super.hasSubscribers(); } /** * Send result to subscribers. * * @param result The result. */ public void sendResult(Result<R> result) { PreCon.notNull(result); _finalResult = result; if (!hasSubscribers()) return; if (result.isSuccess()) { sendSuccess(result); } else if (result.isComplete()) { if (result.isCancelled()) { sendCancel(result); } else { sendError(result); } } else { List<ISubscriber> list = new ArrayList<>(subscribers()); for (ISubscriber subscriber : list) { if (subscriber instanceof FutureResultSubscriber) { //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).on(result); } } _updateAgents.update("onResult", result); } } /** * Declare the result cancelled. * * <p>The same as invoking {@link #sendResult} with a generic * cancel result.</p> * * <p>The result object and message are null.</p> * * @return The agents future. */ public FutureResult<R> cancel() { return cancel(null, null); } /** * Declare the result cancelled. * * <p>The same as invoking {@link #sendResult} with a generic * cancel result.</p> * * <p>The result message is null.</p> * * @param result The result object. * * @return The agents future. */ public FutureResult<R> cancel(@Nullable R result) { return cancel(result, null); } /** * Declare the result cancelled. * * <p>The same as calling {@link #sendResult} with a generic * cancel result.</p> * * @param result The result object. * @param message The message to send with the result. * @param args Optional message format arguments. * * @return The agents future. */ public FutureResult<R> cancel(@Nullable R result, @Nullable CharSequence message, Object... args) { sendResult(new ResultBuilder<R>() .cancel() .result(result) .message(message, args) .build()); return getFuture(); } /** * Declare an error in the result. * * <p>The same as invoking {@link #sendResult} with a generic * error result.</p> * * <p>The result object and message are null.</p> * * @return The agents future. */ public FutureResult<R> error() { return error(null, null); } /** * Declare an error in the result. * * <p>The same as invoking {@link #sendResult} with a generic * error result.</p> * * <p>The result message is null.</p> * * @param result The result object. * * @return The agents future. */ public FutureResult<R> error(@Nullable R result) { return error(result, null); } /** * Declare an error in the result. * * <p>The same as invoking {@link #sendResult} with a generic * error result.</p> * * @param result The result object. * @param message The message to send with the result. * @param args Optional message format arguments. * * @return The agents future. */ public FutureResult<R> error(@Nullable R result, @Nullable CharSequence message, Object... args) { sendResult(new ResultBuilder<R>() .error() .result(result) .message(message, args) .build()); return getFuture(); } /** * Declare the result a success. * * <p>The same as invoking {@link #sendResult} with a generic * success result.</p> * * <p>The result object and message are null.</p> * * @return The agents future. */ public FutureResult<R> success() { return success(null, null); } /** * Declare the result a success. * * <p>The same as invoking {@link #sendResult} with a generic * success result.</p> * * <p>The result message is null.</p> * * @param result The result object. * * @return The agents future. */ public FutureResult<R> success(@Nullable R result) { return success(result, null); } /** * Declare the result a success. * * <p>The same as invoking {@link #sendResult} with a generic * success result.</p> * * @param result The result object. * @param message The message to send with the result. * @param args Optional message format arguments. * * @return The agents future. */ public FutureResult<R> success(@Nullable R result, @Nullable CharSequence message, Object... args) { sendResult(new ResultBuilder<R>() .success() .result(result) .message(message, args) .build()); return getFuture(); } /** * Get a future that can be returned so that a method caller can * attach {@link com.jcwhatever.nucleus.utils.observer.update.IUpdateSubscriber}'s. */ public FutureResult<R> getFuture() { return _future; } protected void sendSuccess(Result<R> result) { _updateAgents.update("onSuccess", result); List<ISubscriber> list = new ArrayList<>(subscribers()); for (ISubscriber subscriber : list) { if (subscriber instanceof FutureResultSubscriber) { //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).onSuccess(result); //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).on(result); } } } protected void sendError(Result<R> result) { _updateAgents.update("onError", result); List<ISubscriber> list = new ArrayList<>(subscribers()); for (ISubscriber subscriber : list) { if (subscriber instanceof FutureResultSubscriber) { //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).onError(result); //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).on(result); } } } protected void sendCancel(Result<R> result) { _updateAgents.update("onCancel", result); List<ISubscriber> list = new ArrayList<>(subscribers()); for (ISubscriber subscriber : list) { if (subscriber instanceof FutureResultSubscriber) { //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).onCancel(result); //noinspection unchecked ((FutureResultSubscriber<R>) subscriber).on(result); } } } private static class FutureResult<R> implements IFutureResult<R> { FutureResultAgent<R> parent; private FutureResult(FutureResultAgent<R> parent) { this.parent = parent; } @Override public FutureResult<R> onResult(FutureResultSubscriber<R> subscriber) { PreCon.notNull(subscriber); if (parent._finalResult != null) subscriber.on(parent._finalResult); parent.addSubscriber(subscriber); parent._hasFutureSubscribers = true; return this; } @Override public FutureResult<R> onSuccess(FutureResultSubscriber<R> subscriber) { PreCon.notNull(subscriber); addSubscriber("onSuccess", subscriber); if (parent._finalResult != null && parent._finalResult.isSuccess()) { subscriber.onSuccess(parent._finalResult); subscriber.on(parent._finalResult); } return this; } @Override public FutureResult<R> onCancel(FutureResultSubscriber<R> subscriber) { PreCon.notNull(subscriber); addSubscriber("onCancel", subscriber); if (parent._finalResult != null && parent._finalResult.isCancelled()) { subscriber.onCancel(parent._finalResult); subscriber.on(parent._finalResult); } return this; } @Override public FutureResult<R> onError(FutureResultSubscriber<R> subscriber) { PreCon.notNull(subscriber); addSubscriber("onError", subscriber); if (parent._finalResult != null && !parent._finalResult.isSuccess() && !parent._finalResult.isCancelled()) { subscriber.onError(parent._finalResult); subscriber.on(parent._finalResult); } return this; } private void addSubscriber(String agentName, FutureResultSubscriber<R> subscriber) { parent._updateAgents.getAgent(agentName).addSubscriber(subscriber); parent._hasFutureSubscribers = true; } } }
mit
jenkinsci/pretested-integration-plugin
src/main/java/org/jenkinsci/plugins/pretestedintegration/scm/git/PretestedIntegrationSCMTrait.java
905
package org.jenkinsci.plugins.pretestedintegration.scm.git; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import jenkins.plugins.git.traits.GitSCMExtensionTrait; import jenkins.plugins.git.traits.GitSCMExtensionTraitDescriptor; import org.jenkinsci.plugins.pretestedintegration.IntegrationStrategy; import org.kohsuke.stapler.DataBoundConstructor; import javax.annotation.Nonnull; public class PretestedIntegrationSCMTrait extends GitSCMExtensionTrait<PretestedIntegrationAsGitPluginExt> { @DataBoundConstructor public PretestedIntegrationSCMTrait(PretestedIntegrationAsGitPluginExt extension) { super(extension); } @Extension public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { @Nonnull @Override public String getDisplayName() { return "Use pretested integration"; } } }
mit
soldom/sensory-data-grapher
Sensory Data Grapher/src/view/PlotSettingsPanel.java
7338
package view; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Observable; import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.xml.stream.XMLStreamException; import model.Model; import controller.Controller; public class PlotSettingsPanel extends JPanel implements ActionListener, ItemListener { private static final long serialVersionUID = 1L; private Controller controller; private JLabel lbXaxis = new JLabel("X- Axis"); private JLabel lbXfrom = new JLabel("from:"); private JTextField txtXfrom = new JTextField("0"); private JLabel lbXto = new JLabel("to:"); private JTextField txtXto = new JTextField("50"); private JLabel lbYaxis = new JLabel("Y- Axis"); private JTextField txtYfrom = new JTextField("-5"); private JLabel lbYfrom = new JLabel("from:"); private JTextField txtYto = new JTextField("5"); private JLabel lbYto = new JLabel("to:"); private JCheckBox cbxXautoScale = new JCheckBox("Auto Scale", true); private JCheckBox cbxYautoScale = new JCheckBox("Auto Scale", true); private JButton btPlot = new JButton("Plot"); private JButton btSaveAsXml = new JButton("Save as XML"); private JLabel lbEmpty = new JLabel(); private JFileChooser fs = new JFileChooser(); public PlotSettingsPanel(Controller controller) { setLayout(new GridBagLayout()); setBorder(new TitledBorder(BorderFactory.createEtchedBorder( EtchedBorder.RAISED, Color.white, new Color(165, 163, 151)), " Plot Settings ")); this.controller = controller; btPlot.addActionListener(this); btSaveAsXml.addActionListener(this); cbxXautoScale.addItemListener(this); cbxYautoScale.addItemListener(this); txtXfrom.setEnabled(false); txtXto.setEnabled(false); txtYfrom.setEnabled(false); txtYto.setEnabled(false); add(lbXaxis, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbXfrom, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(txtXfrom, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbXto, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(txtXto, new GridBagConstraints(5, 1, 2, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(cbxXautoScale, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbYaxis, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbYfrom, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(txtYfrom, new GridBagConstraints(1, 4, 3, 1, 1.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbYto, new GridBagConstraints(4, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(txtYto, new GridBagConstraints(5, 4, 2, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(cbxYautoScale, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(btPlot, new GridBagConstraints(6, 6, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(btSaveAsXml, new GridBagConstraints(2, 6, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(lbEmpty, new GridBagConstraints(7, 0, 0, 7, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); } public void actionPerformed(ActionEvent e) { if (e.getSource() == btPlot) { if(!cbxXautoScale.isSelected()) { controller.setxAutoSet(false); controller.setXmin(Double.parseDouble(txtXfrom.getText())); controller.setXmax(Double.parseDouble(txtXto.getText())); } else { controller.setxAutoSet(true); } if(!cbxYautoScale.isSelected()) { controller.setyAutoSet(false); controller.setYmin(Double.parseDouble(txtYfrom.getText())); controller.setYmax(Double.parseDouble(txtYto.getText())); } else { controller.setyAutoSet(true); } controller.setNotifyObserver(); } if (e.getSource() == btSaveAsXml) { int dataSet = fs.showSaveDialog(PlotSettingsPanel.this); if (e.getSource() == btSaveAsXml) { if (dataSet == JFileChooser.APPROVE_OPTION) { File file = fs.getSelectedFile(); System.out.println(file.getPath()); try { controller.setSaveAsXml(file.getPath()); } catch (FileNotFoundException | XMLStreamException e1) { e1.printStackTrace(); } } } } } @Override public void itemStateChanged(ItemEvent e) { if (e.getItemSelectable() == cbxXautoScale) { if (e.getStateChange() == 1) { txtXfrom.setEnabled(false); txtXto.setEnabled(false); controller.setxAutoSet(true); } else { txtXfrom.setEnabled(true); txtXto.setEnabled(true); controller.setxAutoSet(false); try { controller.setXmax(Double.parseDouble(txtXto.getText())); } catch (NumberFormatException e1) { System.out.println("Could not parse xto data"); e1.printStackTrace(); } try { controller.setXmin(Double.parseDouble(txtXfrom.getText())); } catch (NumberFormatException e1) { System.out.println("Could not parse xfrom data"); e1.printStackTrace(); } } } if (e.getItemSelectable() == cbxYautoScale) { if (e.getStateChange() == 1) { txtYfrom.setEnabled(false); txtYto.setEnabled(false); controller.setyAutoSet(true); } else { txtYfrom.setEnabled(true); txtYto.setEnabled(true); controller.setyAutoSet(false); try { controller.setXmax(Double.parseDouble(txtYto.getText())); } catch (NumberFormatException e1) { System.out.println("Could not parse yto data"); e1.printStackTrace(); } try { controller.setXmin(Double.parseDouble(txtYfrom.getText())); } catch (NumberFormatException e1) { System.out.println("Could not parse yfrom data"); e1.printStackTrace(); } } } } public void update(Observable obs, Object arg) { Model model = (Model) obs; if (model.getDataSet1() != null || model.getDataSet2() != null) { txtXfrom.setText(model.getXmin().toString()); txtXto.setText(model.getXmax().toString()); txtYfrom.setText(model.getYmin().toString()); txtYto.setText(model.getYmax().toString()); cbxXautoScale.setSelected(model.getxAutoSet()); cbxYautoScale.setSelected(model.getyAutoSet()); } } }
mit
SumeetMoray/Nearby-Shops-API
src/main/java/org/nearbyshops/ModelEndpoint/ShopItemEndPoint.java
1533
package org.nearbyshops.ModelEndpoint; import org.nearbyshops.Model.ItemCategory; import org.nearbyshops.Model.ShopItem; import java.util.ArrayList; import java.util.List; /** * Created by sumeet on 30/6/16. */ public class ShopItemEndPoint { private Integer itemCount; private Integer offset; private Integer limit; private Integer max_limit; private ArrayList<ShopItem> results; private List<ItemCategory> subcategories; public void setItemCount(Integer itemCount) { this.itemCount = itemCount; } public List<ItemCategory> getSubcategories() { return subcategories; } public void setSubcategories(List<ItemCategory> subcategories) { this.subcategories = subcategories; } public int getItemCount() { return itemCount; } public void setItemCount(int itemCount) { this.itemCount = itemCount; } public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getMax_limit() { return max_limit; } public void setMax_limit(Integer max_limit) { this.max_limit = max_limit; } public ArrayList<ShopItem> getResults() { return results; } public void setResults(ArrayList<ShopItem> results) { this.results = results; } }
mit
zellerdev/jabref
src/main/java/org/jabref/logic/externalfiles/LinkedFileHandler.java
6256
package org.jabref.logic.externalfiles; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.metadata.FilePreferences; import org.jabref.model.util.FileHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LinkedFileHandler { private static final Logger LOGGER = LoggerFactory.getLogger(LinkedFileHandler.class); private final BibDatabaseContext databaseContext; private final FilePreferences filePreferences; private final BibEntry entry; private final LinkedFile fileEntry; public LinkedFileHandler(LinkedFile fileEntry, BibEntry entry, BibDatabaseContext databaseContext, FilePreferences filePreferences) { this.fileEntry = fileEntry; this.entry = entry; this.databaseContext = Objects.requireNonNull(databaseContext); this.filePreferences = Objects.requireNonNull(filePreferences); } public boolean moveToDefaultDirectory() throws IOException { Optional<Path> targetDirectory = databaseContext.getFirstExistingFileDir(filePreferences); if (!targetDirectory.isPresent()) { return false; } Optional<Path> oldFile = fileEntry.findIn(databaseContext, filePreferences); if (!oldFile.isPresent()) { // Could not find file return false; } String targetDirName = ""; if (!filePreferences.getFileDirPattern().isEmpty()) { targetDirName = FileUtil.createDirNameFromPattern(databaseContext.getDatabase(), entry, filePreferences.getFileDirPattern()); } Path targetPath = targetDirectory.get().resolve(targetDirName).resolve(oldFile.get().getFileName()); if (Files.exists(targetPath)) { // We do not overwrite already existing files LOGGER.debug("The file {} would have been moved to {}. However, there exists already a file with that name so we do nothing.", oldFile.get(), targetPath); return false; } else { // Make sure sub-directories exist Files.createDirectories(targetPath.getParent()); } // Move Files.move(oldFile.get(), targetPath); // Update path fileEntry.setLink(relativize(targetPath)); return true; } public boolean renameToSuggestedName() throws IOException { return renameToName(getSuggestedFileName()); } public boolean renameToName(String targetFileName) throws IOException { Optional<Path> oldFile = fileEntry.findIn(databaseContext, filePreferences); if (!oldFile.isPresent()) { // Could not find file return false; } Path newPath = oldFile.get().resolveSibling(targetFileName); String expandedOldFilePath = oldFile.get().toString(); boolean pathsDifferOnlyByCase = newPath.toString().equalsIgnoreCase(expandedOldFilePath) && !newPath.toString().equals(expandedOldFilePath); if (Files.exists(newPath) && !pathsDifferOnlyByCase) { // We do not overwrite files // Since Files.exists is sometimes not case-sensitive, the check pathsDifferOnlyByCase ensures that we // nonetheless rename files to a new name which just differs by case. LOGGER.debug("The file {} would have been moved to {}. However, there exists already a file with that name so we do nothing.", oldFile.get(), newPath); return false; } else { Files.createDirectories(newPath.getParent()); } // Rename Files.move(oldFile.get(), newPath); // Update path fileEntry.setLink(relativize(newPath)); return true; } private String relativize(Path path) { List<Path> fileDirectories = databaseContext.getFileDirectoriesAsPaths(filePreferences); return FileUtil.relativize(path, fileDirectories).toString(); } public String getSuggestedFileName() { String oldFileName = fileEntry.getLink(); String extension = FileHelper.getFileExtension(oldFileName).orElse(fileEntry.getFileType()); return getSuggestedFileName(extension); } public String getSuggestedFileName(String extension) { String targetFileName = FileUtil.createFileNameFromPattern(databaseContext.getDatabase(), entry, filePreferences.getFileNamePattern()).trim() + '.' + extension; // Only create valid file names return FileUtil.getValidFileName(targetFileName); } /** * Check to see if a file already exists in the target directory. Search is not case sensitive. * * @return First identified path that matches an existing file. This name can be used in subsequent calls to * override the existing file. */ public Optional<Path> findExistingFile(LinkedFile flEntry, BibEntry entry, String targetFileName) { // The .get() is legal without check because the method will always return a value. Path targetFilePath = flEntry.findIn(databaseContext, filePreferences) .get().getParent().resolve(targetFileName); Path oldFilePath = flEntry.findIn(databaseContext, filePreferences).get(); //Check if file already exists in directory with different case. //This is necessary because other entries may have such a file. Optional<Path> matchedByDiffCase = Optional.empty(); try (Stream<Path> stream = Files.list(oldFilePath.getParent())) { matchedByDiffCase = stream.filter(name -> name.toString().equalsIgnoreCase(targetFilePath.toString())) .findFirst(); } catch (IOException e) { LOGGER.error("Could not get the list of files in target directory", e); } return matchedByDiffCase; } }
mit
markquinn12/springBoot-JHipster-AJP-Port
src/main/java/mark/quinn/config/metrics/package-info.java
80
/** * Health and Metrics specific code. */ package mark.quinn.config.metrics;
mit
chaos5958/CodeInjection
src/hhyeo_eval/CodeInjector.java
24670
package hhyeo_eval; import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.Local; import soot.PackManager; import soot.PatchingChain; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.Unit; import soot.jimple.AbstractStmtSwitch; import soot.jimple.AssignStmt; import soot.jimple.InvokeExpr; import soot.jimple.InvokeStmt; import soot.jimple.Jimple; import soot.jimple.NullConstant; import soot.jimple.StringConstant; import soot.options.Options; import soot.LongType; import soot.Value; import soot.util.Chain; public class CodeInjector { private static int Local_index = 0; private static Value Request, Response; private static Local RequestUrl; private static Local ResponseUrl; private static Local InternalMP; // MP = mediaplayer private static Local InternalMP_CB; public static void main(String[] args) { Options.v().set_src_prec(Options.src_prec_apk); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_dex); // resolve several classes Scene.v().addBasicClass("android.util.Log", SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.System", SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.Long", SootClass.SIGNATURES); Scene.v().addBasicClass("java.lang.String", SootClass.SIGNATURES); Scene.v().addBasicClass("com.squareup.okhttp.Request", SootClass.SIGNATURES); PackManager.v().getPack("jtp").add(new Transform("jtp.myInstrumenter", new BodyTransformer() { @Override protected void internalTransform(final Body b, String phaseName, @SuppressWarnings("rawtypes") Map options) { final PatchingChain<Unit> units = b.getUnits(); // important to use snapshotIterator here for (Iterator<Unit> iter = units.snapshotIterator(); iter.hasNext();) { final Unit u = iter.next(); u.apply(new AbstractStmtSwitch() { public void caseAssignStmt(AssignStmt stmt) { //image - piacasso library (using okhttp library) if (stmt.containsInvokeExpr() && b.getMethod().getDeclaringClass().toString().equals("com.squareup.picasso.OkHttpDownloader") && b.getMethod().getSignature().equals("<com.squareup.picasso.OkHttpDownloader: com.squareup.picasso.Downloader$Response load(android.net.Uri,int)>")) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); if (invokeExpr.getMethod().getSignature().equals("<com.squareup.okhttp.Call: com.squareup.okhttp.Response execute()>")) { //log okhttp request, response message and latency log_okhttp(b, units, u, stmt, "CodeInjector_com.squareup.picasso.OkHttpDownloader"); // check that we did not mess up the Jimple b.validate(); } /* get okhttp request message */ else if (invokeExpr.getMethod().getSignature().equals ("<com.squareup.okhttp.Request$Builder: com.squareup.okhttp.Request build()>")) { Request = stmt.getLeftOp(); } } //metadata - bbc code (using okhttp library) else if (stmt.containsInvokeExpr() && b.getMethod().getDeclaringClass().toString().equals("bbc.mobile.news.v3.common.net.DownloadManager") && b.getMethod().getSignature().equals("<bbc.mobile.news.v3.common.net.DownloadManager: bbc.mobile.news.v3.common.net.DownloadManager$DownloadResponse openSync(java.net.URL,java.util.Map)>")) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); //case 1: execute method: send a request message and get the corresponding response message if (invokeExpr.getMethod().getSignature().equals("<com.squareup.okhttp.Call: com.squareup.okhttp.Response execute()>")) { //log okhttp request, response message and latency log_okhttp(b, units, u, stmt, "CodeInjector_bbc.mobile.news.v3.common.net.DownloadManager"); // check that we did not mess up the Jimple b.validate(); } /* get okhttp request message */ else if (invokeExpr.getMethod().getSignature().equals ("<com.squareup.okhttp.Request$Builder: com.squareup.okhttp.Request build()>")) { Request = stmt.getLeftOp(); } } //json for media - bbc code (using okhttp library) else if (stmt.containsInvokeExpr() && b.getMethod().getDeclaringClass().toString().equals("bbc.mobile.news.v3.media.MediaSelectorTask") && b.getMethod().getSignature().equals("<bbc.mobile.news.v3.media.MediaSelectorTask: bbc.mobile.news.v3.media.MediaSelectorResultsModel work()>")) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); //case 1: execute method: send a request message and get the corresponding response message if (invokeExpr.getMethod().getSignature().equals("<com.squareup.okhttp.Call: com.squareup.okhttp.Response execute()>")) { //log okhttp request, response message and latency log_okhttp(b, units, u, stmt, "bbc.mobile.news.v3.media.MediaSelectorTask"); // check that we did not mess up the Jimple b.validate(); } /* get okhttp request message */ else if (invokeExpr.getMethod().getSignature().equals ("<com.squareup.okhttp.Request$Builder: com.squareup.okhttp.Request build()>")) { Request = stmt.getLeftOp(); } } } public void caseInvokeStmt(InvokeStmt stmt) { if (b.getMethod().getDeclaringClass().toString().equals("bbc.mobile.news.v3.media.InternalMediaPlayer") && b.getMethod().getSignature().equals("<bbc.mobile.news.v3.media.InternalMediaPlayer: void play(java.lang.String,boolean)>")) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); //case 1: execute method: send a request message and get the corresponding response message if (invokeExpr.getMethod().getSignature().equals("<android.media.MediaPlayer: void prepareAsync()>")) { //get a media Url Chain<Local> Locals = b.getLocals(); for (Iterator<Local> iter = Locals.snapshotIterator(); iter.hasNext();) { final Local u = iter.next(); if (u.getName().equals("$r1") && u.getType().toString().equals("java.lang.String")) { RequestUrl = u; break; } } //log a request Url and time final String AppLogKey = "CodeInjector_bbc.mobile.news.v3.media.InternalMediaPlayer"; log_mediarequest (b, units, u, AppLogKey, RequestUrl, true); // check that we did not mess up the Jimple b.validate(); } } else if (b.getMethod().getDeclaringClass().toString().equals("bbc.mobile.news.v3.media.InternalMediaPlayer$Callbacks") && b.getMethod().getSignature().equals("<bbc.mobile.news.v3.media.InternalMediaPlayer$Callbacks: void onPrepared(android.media.MediaPlayer)>")) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); System.out.println("find" + invokeExpr.getMethod().getSignature()); //case 1: execute method: send a request message and get the corresponding response message if (invokeExpr.getMethod().getSignature().equals("<bbc.mobile.news.v3.media.InternalMediaPlayer: void resume()>")) { //get a media Url and InternalMediaPlayer Chain<Local> Locals = b.getLocals(); for (Iterator<Local> iter = Locals.snapshotIterator(); iter.hasNext();) { final Local u = iter.next(); if (u.getName().equals("$r4") && u.getType().toString().equals("java.lang.String")) ResponseUrl = u; else if (u.getName().equals("$r2") && u.getType().toString().equals("bbc.mobile.news.v3.media.InternalMediaPlayer")) InternalMP = u; else if (u.getName().equals("$r0") && u.getType().toString().equals("bbc.mobile.news.v3.media.InternalMediaPlayer$Callbacks")) InternalMP_CB = u; } //log a request Url and time final String AppLogKey = "CodeInjector_bbc.mobile.news.v3.media.InternalMediaPlayer$Callbacks"; log_mediaresponse (b, units, u, AppLogKey, InternalMP_CB, InternalMP, ResponseUrl, false); // check that we did not mess up the Jimple b.validate(); } } } }); } } })); soot.Main.main(args); } private static Local addTmpThrowable(Body body) { Local tmpThrowable = Jimple.v().newLocal("tmpThrowable", RefType.v("java.lang.Throwable")); body.getLocals().add(tmpThrowable); return tmpThrowable; } private static Local addTmpName(Body body) { Local tmpString = Jimple.v().newLocal("tmpAppname", RefType.v("java.lang.String")); body.getLocals().add(tmpString); return tmpString; } private static Local addTmpMessage(Body body) { String Local_name = "tmpMessage" + String.valueOf(Local_index); Local tmpString = Jimple.v().newLocal(Local_name, RefType.v("java.lang.String")); body.getLocals().add(tmpString); Local_index++; return tmpString; } private static Local addTmpTime(Body body) { Local tmpLong = Jimple.v().newLocal("tmpTime", RefType.v("java.lang.Long")); body.getLocals().add(tmpLong); return tmpLong; } private static Local addTmpTime_prim(Body body) { String Local_name = "tmpTime_prim" + String.valueOf(Local_index); Local tmpLong_prim = Jimple.v().newLocal(Local_name, LongType.v()); body.getLocals().add(tmpLong_prim); Local_index++; return tmpLong_prim; } private static Local addTmpRequest(Body body) { Local tmpRequest = Jimple.v().newLocal("tmpRequest", RefType.v("com.squareup.okhttp.Request")); body.getLocals().add(tmpRequest); return tmpRequest; } private static Local addTmpResponse(Body body) { Local tmpResponse = Jimple.v().newLocal("tmpResponse", RefType.v("com.squareup.okhttp.Response")); body.getLocals().add(tmpResponse); return tmpResponse; } private static Local addTmpInternalMP(Body body) { Local tmpInternalMP = Jimple.v().newLocal("tmpInternalMediaPlayer", RefType.v("bbc.mobile.news.v3.media.InternalMediaPlayer")); body.getLocals().add(tmpInternalMP); return tmpInternalMP; } private static void log_okhttp (Body b, PatchingChain<Unit> units, Unit u, AssignStmt stmt, String AppLogKey) { // Locals to inject Local tmpThrowable = addTmpThrowable(b); Local tmpAppName = addTmpName(b); Local tmpMessage = addTmpMessage(b); Local logMessage = addTmpMessage(b); Local spaceMessage = addTmpMessage(b); Local indexMessage = addTmpMessage(b); Local tmpTime = addTmpTime(b); Local tmpReqTime = addTmpTime_prim(b); Local tmpResTime = addTmpTime_prim(b); Local tmpLatency = addTmpTime_prim(b); Local tmpRequest = addTmpRequest(b); Local tmpResponse = addTmpResponse(b); // get sootMethod to use SootMethod to_log = Scene.v().getSootClass("android.util.Log") .getMethod("int e(java.lang.String,java.lang.String,java.lang.Throwable)"); SootMethod to_curr_time = Scene.v().getSootClass("java.lang.System") .getMethod("long currentTimeMillis()"); SootMethod to_toString = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.String toString(long)"); SootMethod to_longValue = Scene.v().getSootClass("java.lang.Long") .getMethod("long longValue()"); SootMethod to_valueOf = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.Long valueOf(long)"); SootMethod to_toString_okhttpreq = Scene.v().getSootClass("com.squareup.okhttp.Request") .getMethod("java.lang.String toString()"); SootMethod to_toString_okhttpres = Scene.v().getSootClass("com.squareup.okhttp.Response") .getMethod("java.lang.String toString()"); SootMethod to_concat = Scene.v().getSootClass("java.lang.String") .getMethod("java.lang.String concat(java.lang.String)"); //get a http response message Response = stmt.getLeftOp(); //before execute //1. setup metadatas for log units.insertBefore(Jimple.v().newAssignStmt(tmpThrowable, NullConstant.v()), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, StringConstant.v("")), u); units.insertBefore(Jimple.v().newAssignStmt(spaceMessage, StringConstant.v(" ")), u); //2. log a okhttp request message units.insertBefore(Jimple.v().newAssignStmt(tmpRequest, Request), u); units.insertBefore(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newVirtualInvokeExpr(tmpRequest, to_toString_okhttpreq.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("1)okhttp_request: ")), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); //3. measure time before execute method (msec) units.insertBefore(Jimple.v().newAssignStmt(tmpAppName, StringConstant.v(AppLogKey + ":request")), u); units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newStaticInvokeExpr(to_curr_time.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpTime, Jimple.v().newStaticInvokeExpr(to_valueOf.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newVirtualInvokeExpr(tmpTime, to_longValue.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newStaticInvokeExpr(to_toString.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(to_log.makeRef(), tmpAppName, tmpMessage, tmpThrowable)), u); //after execute (reverser order) //1. log latency and print all information in android.utils.log units.insertAfter(Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(to_log.makeRef(), tmpAppName, logMessage, tmpThrowable)), u); units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("3)latency time(msec): ")), u); units.insertAfter(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newStaticInvokeExpr(to_toString.makeRef(), tmpLatency)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpLatency, Jimple.v().newVirtualInvokeExpr(tmpTime, to_longValue.makeRef())), u); units.insertAfter(Jimple.v().newAssignStmt(tmpTime, Jimple.v().newStaticInvokeExpr(to_valueOf.makeRef(), tmpLatency)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpLatency, Jimple.v().newSubExpr(tmpResTime, tmpReqTime)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpAppName, StringConstant.v(AppLogKey)), u); //2. log a http response message units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertAfter(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("2)okhttp_response: ")), u); units.insertAfter(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newVirtualInvokeExpr(tmpResponse, to_toString_okhttpres.makeRef())), u); units.insertAfter(Jimple.v().newAssignStmt(tmpResponse, Response), u); //3. measure time after execute method (msec) units.insertAfter(Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(to_log.makeRef(), tmpAppName, tmpMessage, tmpThrowable)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newStaticInvokeExpr(to_toString.makeRef(), tmpResTime)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpResTime, Jimple.v().newVirtualInvokeExpr(tmpTime, to_longValue.makeRef())), u); units.insertAfter(Jimple.v().newAssignStmt(tmpTime, Jimple.v().newStaticInvokeExpr(to_valueOf.makeRef(), tmpResTime)), u); units.insertAfter(Jimple.v().newAssignStmt(tmpResTime, Jimple.v().newStaticInvokeExpr(to_curr_time.makeRef())), u); units.insertAfter(Jimple.v().newAssignStmt(tmpAppName, StringConstant.v(AppLogKey + ":response")), u); } private static void log_mediarequest (Body b, PatchingChain<Unit> units, Unit u, String AppLogKey, Local mediaUrl, boolean isRequest) { // Locals to inject Local tmpThrowable = addTmpThrowable(b); Local tmpAppName = addTmpName(b); Local tmpMessage = addTmpMessage(b); Local logMessage = addTmpMessage(b); Local spaceMessage = addTmpMessage(b); Local indexMessage = addTmpMessage(b); Local tmpTime = addTmpTime(b); Local tmpReqTime = addTmpTime_prim(b); // get sootMethod to use SootMethod to_log = Scene.v().getSootClass("android.util.Log") .getMethod("int e(java.lang.String,java.lang.String,java.lang.Throwable)"); SootMethod to_curr_time = Scene.v().getSootClass("java.lang.System") .getMethod("long currentTimeMillis()"); SootMethod to_toString = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.String toString(long)"); SootMethod to_longValue = Scene.v().getSootClass("java.lang.Long") .getMethod("long longValue()"); SootMethod to_valueOf = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.Long valueOf(long)"); SootMethod to_concat = Scene.v().getSootClass("java.lang.String") .getMethod("java.lang.String concat(java.lang.String)"); // String metadata_name; if (isRequest) metadata_name = new String (": media_request"); else metadata_name = new String (": media_response"); //before execute //1. setup metadatas for log units.insertBefore(Jimple.v().newAssignStmt(tmpThrowable, NullConstant.v()), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, StringConstant.v("")), u); units.insertBefore(Jimple.v().newAssignStmt(spaceMessage, StringConstant.v(" ")), u); units.insertBefore(Jimple.v().newAssignStmt(tmpAppName, StringConstant.v(AppLogKey + metadata_name)), u); //2. log a request Url units.insertBefore(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("1)Url: ")), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), mediaUrl)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); //3. measure time before execute method (msec) units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newStaticInvokeExpr(to_curr_time.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpTime, Jimple.v().newStaticInvokeExpr(to_valueOf.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newVirtualInvokeExpr(tmpTime, to_longValue.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newStaticInvokeExpr(to_toString.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("2)time: ")), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); units.insertBefore(Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(to_log.makeRef(), tmpAppName, logMessage, tmpThrowable)), u); } private static void log_mediaresponse (Body b, PatchingChain<Unit> units, Unit u, String AppLogKey, Local internalMP_CB, Local internalMP, Local mediaUrl, boolean isRequest) { // Locals to inject Local tmpThrowable = addTmpThrowable(b); Local tmpAppName = addTmpName(b); Local tmpMessage = addTmpMessage(b); Local logMessage = addTmpMessage(b); Local spaceMessage = addTmpMessage(b); Local indexMessage = addTmpMessage(b); Local tmpTime = addTmpTime(b); Local tmpReqTime = addTmpTime_prim(b); // get sootMethod to use SootMethod to_log = Scene.v().getSootClass("android.util.Log") .getMethod("int e(java.lang.String,java.lang.String,java.lang.Throwable)"); SootMethod to_curr_time = Scene.v().getSootClass("java.lang.System") .getMethod("long currentTimeMillis()"); SootMethod to_toString = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.String toString(long)"); SootMethod to_longValue = Scene.v().getSootClass("java.lang.Long") .getMethod("long longValue()"); SootMethod to_valueOf = Scene.v().getSootClass("java.lang.Long") .getMethod("java.lang.Long valueOf(long)"); SootMethod to_concat = Scene.v().getSootClass("java.lang.String") .getMethod("java.lang.String concat(java.lang.String)"); SootMethod to_getStreamUrl = Scene.v().getSootClass("bbc.mobile.news.v3.media.InternalMediaPlayer") .getMethod("java.lang.String getStreamUrl()"); // String metadata_name; if (isRequest) metadata_name = new String (": media_request"); else metadata_name = new String (": media_response"); //before execute //1. setup metadatas for log units.insertBefore(Jimple.v().newAssignStmt(tmpThrowable, NullConstant.v()), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, StringConstant.v("")), u); units.insertBefore(Jimple.v().newAssignStmt(spaceMessage, StringConstant.v(" ")), u); units.insertBefore(Jimple.v().newAssignStmt(tmpAppName, StringConstant.v(AppLogKey + metadata_name)), u); //2. log a request Url units.insertBefore(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("1)Url: ")), u); units.insertBefore(Jimple.v().newAssignStmt(internalMP, Jimple.v().newInstanceFieldRef(internalMP_CB, Scene.v().getField("<bbc.mobile.news.v3.media.InternalMediaPlayer$Callbacks: bbc.mobile.news.v3.media.InternalMediaPlayer this$0>").makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newVirtualInvokeExpr(internalMP, to_getStreamUrl.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); //3. measure time before execute method (msec) units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newStaticInvokeExpr(to_curr_time.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpTime, Jimple.v().newStaticInvokeExpr(to_valueOf.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newAssignStmt(tmpReqTime, Jimple.v().newVirtualInvokeExpr(tmpTime, to_longValue.makeRef())), u); units.insertBefore(Jimple.v().newAssignStmt(tmpMessage, Jimple.v().newStaticInvokeExpr(to_toString.makeRef(), tmpReqTime)), u); units.insertBefore(Jimple.v().newAssignStmt(indexMessage, StringConstant.v("2)time: ")), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), indexMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), tmpMessage)), u); units.insertBefore(Jimple.v().newAssignStmt(logMessage, Jimple.v().newVirtualInvokeExpr(logMessage, to_concat.makeRef(), spaceMessage)), u); units.insertBefore(Jimple.v().newInvokeStmt( Jimple.v().newStaticInvokeExpr(to_log.makeRef(), tmpAppName, logMessage, tmpThrowable)), u); } }
mit
JCThePants/ArborianProtect
src/com/jcwhatever/arborianprotect/filters/IFilterPolicy.java
1641
/* * This file is part of ArborianProtect for Bukkit/Spigot, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.arborianprotect.filters; /** * Interface for a filter that has no permission but instead * uses a policy for its filtered items. */ public interface IFilterPolicy { /** * Get the filters policy. */ FilterPolicy getPolicy(); /** * Set the filters policy. * * @param policy The policy to set. */ void setPolicy(FilterPolicy policy); }
mit
dvsa/mot
mot-selenium/src/main/java/uk/gov/dvsa/domain/service/EventService.java
1031
package uk.gov.dvsa.domain.service; import com.jayway.restassured.response.Response; import uk.gov.dvsa.domain.api.request.CreateEventRequest; import uk.gov.dvsa.domain.model.User; import uk.gov.dvsa.domain.model.mot.Event; import uk.gov.dvsa.framework.config.webdriver.WebDriverConfigurator; import java.io.IOException; public class EventService extends Service { private static final String CREATE_EVENT_PATH = "/testsupport/event/create"; public EventService() { super(WebDriverConfigurator.testSupportUrl()); } /** * * @param event * @return ID of the created event * @throws IOException */ public String createEvent(Event event) throws IOException { CreateEventRequest createEventRequest = new CreateEventRequest(event); String request = jsonHandler.convertToString(createEventRequest); Response response = motClient.postWithoutToken(request, CREATE_EVENT_PATH); return ServiceResponse.createResponse(response, String.class); } }
mit
P1erreGaultier/ProjetService
com.alma.fournisseur.infrastructure/src/main/java/com/alma/wsimport/ValidateCardResponse.java
1573
package com.alma.wsimport; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour anonymous complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="validateCardReturn" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "validateCardReturn" }) @XmlRootElement(name = "validateCardResponse") public class ValidateCardResponse { @XmlElement(required = true) protected String validateCardReturn; /** * Obtient la valeur de la propriété validateCardReturn. * * @return * possible object is * {@link String } * */ public String getValidateCardReturn() { return validateCardReturn; } /** * Définit la valeur de la propriété validateCardReturn. * * @param value * allowed object is * {@link String } * */ public void setValidateCardReturn(String value) { this.validateCardReturn = value; } }
mit
aglne/Archimulator
src/main/java/archimulator/uncore/cache/partitioning/mlpAware/L2AccessMLPCostProfile.java
3324
/** * **************************************************************************** * Copyright (c) 2010-2015 by Min Cai (min.cai.china@gmail.com). * <p> * This file is part of the Archimulator multicore architectural simulator. * <p> * Archimulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * Archimulator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with Archimulator. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************** */ package archimulator.uncore.cache.partitioning.mlpAware; import java.util.ArrayList; import java.util.List; /** * L2 cache access MLP-cost profile. * * @author Min Cai */ public class L2AccessMLPCostProfile { private List<Integer> hitCounters; private int missCounter; /** * Create an L2 cache access MLP-cost profile. * * @param associativity the associativity */ public L2AccessMLPCostProfile(int associativity) { this.hitCounters = new ArrayList<>(); for (int i = 0; i < associativity; i++) { this.hitCounters.add(0); } } /** * Increment the hit counter for the specified stack distance. * * @param stackDistance the stack distance */ public void incrementCounter(int stackDistance) { if (stackDistance == -1) { this.missCounter++; } else { this.hitCounters.set(stackDistance, this.hitCounters.get(stackDistance) + 1); } } /** * Decrement the hit counter for the specified stack distance. * * @param stackDistance the stack distance */ public void decrementCounter(int stackDistance) { if (stackDistance == -1) { this.missCounter--; } else { this.hitCounters.set(stackDistance, this.hitCounters.get(stackDistance) - 1); } } /** * Get the value of N, which is the number of L2 accesses with stack distance greater than or equal to the specified stack distance. * * @param stackDistance the stack distance * @return the value of N, which is the number of L2 accesses with stack distance greater than or equal to the specified stack distance */ public int getN(int stackDistance) { if (stackDistance == -1) { return this.missCounter; } int n = 0; for (int i = stackDistance; i < this.hitCounters.size(); i++) { n += this.hitCounters.get(i); } return n; } /** * Get the list of hit counters. * * @return the list of hit counters */ public List<Integer> getHitCounters() { return hitCounters; } /** * Get the miss counter. * * @return the miss counter */ public int getMissCounter() { return missCounter; } }
mit
Quant1um/The-Harvester
HarvesterProject/src/net/quantium/harvester/entity/TreeEntity.java
3519
package net.quantium.harvester.entity; import java.util.Random; import net.quantium.harvester.Main; import net.quantium.harvester.entity.hitbox.Hitbox; import net.quantium.harvester.item.ItemSlot; import net.quantium.harvester.item.Items; import net.quantium.harvester.item.instances.ToolItem; import net.quantium.harvester.item.instances.ToolItem.ToolType; import net.quantium.harvester.render.Color; import net.quantium.harvester.render.ColorBundle; import net.quantium.harvester.render.Renderer; import net.quantium.harvester.world.World; public class TreeEntity extends LivingEntity { public static final int[] treeColors; static{ treeColors = new int[256]; for(int i = 0; i < 256; i++){ treeColors[i] = (int) Math.min(Math.max(((1 - (i / 256f)) * 3), 0), 9) * 100 + (int) Math.min(Math.max(((i / 256f) * 8), 0), 9) * 10; } } /** * */ private static final long serialVersionUID = 1L; public int type; public int temp; public int rotation; public TreeEntity(Random rand, byte temp, int type){ if(type > 2) type = 2; this.type = rand.nextInt(100) == 10 ? rand.nextInt(3) : type; rotation = rand.nextInt(1); this.temp = treeColors[temp + 128]; health = maxHealth = 20; } @Override public void init() { hitbox = new Hitbox(type == 0 ? 7 : type == 1 ? 4 : 10, 5, type == 0 ? -1 : type == 1 ? -3 : -5, -5); } private static final int[] spriteSheetMetaX0 = {0, 4, 11}; private static final int[] spriteSheetMetaY0 = {0, 3, 0}; private static final int[] spriteSheetMetaW0 = {3, 3, 5}; private static final int[] spriteSheetMetaH0 = {5, 2, 7}; private static final int[] spriteSheetMetaX1 = {4, 8, 6}; private static final int[] spriteSheetMetaY1 = {0, 0, 5}; private static final int[] spriteSheetMetaW1 = {4, 3, 5}; private static final int[] spriteSheetMetaH1 = {3, 5, 6}; @Override public void render(Renderer render) { ColorBundle bnd = ColorBundle.get(-1, Color.darker((short) temp, 1), temp, -1, -1, Color.lighter((short)temp, 1)); ColorBundle bnd0 = ColorBundle.get(-1, 321, 432, -1, -1, 543); int meta = type; int x0 = spriteSheetMetaX0[meta]; int x1 = spriteSheetMetaX1[meta]; int y0 = spriteSheetMetaY0[meta]; int y1 = spriteSheetMetaY1[meta]; int w0 = spriteSheetMetaW0[meta]; int w1 = spriteSheetMetaW1[meta]; int h0 = spriteSheetMetaH0[meta]; int h1 = spriteSheetMetaH1[meta]; render.get().drawColored(x - w0 * 4, y - h0 * 8, x0, y0, w0, h0, bnd0, "ambient", 0); render.get().drawColored(x - w0 * 4 + (type == 0 ? -1 : 0), y - h0 * 8 + (type == 1 ? -20 : 0), x1, y1, w1, h1, bnd, "ambient", 0); } @Override public void bump(Entity ent) {} @Override public boolean isPassable(Entity ent) { return false; } @Override public boolean onInteract(World world2, PlayerEntity playerEntity, InteractionMode im, ItemSlot item) { if(item != null && item.getItem() instanceof ToolItem && ((ToolItem)item.getItem()).getToolType() == ToolType.AXE){ this.hit(((ToolItem)item.getItem()).getPower()); }else{ this.hit(1); } if(Main.RANDOM.nextInt(5) == 0) world.throwItem(x, y, new ItemSlot(Items.stick, 0, Main.RANDOM.nextInt(2) + 1)); if(Main.RANDOM.nextInt(30) == 0) world.throwItem(x, y, new ItemSlot(Items.nut, 0, Main.RANDOM.nextInt(1) + 1)); return true; } @Override public void onDied() { super.onDied(); world.throwItem(x, y, new ItemSlot(Items.wood, 0, Main.RANDOM.nextInt(5) + 1)); } }
mit
HintonBR/scratch
College Programs/CS252 - Theoretical Programming Parsing-Compilers/CS252p2/DFA.java
26537
import java.io.*; import java.util.*; class DFA { String startState; String finalState[] = new String[5]; int numberOfFinalStates = 0; String inputSymbols[] = new String[6]; int numberOfInputs = 0; String grammer[][] = new String[15][7]; String finalgrammer[][] = new String[15][7]; int numberInFinalGrammer = 0; int numberOfStates = 0; int insert(String myString) { if (isIn(myString) == -1) { grammer[numberOfStates][0] = myString; numberOfStates += 1; return (numberOfStates -1); } return -1; } int isIn(String myString) { int counter; for (counter = 0; counter < numberOfStates; counter++) { if (grammer[counter][0].equals(myString)) { return counter; } } return -1; } int insertInput(String myString) { inputSymbols[numberOfInputs] = myString; numberOfInputs += 1; return (numberOfInputs - 1); } int inputIsIn(String myString) { int counter; for (counter = 0; counter < (inputSymbols.length); counter++) { if (inputSymbols[counter] != null) { if (inputSymbols[counter].equals(myString)) { return counter; } } } return -1; } int insertFinalState(String myString) { finalState[numberOfFinalStates] = myString; numberOfFinalStates += 1; return 1; } int isFinalState(String myString) { int counter; for (counter = 0; counter < numberOfFinalStates; counter++) { if (finalState[counter].equals(myString)) { return counter; } } return -1; } String checkForLambdaInputs(int index) { return grammer[index][6]; } void insertIntoFinalGrammer(String myString) { finalgrammer[numberInFinalGrammer][0] = myString; numberInFinalGrammer++; return; } boolean isInFinalGrammer(String myString) { int counter; for (counter = 0; counter < numberInFinalGrammer; counter++) { if (finalgrammer[counter][0].equals(myString) == true) { return true; } } return false; } void removeCommas() { int counter = 0, counter2 = 0; for (counter = 0; counter < numberInFinalGrammer; counter++) { for (counter2 = 0; counter2 <= numberOfInputs; counter2++) { if (finalgrammer[counter][counter2] != null) { finalgrammer[counter][counter2] = removeFromString(finalgrammer[counter][counter2], ","); } } } }//end of remove Commas void output() { int counter; int counter2 = 0; System.out.println("Printing out the DFA"); System.out.println(finalgrammer[0][0]); finalgrammer[0][6] = "T"; for (counter = 0; counter < numberInFinalGrammer; counter++) { while (counter2 < finalgrammer[counter][0].length()) { if ((counter2+1) == finalgrammer[counter][0].length()) { if ((isFinalState(finalgrammer[counter][0].substring(counter2)) != -1)) { finalgrammer[counter][6] = "T"; System.out.print(finalgrammer[counter][0]); System.out.print(" "); break; } } else { if ((isFinalState(finalgrammer[counter][0].substring(counter2, counter2 + 1)) != -1)) { finalgrammer[counter][6] = "T"; System.out.print(finalgrammer[counter][0]); System.out.print(" "); break; } } counter2++; } counter2 = 0; } System.out.println(); for (counter = 0; counter < numberInFinalGrammer; counter++) { if (finalgrammer[counter][6] == null) { System.out.print(finalgrammer[counter][0]); System.out.print(" "); } } System.out.print("L"); System.out.println(); for (counter = 0; counter < numberInFinalGrammer; counter++) { for (counter2 = 1; counter2 <= numberOfInputs; counter2++) { System.out.print(finalgrammer[counter][0]); System.out.print(inputSymbols[counter2 -1]); if (finalgrammer[counter][counter2].equals("") == false) { System.out.print(finalgrammer[counter][counter2]); } else { System.out.print("L"); } System.out.println(); } } for (counter = 0; counter < numberOfInputs; counter++) { System.out.print("L"); System.out.print(inputSymbols[counter]); System.out.print("L"); System.out.println(); } }//end of output method; String removeFromString(String myString, String stringToRemove) { int remove; String mainString = myString; String tempString; int counter = 0; int sIndex; if (mainString == null) { return null; } while (counter != -1) { remove = mainString.indexOf(stringToRemove); if (remove != -1) { tempString = mainString.substring(remove + stringToRemove.length()); mainString = mainString.substring(0, remove); mainString = mainString.concat(tempString); } counter = mainString.indexOf(stringToRemove); } return mainString; } public static void main(String args[]) throws IOException { int grammerIndex; int index; String tempState; String finals = ""; String temp = ""; int positionInString = 0; int position = 0; int positionInString2 = 0; StringTokenizer stringTok; String tempSymbol; RandomAccessFile inFile = null; DFA myObject = new DFA(); int counter = 0; int counter2 = 0; final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz"; final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; myObject.inputSymbols[5] = "l"; //open file for input System.out.println("We are getting the startstate"); //get startstate from firstline in the array myObject.startState = inFile.readLine(); myObject.startState = myObject.removeFromString(myObject.startState, "/r/n"); myObject.insert(myObject.startState); System.out.println("We are parsing the final states now"); //get final states and put them in the array tempState = inFile.readLine(); tempState = myObject.removeFromString(tempState, "/r/n"); while (counter < tempState.length()) { if ((counter + 1) < tempState.length()) { while (tempState.substring(counter, counter + 1) == " ") { counter += 1; } while (tempState.substring(counter, counter + 1) != " ") { finals = finals.concat(tempState.substring(counter, counter + 1)); counter += 1; if (counter >= (tempState.length() -1)) { break; } } } else { finals = finals.concat(tempState.substring(counter)); counter += 1; } myObject.insert(finals.trim()); myObject.insertFinalState(finals.trim()); finals = ""; } System.out.println("WE are reading in the other states"); counter = 0; tempState = inFile.readLine(); tempState = myObject.removeFromString(tempState, "/r/n"); while (counter < tempState.length()) { if ((counter+1) < tempState.length()) { while (tempState.substring(counter, counter + 1) == " ") { counter += 1; } while (tempState.substring(counter, counter + 1) != " ") { finals = finals.concat(tempState.substring(counter, counter + 1)); counter += 1; if (counter >= (tempState.length() -1)) { break; } } } else { finals = finals.concat(tempState.substring(counter)); counter +=1; } myObject.insert(finals.trim()); finals = ""; } counter = 0; System.out.println("WE are parsing the transitions now"); //Start parsing the transitions and put them in the array tempState = inFile.readLine(); tempState = myObject.removeFromString(tempState, "/r/n"); while (tempState != null) { //get first state while (LOWERCASE.indexOf(tempState.substring(counter, counter + 1)) == -1) { finals = finals.concat(tempState.substring(counter, counter + 1)); counter += 1; } grammerIndex = myObject.isIn(finals); //get input symbol tempSymbol = tempState.substring(counter, counter + 1); index = myObject.inputIsIn(tempSymbol); if (index == -1) { index = myObject.insertInput(tempSymbol); } //increment index by one to make sure it points to the same spot //in the grammer array index += 1; counter++; finals = ""; //read in and input the state that the transition goes to while (counter < tempState.length()) { finals = finals.concat(tempState.substring(counter, counter + 1)); counter += 1; } //grammerIndex = myObject.isIn(finals); counter = myObject.isIn(finals); if (myObject.grammer[grammerIndex][index] == null) { myObject.grammer[grammerIndex][index] = finals; } else { myObject.grammer[grammerIndex][index] = myObject.grammer[grammerIndex][index].concat(","); myObject.grammer[grammerIndex][index] = myObject.grammer[grammerIndex][index].concat(finals.trim()); } tempState = inFile.readLine(); tempState = myObject.removeFromString(tempState, "/r/n"); counter = 0; finals = ""; } System.out.println("We finished reading in the states here -- Doing Lambda closure!!"); //Begin revising here to finish program finals = ""; //begin processing array - lambda closure //begin processing array - lambda closure for (counter = 0; counter < myObject.numberOfStates; counter++) { for (counter2 = 6; counter2 == 6; counter2++) { if (myObject.grammer[counter][counter2] != null) { while (positionInString != -1) { positionInString2 = 0; positionInString = myObject.grammer[counter][counter2].indexOf(","); while (positionInString != -1) { temp = myObject.checkForLambdaInputs(myObject.isIn(myObject.grammer[counter][counter2].substring(positionInString2, positionInString))); if (temp != null) { if (finals == "") { finals = finals.concat(temp); } else { finals = finals.concat(","); finals = finals.concat(temp); } } positionInString2 = positionInString + 1; positionInString = myObject.grammer[counter][counter2].indexOf(",", positionInString2); }//end of while temp = myObject.checkForLambdaInputs(myObject.isIn(myObject.grammer[counter][counter2].substring(positionInString2))); positionInString = myObject.grammer[counter][counter2].length() - 1; if (temp != null) { if (finals == "") { finals = finals.concat(temp); } else { finals = finals.concat(","); finals = finals.concat(temp); } } if (finals != "") { position = 0; positionInString2 = finals.indexOf(","); while (positionInString2 != -1) { temp = finals.substring(position, positionInString2); index = myObject.grammer[counter][counter2].indexOf(temp); if (index == -1) { myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(","); myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(temp); } position = positionInString2 +1; positionInString2 += 1; positionInString2 = finals.indexOf(",", positionInString2); } temp = finals.substring(position); index = myObject.grammer[counter][counter2].indexOf(temp); if (index == -1) { myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(","); myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(temp); } finals = ""; if (myObject.grammer[counter][counter2].length() != (positionInString +1)) { positionInString2 = positionInString + 1; } else { positionInString = -1; } }//end of if else { positionInString = -1; } }//end of outer while positionInString = 0; }// end of if }//end of inner for }//end of outer for finals = ""; for (counter = 0; counter < myObject.numberOfStates; counter++) { for (counter2 = 1; counter2 <= myObject.numberOfInputs; counter2++) { if (myObject.grammer[counter][counter2] != null) { while (positionInString != -1) { positionInString2 = 0; positionInString = myObject.grammer[counter][counter2].indexOf(","); while (positionInString != -1) { temp = myObject.checkForLambdaInputs(myObject.isIn(myObject.grammer[counter][counter2].substring(positionInString2, positionInString))); if (temp != null) { if (finals == "") { finals = finals.concat(temp); } else { finals = finals.concat(","); finals = finals.concat(temp); } } positionInString2 = positionInString + 1; positionInString = myObject.grammer[counter][counter2].indexOf(",", positionInString2); }//end of while temp = myObject.checkForLambdaInputs(myObject.isIn(myObject.grammer[counter][counter2].substring(positionInString2))); positionInString = myObject.grammer[counter][counter2].length() - 1; if (temp != null) { if (finals == "") { finals = finals.concat(temp); } else { finals = finals.concat(","); finals = finals.concat(temp); } } if (finals != "") { position = 0; positionInString2 = finals.indexOf(","); while (positionInString2 != -1) { temp = finals.substring(position, positionInString2); index = myObject.grammer[counter][counter2].indexOf(temp); if (index == -1) { myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(","); myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(temp); } position = positionInString2 +1; positionInString2 += 1; positionInString2 = finals.indexOf(",", positionInString2); } temp = finals.substring(position); index = myObject.grammer[counter][counter2].indexOf(temp); if (index == -1) { myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(","); myObject.grammer[counter][counter2] = myObject.grammer[counter][counter2].concat(temp); } finals = ""; if (myObject.grammer[counter][counter2].length() != (positionInString +1)) { positionInString2 = positionInString + 1; } else { positionInString = -1; } }//end of if else { positionInString = -1; } }//end of outer while positionInString = 0; }// end of if }//end of inner for }//end of outer for System.out.println("We finished doing the lambda closure here"); for (counter = 0; counter < myObject.numberOfStates; counter++) { for (counter2 = 1; counter2 <= myObject.numberOfInputs; counter2++) { System.out.print(myObject.grammer[counter][0]); System.out.print(myObject.inputSymbols[counter2 -1]); if (myObject.grammer[counter][counter2] != null) { System.out.println(myObject.grammer[counter][counter2]); } else { System.out.println("L"); } } } System.out.println("Starting to create the final grammer"); if (myObject.grammer[0][6] != null) { myObject.startState = myObject.startState.concat(","); myObject.startState = myObject.startState.concat(myObject.grammer[0][6]); } counter = 0; myObject.finalgrammer[0][0] = myObject.startState; myObject.numberInFinalGrammer++; while (myObject.finalgrammer[counter][0] != null) { positionInString2 = 0; positionInString = myObject.finalgrammer[counter][0].indexOf(","); while (positionInString != -1) { index = myObject.isIn(myObject.finalgrammer[counter][0].substring(positionInString2, positionInString)); for (counter2 = 1; counter2 <= myObject.numberOfInputs; counter2++) { if (myObject.grammer[index][counter2] != null) { stringTok = new StringTokenizer(myObject.grammer[index][counter2], ","); if (stringTok.countTokens() < 2) { temp = stringTok.nextToken(); if (myObject.finalgrammer[counter][counter2] != null && myObject.finalgrammer[counter][counter2] != "") { if (myObject.finalgrammer[counter][counter2].indexOf(temp) == -1) { temp = ",".concat(temp); myObject.finalgrammer[counter][counter2] = myObject.finalgrammer[counter][counter2].concat(temp); } } else { myObject.finalgrammer[counter][counter2]= myObject.grammer[index][counter2]; } } else { while (stringTok.hasMoreTokens() == true) { try { temp = stringTok.nextToken(); } catch (NoSuchElementException e) { } if (myObject.finalgrammer[counter][counter2] != null && myObject.finalgrammer[counter][counter2] != "") { if (myObject.finalgrammer[counter][counter2].indexOf(temp) == -1) { temp = ",".concat(temp); myObject.finalgrammer[counter][counter2] = myObject.finalgrammer[counter][counter2].concat(temp); } } else { myObject.finalgrammer[counter][counter2] = temp; } }//end of while }//end of else } else { if (myObject.finalgrammer[counter][counter2] == null) { myObject.finalgrammer[counter][counter2] = ""; } } }//end of for positionInString2 = positionInString + 1; positionInString = myObject.finalgrammer[counter][0].indexOf(",", positionInString2); }//end of outer while index = myObject.isIn(myObject.finalgrammer[counter][0].substring(positionInString2)); for (counter2 = 1; counter2 <= myObject.numberOfInputs; counter2++) { if (myObject.grammer[index][counter2] != null) { stringTok = new StringTokenizer(myObject.grammer[index][counter2], ","); if (stringTok.countTokens() < 2) { temp = stringTok.nextToken(); if (myObject.finalgrammer[counter][counter2] != null && myObject.finalgrammer[counter][counter2] != "") { if (myObject.finalgrammer[counter][counter2].indexOf(temp) == -1) { temp = ",".concat(temp); myObject.finalgrammer[counter][counter2] = myObject.finalgrammer[counter][counter2].concat(temp); } } else { myObject.finalgrammer[counter][counter2]= myObject.grammer[index][counter2]; } } else { while (stringTok.hasMoreTokens() == true) { try { temp = stringTok.nextToken(); } catch (NoSuchElementException e) { } if (myObject.finalgrammer[counter][counter2] != null && myObject.finalgrammer[counter][counter2] != "") { if (myObject.finalgrammer[counter][counter2].indexOf(temp) == -1) { temp = ",".concat(temp); myObject.finalgrammer[counter][counter2] = myObject.finalgrammer[counter][counter2].concat(temp); } } else { myObject.finalgrammer[counter][counter2] = temp; } }//end of while }//end of else } else { if (myObject.finalgrammer[counter][counter2] == null) { myObject.finalgrammer[counter][counter2] = ""; } } }//end of for for (counter2 = 1; counter2 <= myObject.numberOfInputs; counter2++) { if (myObject.finalgrammer[counter][counter2] != null) { if (myObject.finalgrammer[counter][counter2] != "" && myObject.isInFinalGrammer(myObject.finalgrammer[counter][counter2]) == false) { myObject.insertIntoFinalGrammer(myObject.finalgrammer[counter][counter2]); } } } counter++; } myObject.removeCommas(); myObject.output(); } //end of main }//end of DFA class
mit
fimkrypto/nextrtc-signaling-server
src/test/java/org/nextrtc/signalingserver/domain/ServerTest.java
11563
package org.nextrtc.signalingserver.domain; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.CONVERSATION_CREATED; import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.MEMBER_LOCAL_STREAM_CREATED; import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.SESSION_STARTED; import java.util.List; import javax.websocket.CloseReason; import javax.websocket.Session; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.nextrtc.signalingserver.BaseTest; import org.nextrtc.signalingserver.EventChecker; import org.nextrtc.signalingserver.MessageMatcher; import org.nextrtc.signalingserver.api.NextRTCEvent; import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener; import org.nextrtc.signalingserver.domain.ServerTest.LocalStreamCreated; import org.nextrtc.signalingserver.domain.ServerTest.ServerEventCheck; import org.nextrtc.signalingserver.exception.Exceptions; import org.nextrtc.signalingserver.exception.SignalingException; import org.nextrtc.signalingserver.repository.Members; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = { ServerEventCheck.class, LocalStreamCreated.class }) public class ServerTest extends BaseTest { @NextRTCEventListener({ SESSION_STARTED, CONVERSATION_CREATED }) public static class ServerEventCheck extends EventChecker { } @Rule public ExpectedException expect = ExpectedException.none(); @Autowired private Server server; @Autowired private Members members; @Autowired private ServerEventCheck eventCheckerCall; @Test public void shouldThrowExceptionWhenMemberDoesntExists() throws Exception { // given Session session = mock(Session.class); when(session.getId()).thenReturn("s1"); // then expect.expect(SignalingException.class); expect.expectMessage(Exceptions.MEMBER_NOT_FOUND.name()); // when server.handle(mock(Message.class), session); } @Test public void shouldRegisterUserOnWebSocketConnection() throws Exception { // given Session session = mock(Session.class); when(session.getId()).thenReturn("s1"); // when server.register(session); // then assertTrue(members.findBy("s1").isPresent()); } @Test public void shouldCreateConversationOnCreateSignal() throws Exception { // given Session session = mockSession("s1"); server.register(session); // when server.handle(Message.create()// .signal("create")// .build(), session); // then List<NextRTCEvent> events = eventCheckerCall.getEvents(); assertThat(events.size(), is(2)); } @Test public void shouldCreateConversationCreate() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); // then assertThat(s1Matcher.getMessages().size(), is(1)); assertThat(s1Matcher.getMessage().getSignal(), is("created")); assertThat(s2Matcher.getMessages().size(), is(0)); } @Test public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); s1Matcher.reset(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertMessage(s1Matcher, 0, "s2", "s1", "joined", EMPTY); assertMessage(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY); assertThat(s2Matcher.getMessages().size(), is(1)); assertMessage(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey); } @NextRTCEventListener({ MEMBER_LOCAL_STREAM_CREATED }) public static class LocalStreamCreated extends EventChecker { } @Autowired private LocalStreamCreated eventLocalStream; @Test public void shouldCreateConversationJoinMemberAndPassOfferResponseToRestMembers() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); s1Matcher.reset(); s2Matcher.reset(); // when // s2 has to create local stream server.handle(Message.create()// .to("s1")// .signal("offerResponse")// .content("s2 spd")// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(1)); assertMessage(s1Matcher, 0, "s2", "s1", "answerRequest", "s2 spd"); assertThat(s2Matcher.getMessages().size(), is(0)); assertThat(eventLocalStream.getEvents().size(), is(1)); assertThat(eventLocalStream.getEvents().get(0).getType(), is(MEMBER_LOCAL_STREAM_CREATED)); } @Test public void shouldCreateConversationJoinMemberAndPassOfferResponseToRestTwoMembers() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); MessageMatcher s3Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); Session s3 = mockSession("s3", s3Matcher); server.register(s1); server.register(s2); server.register(s3); server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s3); s1Matcher.reset(); s2Matcher.reset(); s3Matcher.reset(); // when // s2 has to create local stream server.handle(Message.create()// .to("s1")// .signal("offerResponse")// .content("s2 spd")// .build(), s2); // s3 has to create local stream server.handle(Message.create()// .to("s1")// .signal("offerResponse")// .content("s3 spd")// .build(), s3); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertMessage(s1Matcher, 0, "s2", "s1", "answerRequest", "s2 spd"); assertMessage(s1Matcher, 1, "s3", "s1", "answerRequest", "s3 spd"); assertThat(s2Matcher.getMessages().size(), is(0)); assertThat(s3Matcher.getMessages().size(), is(0)); assertThat(eventLocalStream.getEvents().size(), is(2)); } @Test public void shouldExchangeSpds() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); server.handle(Message.create()// .signal("create")// .build(), s1); // -> created String conversationKey = s1Matcher.getMessage().getContent(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // -> joined // -> offerRequest server.handle(Message.create()// .to("s1")// .signal("offerResponse")// .content("s2 spd")// .build(), s2); // -> answerRequest s1Matcher.reset(); s2Matcher.reset(); // when server.handle(Message.create()// .to("s2")// .signal("answerResponse")// .content("s1 spd")// .build(), s1); // then assertThat(s2Matcher.getMessages().size(), is(1)); assertMessage(s2Matcher, 0, "s1", "s2", "finalize", "s1 spd"); assertThat(s1Matcher.getMessages().size(), is(0)); assertThat(eventLocalStream.getEvents().size(), is(2)); } @Test public void shouldExchangeCandidate() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); server.handle(Message.create()// .signal("create")// .build(), s1); // -> created String conversationKey = s1Matcher.getMessage().getContent(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // -> joined // -> offerRequest server.handle(Message.create()// .to("s1")// .signal("offerResponse")// .content("s2 spd")// .build(), s2); // -> answerRequest server.handle(Message.create()// .to("s2")// .signal("answerResponse")// .content("s1 spd")// .build(), s1); // -> finalize s1Matcher.reset(); s2Matcher.reset(); server.handle(Message.create()// .to("s1")// .signal("candidate")// .content("candidate s2")// .build(), s2); server.handle(Message.create()// .to("s2")// .signal("candidate")// .content("candidate s1")// .build(), s1); // when // then assertThat(s1Matcher.getMessages().size(), is(1)); assertMessage(s1Matcher, 0, "s2", "s1", "candidate", "candidate s2"); assertThat(s2Matcher.getMessages().size(), is(1)); assertMessage(s2Matcher, 0, "s1", "s2", "candidate", "candidate s1"); } @Test public void shouldUnregisterSession() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); server.handle(Message.create()// .signal("create")// .build(), s1); // -> created String conversationKey = s1Matcher.getMessage().getContent(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); s1Matcher.reset(); s2Matcher.reset(); server.unregister(s1, mock(CloseReason.class)); // when // then assertThat(s1Matcher.getMessages().size(), is(0)); assertThat(s2Matcher.getMessages().size(), is(1)); assertMessage(s2Matcher, 0, "s1", "s2", "left", EMPTY); } private void assertMessage(MessageMatcher matcher, int number, String from, String to, String signal, String content) { assertThat(matcher.getMessage(number).getFrom(), is(from)); assertThat(matcher.getMessage(number).getTo(), is(to)); assertThat(matcher.getMessage(number).getSignal(), is(signal)); assertThat(matcher.getMessage(number).getContent(), is(content)); } @Before public void resetObjects() { eventCheckerCall.reset(); eventLocalStream.reset(); members.unregister("s1"); members.unregister("s2"); members.unregister("s3"); } }
mit
mklaehn/nbfx-platform
nbfx.util/src/org/nbfx/util/NBFxThreading.java
1468
/* * The MIT License * * Copyright 2015 NBFx. * * 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.nbfx.util; import java.util.concurrent.Callable; import java.util.concurrent.Future; public interface NBFxThreading { boolean isCurrentThread(); void ensureThread(); void runLater(final Runnable runnable); <T> Future<T> getAsynch(final Callable<T> callable); <T> T get(final Callable<T> callable); }
mit
KamranMackey/CommandHelper
src/main/java/com/laytonsmith/abstraction/bukkit/entities/BukkitMCSlime.java
669
package com.laytonsmith.abstraction.bukkit.entities; import com.laytonsmith.abstraction.AbstractionObject; import com.laytonsmith.abstraction.bukkit.BukkitMCLivingEntity; import com.laytonsmith.abstraction.entities.MCSlime; import org.bukkit.entity.Slime; /** * * @author Hekta */ public class BukkitMCSlime extends BukkitMCLivingEntity implements MCSlime { public BukkitMCSlime(Slime slime) { super(slime); } public BukkitMCSlime(AbstractionObject ao) { this((Slime) ao.getHandle()); } @Override public int getSize() { return ((Slime)getHandle()).getSize(); } @Override public void setSize(int size) { ((Slime)getHandle()).setSize(size); } }
mit
chen-android/guoliao
CallKit/src/main/java/io/rong/callkit/VideoPlugin.java
6188
package io.rong.callkit; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.Fragment; import android.widget.Toast; import java.util.ArrayList; import io.rong.calllib.RongCallClient; import io.rong.calllib.RongCallCommon; import io.rong.calllib.RongCallSession; import io.rong.common.RLog; import io.rong.imkit.RongExtension; import io.rong.imkit.RongIM; import io.rong.imkit.plugin.IPluginModule; import io.rong.imkit.utilities.PermissionCheckUtil; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Discussion; /** * Created by weiqinxiao on 16/8/16. */ public class VideoPlugin implements IPluginModule { private static final String TAG = "VideoPlugin"; private ArrayList<String> allMembers; private Context context; private Conversation.ConversationType conversationType; private String targetId; @Override public Drawable obtainDrawable(Context context) { return context.getResources().getDrawable(R.drawable.rc_ic_video_selector); } @Override public String obtainTitle(Context context) { return context.getString(R.string.rc_voip_video); } @Override public void onClick(Fragment currentFragment, final RongExtension extension) { String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}; if (!PermissionCheckUtil.requestPermissions(currentFragment, permissions)) { return; } context = currentFragment.getActivity().getApplicationContext(); conversationType = extension.getConversationType(); targetId = extension.getTargetId(); RongCallSession profile = RongCallClient.getInstance().getCallSession(); if (profile != null && profile.getActiveTime() > 0) { Toast.makeText(context, profile.getMediaType() == RongCallCommon.CallMediaType.AUDIO ? context.getString(R.string.rc_voip_call_audio_start_fail) : context.getString(R.string.rc_voip_call_video_start_fail), Toast.LENGTH_SHORT) .show(); return; } ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()) { Toast.makeText(context, context.getString(R.string.rc_voip_call_network_error), Toast.LENGTH_SHORT).show(); return; } if (conversationType.equals(Conversation.ConversationType.PRIVATE)) { Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEVIDEO); intent.putExtra("conversationType", conversationType.getName().toLowerCase()); intent.putExtra("targetId", targetId); intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setPackage(context.getPackageName()); context.getApplicationContext().startActivity(intent); } else if (conversationType.equals(Conversation.ConversationType.DISCUSSION)) { RongIM.getInstance().getDiscussion(targetId, new RongIMClient.ResultCallback<Discussion>() { @Override public void onSuccess(Discussion discussion) { Intent intent = new Intent(context, CallSelectMemberActivity.class); allMembers = (ArrayList<String>) discussion.getMemberIdList(); intent.putStringArrayListExtra("allMembers", allMembers); String myId = RongIMClient.getInstance().getCurrentUserId(); ArrayList<String> invited = new ArrayList<>(); invited.add(myId); intent.putStringArrayListExtra("invitedMembers", invited); intent.putExtra("mediaType", RongCallCommon.CallMediaType.VIDEO.getValue()); extension.startActivityForPluginResult(intent, 110, VideoPlugin.this); } @Override public void onError(RongIMClient.ErrorCode e) { RLog.d(TAG, "get discussion errorCode = " + e.getValue()); } }); } else if (conversationType.equals(Conversation.ConversationType.GROUP)) { Intent intent = new Intent(context, CallSelectMemberActivity.class); String myId = RongIMClient.getInstance().getCurrentUserId(); ArrayList<String> invited = new ArrayList<>(); invited.add(myId); intent.putStringArrayListExtra("invitedMembers", invited); intent.putExtra("groupId", targetId); intent.putExtra("mediaType", RongCallCommon.CallMediaType.VIDEO.getValue()); extension.startActivityForPluginResult(intent, 110, this); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_MULTIVIDEO); ArrayList<String> userIds = data.getStringArrayListExtra("invited"); userIds.add(RongIMClient.getInstance().getCurrentUserId()); intent.putExtra("conversationType", conversationType.getName().toLowerCase()); intent.putExtra("targetId", targetId); intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName()); intent.putStringArrayListExtra("invitedUsers", userIds); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setPackage(context.getPackageName()); context.getApplicationContext().startActivity(intent); } }
mit
lolkedijkstra/xml2j-gen
samples/discogs/releases/src/main/java/com/xml2j/discogs/releases/handlers/ReleasesMessageHandler.java
1617
package com.xml2j.discogs.releases.handlers; /****************************************************************************** ----------------------------------------------------------------------------- XML2J XSD to Java code generator ----------------------------------------------------------------------------- This code was generated using XML2J code generator. Version: 2.4.2 Project home: XML2J https://sourceforge.net/projects/xml2j/ Module: RELEASES Generation date: Sun Apr 15 13:02:55 CEST 2018 Author: XML2J-Generator ******************************************************************************/ import org.xml.sax.XMLReader; import com.xml2j.discogs.releases.Releases; import com.xml2j.discogs.releases.ReleasesHandler; import com.xml2j.xml.core.XMLMessageHandler; import com.xml2j.xml.parser.ParserTask; /** * This class reads the XML document from an XML inputsource. * * This class is the entry point for the client application. */ public class ReleasesMessageHandler extends XMLMessageHandler<Releases> { /** root element. */ static final String ELEMENT_NAME = "releases"; /** * Constructor. * * @see XMLMessageHandler XMLMessageHandler * @param task * The parser task * @param reader * The (SAX) XML Reader object */ public ReleasesMessageHandler(ParserTask task, XMLReader reader) { super(reader , new ReleasesHandler( task , reader , null // root has no parent , ELEMENT_NAME , Releases.getAllocator() , null // not applicable for root , doProcess(ELEMENT_NAME, task)) ); } }
mit
BIG-IoT/example-projects
more-java-examples/src/main/java/org/eclipse/bigiot/lib/examples/types/MyParkingResultPojo.java
916
/** * Copyright (c) 2016-2017 in alphabetical order: * Bosch Software Innovations GmbH, Robert Bosch GmbH, Siemens AG * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Denis Kramer (Bosch Software Innovations GmbH) * Stefan Schmid (Robert Bosch GmbH) * Andreas Ziller (Siemens AG) */ package org.eclipse.bigiot.lib.examples.types; public class MyParkingResultPojo { public double latitude; public double longitude; public double distance; public String status; @Override public String toString() { return "MyParkingResultPojo [longitude=" + longitude + ", latitude=" + latitude + ", distance=" + distance + ", status=" + status + "]"; } }
mit
tah187/homecad
homecad/src/homecad/model/facade/HomeCADmodel.java
1742
package homecad.model.facade; import homecad.model.*; import homecad.model.exception.*; //----------------------------------------------- //Programming 2 -- OUA Term 4, 2010 //----------------------------------------------- //Interface to the system functionality (model) //----------------------------------------------- public interface HomeCADmodel { public Owner getOwner(); public void addRoom(Room room) throws StructuralException, FinanceException; public void removeRoom(RoomReference location) throws StructuralException; public Room getRoom(RoomReference location); public Room[] getStoreyRooms(int storey); public Room[] getAllRooms(); public boolean addItem(RoomReference location, Item item) throws FinanceException; public boolean removeItem(RoomReference location, String name); public void addExitPoint(RoomReference source, RoomReference destination, String exitName) throws StructuralException; public void removeExitPoint(RoomReference source, String exitName) throws StructuralException; public void reset(); public int calculateHouseSize(); public int calculateStoreySize(int storey); public int calculateRoomCost(RoomReference location); public int calculateHouseCost(); public int calculateStoreyCost(int storey); /* this returns an array containing 2 ints, with the first element indicating the number of rows, and the second element the number of columns for a given storey. */ public int[] getMaxGridSize(int storey); public int getNumberOfStories(); public boolean doesRoomExist(RoomReference test); public RoomReference validateRoomReference (RoomReference location); }
mit
sherter/google-java-format-gradle-plugin
subprojects/format/src/main/groovy/com/github/sherter/googlejavaformatgradleplugin/format/Gjf.java
1699
package com.github.sherter.googlejavaformatgradleplugin.format; import com.google.common.collect.ImmutableList; /** Static factory method for creating new {@link Formatter}s. */ public class Gjf { public static final String GROUP_ID = "com.google.googlejavaformat"; public static final String ARTIFACT_ID = "google-java-format"; public static final ImmutableList<String> SUPPORTED_VERSIONS = ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "1.10.0", "1.11.0"); /** * Constructs a new formatter that delegates to <a * href="https://github.com/google/google-java-format">google-java-format</a>. * * @param classLoader load {@code google-java-format} classes from this {@code ClassLoader} * @param config configure the formatter according to this configuration * @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed */ public static Formatter newFormatter(ClassLoader classLoader, Configuration config) throws ReflectiveOperationException { return newFormatterFactory(classLoader, config).create(); } private static FormatterFactory newFormatterFactory( ClassLoader classLoader, Configuration config) { switch (config.version) { case "1.0": return new OneDotZeroFactory(classLoader, config); case "1.1": case "1.2": case "1.3": case "1.4": case "1.5": case "1.6": case "1.7": return new OneDotOneFactory(classLoader, config); case "1.8": case "1.9": case "1.10.0": case "1.11.0": default: return new OneDotEightFactory(classLoader, config); } } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/java/util/jar/Manifest.java
14997
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1997, 2013. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util.jar; import java.io.FilterInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import com.ibm.jvm.io.LocalizedInputStream; //IBM-zos_bringup /** * The Manifest class is used to maintain Manifest entry names and their * associated Attributes. There are main Manifest Attributes as well as * per-entry Attributes. For information on the Manifest format, please * see the * <a href="../../../../technotes/guides/jar/jar.html"> * Manifest format specification</a>. * * @author David Connelly * @see Attributes * @since 1.2 */ public class Manifest implements Cloneable { // manifest main attributes private Attributes attr = new Attributes(); // manifest entries private Map<String, Attributes> entries = new HashMap<>(); /** * Constructs a new, empty Manifest. */ public Manifest() { } /** * Constructs a new Manifest from the specified input stream. * * @param is the input stream containing manifest data * @throws IOException if an I/O error has occurred */ public Manifest(InputStream is) throws IOException { read(is); } /** * Constructs a new Manifest that is a copy of the specified Manifest. * * @param man the Manifest to copy */ public Manifest(Manifest man) { attr.putAll(man.getMainAttributes()); entries.putAll(man.getEntries()); } /** * Returns the main Attributes for the Manifest. * @return the main Attributes for the Manifest */ public Attributes getMainAttributes() { return attr; } /** * Returns a Map of the entries contained in this Manifest. Each entry * is represented by a String name (key) and associated Attributes (value). * The Map permits the {@code null} key, but no entry with a null key is * created by {@link #read}, nor is such an entry written by using {@link * #write}. * * @return a Map of the entries contained in this Manifest */ public Map<String,Attributes> getEntries() { return entries; } /** * Returns the Attributes for the specified entry name. * This method is defined as: * <pre> * return (Attributes)getEntries().get(name) * </pre> * Though {@code null} is a valid {@code name}, when * {@code getAttributes(null)} is invoked on a {@code Manifest} * obtained from a jar file, {@code null} will be returned. While jar * files themselves do not allow {@code null}-named attributes, it is * possible to invoke {@link #getEntries} on a {@code Manifest}, and * on that result, invoke {@code put} with a null key and an * arbitrary value. Subsequent invocations of * {@code getAttributes(null)} will return the just-{@code put} * value. * <p> * Note that this method does not return the manifest's main attributes; * see {@link #getMainAttributes}. * * @param name entry name * @return the Attributes for the specified entry name */ public Attributes getAttributes(String name) { return getEntries().get(name); } /** * Clears the main Attributes as well as the entries in this Manifest. */ public void clear() { attr.clear(); entries.clear(); } /** * Writes the Manifest to the specified OutputStream. * Attributes.Name.MANIFEST_VERSION must be set in * MainAttributes prior to invoking this method. * * @param out the output stream * @exception IOException if an I/O error has occurred * @see #getMainAttributes */ public void write(OutputStream out) throws IOException { DataOutputStream dos = new DataOutputStream(out); // Write out the main attributes for the manifest attr.writeMain(dos); // Now write out the pre-entry attributes Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Attributes> e = it.next(); StringBuffer buffer = new StringBuffer("Name: "); String value = e.getKey(); if (value != null) { byte[] vb = value.getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); } buffer.append(value); buffer.append("\r\n"); make72Safe(buffer); dos.writeBytes(buffer.toString()); e.getValue().write(dos); } dos.flush(); } /** * Adds line breaks to enforce a maximum 72 bytes per line. */ static void make72Safe(StringBuffer line) { int length = line.length(); if (length > 72) { int index = 70; while (index < length - 2) { line.insert(index, "\r\n "); index += 72; length += 3; } } return; } /** * Reads the Manifest from the specified InputStream. The entry * names and attributes read will be merged in with the current * manifest entries. * * @param is the input stream * @exception IOException if an I/O error has occurred */ public void read(InputStream is) throws IOException { // Buffered input stream for reading manifest data FastInputStream fis = new FastInputStream(is); // Line buffer byte[] lbuf = new byte[512]; // Read the main attributes for the manifest attr.read(fis, lbuf); // Total number of entries, attributes read int ecount = 0, acount = 0; // Average size of entry attributes int asize = 2; // Now parse the manifest entries int len; String name = null; boolean skipEmptyLines = true; byte[] lastline = null; while ((len = fis.readLine(lbuf)) != -1) { if (lbuf[--len] != '\n') { throw new IOException("manifest line too long"); } if (len > 0 && lbuf[len-1] == '\r') { --len; } if (len == 0 && skipEmptyLines) { continue; } skipEmptyLines = false; if (name == null) { name = parseName(lbuf, len); if (name == null) { throw new IOException("invalid manifest format"); } if (fis.peek() == ' ') { // name is wrapped lastline = new byte[len - 6]; System.arraycopy(lbuf, 6, lastline, 0, len - 6); continue; } } else { // continuation line byte[] buf = new byte[lastline.length + len - 1]; System.arraycopy(lastline, 0, buf, 0, lastline.length); System.arraycopy(lbuf, 1, buf, lastline.length, len - 1); if (fis.peek() == ' ') { // name is wrapped lastline = buf; continue; } name = new String(buf, 0, buf.length, "UTF8"); lastline = null; } Attributes attr = getAttributes(name); if (attr == null) { attr = new Attributes(asize); entries.put(name, attr); } attr.read(fis, lbuf); ecount++; acount += attr.size(); //XXX: Fix for when the average is 0. When it is 0, // you get an Attributes object with an initial // capacity of 0, which tickles a bug in HashMap. asize = Math.max(2, acount / ecount); name = null; skipEmptyLines = true; } } private String parseName(byte[] lbuf, int len) { if (toLower(lbuf[0]) == 'n' && toLower(lbuf[1]) == 'a' && toLower(lbuf[2]) == 'm' && toLower(lbuf[3]) == 'e' && lbuf[4] == ':' && lbuf[5] == ' ') { try { return new String(lbuf, 6, len - 6, "UTF8"); } catch (Exception e) { } } return null; } private int toLower(int c) { return (c >= 'A' && c <= 'Z') ? 'a' + (c - 'A') : c; } /** * Returns true if the specified Object is also a Manifest and has * the same main Attributes and entries. * * @param o the object to be compared * @return true if the specified Object is also a Manifest and has * the same main Attributes and entries */ public boolean equals(Object o) { if (o instanceof Manifest) { Manifest m = (Manifest)o; return attr.equals(m.getMainAttributes()) && entries.equals(m.getEntries()); } else { return false; } } /** * Returns the hash code for this Manifest. */ public int hashCode() { return attr.hashCode() + entries.hashCode(); } /** * Returns a shallow copy of this Manifest. The shallow copy is * implemented as follows: * <pre> * public Object clone() { return new Manifest(this); } * </pre> * @return a shallow copy of this Manifest */ public Object clone() { return new Manifest(this); } /* * A fast buffered input stream for parsing manifest files. */ static class FastInputStream extends FilterInputStream { private byte buf[]; private int count = 0; private int pos = 0; FastInputStream(InputStream in) { /* We localize the InputStream since for z/OS the input will normally be //IBM-zos_bringup * EBCDIC and the readLine method of this class makes the assumption that //IBM-zos_bringup * the input is ASCII. We could mandate that manifest files must always //IBM-zos_bringup * be ASCII encoded; however this makes it difficult to write and maintain //IBM-zos_bringup * manifest files on z/OS. Also the build creates a manifest from a text //IBM-zos_bringup * file and edits using sed which work on EBCDIC data, for z/OS, hence we //IBM-zos_bringup * would otherwise need to fix up the build. //IBM-zos_bringup */ //IBM-zos_bringup this(LocalizedInputStream.localize(in), 8192); //IBM-zos_bringup //IBM-zos_bringup } FastInputStream(InputStream in, int size) { super(LocalizedInputStream.localize(in)); //IBM-zos_bringup buf = new byte[size]; } public int read() throws IOException { if (pos >= count) { fill(); if (pos >= count) { return -1; } } return Byte.toUnsignedInt(buf[pos++]); } public int read(byte[] b, int off, int len) throws IOException { int avail = count - pos; if (avail <= 0) { if (len >= buf.length) { return in.read(b, off, len); } fill(); avail = count - pos; if (avail <= 0) { return -1; } } if (len > avail) { len = avail; } System.arraycopy(buf, pos, b, off, len); pos += len; return len; } /* * Reads 'len' bytes from the input stream, or until an end-of-line * is reached. Returns the number of bytes read. */ public int readLine(byte[] b, int off, int len) throws IOException { byte[] tbuf = this.buf; int total = 0; while (total < len) { int avail = count - pos; if (avail <= 0) { fill(); avail = count - pos; if (avail <= 0) { return -1; } } int n = len - total; if (n > avail) { n = avail; } int tpos = pos; int maxpos = tpos + n; while (tpos < maxpos && tbuf[tpos++] != '\n') ; n = tpos - pos; System.arraycopy(tbuf, pos, b, off, n); off += n; total += n; pos = tpos; if (tbuf[tpos-1] == '\n') { break; } } return total; } public byte peek() throws IOException { if (pos == count) fill(); if (pos == count) return -1; // nothing left in buffer return buf[pos]; } public int readLine(byte[] b) throws IOException { return readLine(b, 0, b.length); } public long skip(long n) throws IOException { if (n <= 0) { return 0; } long avail = count - pos; if (avail <= 0) { return in.skip(n); } if (n > avail) { n = avail; } pos += n; return n; } public int available() throws IOException { return (count - pos) + in.available(); } public void close() throws IOException { if (in != null) { in.close(); in = null; buf = null; } } private void fill() throws IOException { count = pos = 0; int n = in.read(buf, 0, buf.length); if (n > 0) { count = n; } } } } //IBM-zos_bringup
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/xmltext/src/main/java/isostdisois_13584_32ed_1techxmlschemaontomlSimplified/ORGANIZATION.java
3684
/** */ package isostdisois_13584_32ed_1techxmlschemaontomlSimplified; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>ORGANIZATION</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getId <em>Id</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getName <em>Name</em>}</li> * <li>{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getDescription <em>Description</em>}</li> * </ul> * * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getORGANIZATION() * @model * @generated */ public interface ORGANIZATION extends EObject { /** * Returns the value of the '<em><b>Id</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Id</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Id</em>' attribute. * @see #setId(String) * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getORGANIZATION_Id() * @model * @generated */ String getId(); /** * Sets the value of the '{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getId <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Id</em>' attribute. * @see #getId() * @generated */ void setId(String value); /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getORGANIZATION_Name() * @model required="true" * @generated */ String getName(); /** * Sets the value of the '{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Description</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Description</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Description</em>' attribute. * @see #setDescription(String) * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getORGANIZATION_Description() * @model * @generated */ String getDescription(); /** * Sets the value of the '{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.ORGANIZATION#getDescription <em>Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Description</em>' attribute. * @see #getDescription() * @generated */ void setDescription(String value); } // ORGANIZATION
mit
jinchen92/JavaBasePractice
src/com/jinwen/thread/multithread/supplement/example4/Run4_threadCreateException3.java
1028
package com.jinwen.thread.multithread.supplement.example4; /** * P298 * 线程中出现异常,捕捉 */ public class Run4_threadCreateException3 { public static void main(String[] args) { Thread1.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { System.out.println("线程:" + t.getName() + " 出现了异常:"); e.printStackTrace(); } }); Thread1 t1 = new Thread1(); t1.setName("thread t1"); t1.start(); Thread1 t2 = new Thread1(); t2.setName("thread t2"); t2.start(); } } /* 输出: java.lang.NullPointerException at com.brianway.learning.java.multithread.supplement.example4.Thread1.run(Thread1.java:10) java.lang.NullPointerException at com.brianway.learning.java.multithread.supplement.example4.Thread1.run(Thread1.java:10) 线程:thread t1 出现了异常: 线程:thread t2 出现了异常: */
mit
DavidTanner/aws-beanstalk-publisher
src/main/java/org/jenkinsci/plugins/awsbeanstalkpublisher/AWSEBCredentials.java
4637
package org.jenkinsci.plugins.awsbeanstalkpublisher; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSCredentialsProviderChain; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.internal.StaticCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ModelObject; import hudson.util.FormValidation; public class AWSEBCredentials extends AbstractDescribableImpl<AWSEBCredentials> implements ModelObject { @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private final String name; private final String awsAccessKeyId; private final String awsSecretSharedKey; private final static Set<AWSEBCredentials> credentials = new HashSet<AWSEBCredentials>(); public String getName() { return name; } public String getAwsAccessKeyId() { return awsAccessKeyId; } public String getAwsSecretSharedKey() { return awsSecretSharedKey; } public Regions getAwsRegion() { return Regions.DEFAULT_REGION; } @DataBoundConstructor public AWSEBCredentials(String name, String awsAccessKeyId, String awsSecretSharedKey) { this.name = name; this.awsAccessKeyId = awsAccessKeyId; this.awsSecretSharedKey = awsSecretSharedKey; } public String getDisplayName() { return name + " : " + awsAccessKeyId; } public AWSCredentialsProvider getAwsCredentials() { AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(new BasicAWSCredentials(getAwsAccessKeyId(), getAwsSecretSharedKey()))); return credentials; } public static void configureCredentials(Collection<AWSEBCredentials> toAdd) { credentials.clear(); credentials.addAll(toAdd); } public static Set<AWSEBCredentials> getCredentials() { return credentials; } public static AWSEBCredentials getCredentialsByString(String credentialsString) { Set<AWSEBCredentials> credentials = getCredentials(); for (AWSEBCredentials credential : credentials) { if (credential.toString().equals(credentialsString)) { return credential; } } return null; } @Override public boolean equals(Object o) { if (!(o instanceof AWSEBCredentials)) { return false; } AWSEBCredentials creds = (AWSEBCredentials) o; boolean isSame = this.awsAccessKeyId.equals(creds.awsAccessKeyId); isSame &= this.name.equals(creds.name); return isSame; } @Override public String toString() { return name + " : " + awsAccessKeyId; } @Override public int hashCode() { return (awsAccessKeyId).hashCode(); } @Override public DescriptorImpl getDescriptor() { return DESCRIPTOR; } public final static class DescriptorImpl extends Descriptor<AWSEBCredentials> { @Override public String getDisplayName() { return "Credentials for Amazon Web Service"; } public FormValidation doLoadApplications(@QueryParameter("awsAccessKeyId") String accessKey, @QueryParameter("awsSecretSharedKey") String secretKey, @QueryParameter("awsRegion") String regionString) { if (accessKey == null || secretKey == null) { return FormValidation.error("Access key and Secret key cannot be empty"); } AWSEBCredentials credentials = new AWSEBCredentials("", accessKey, secretKey); Regions region = Enum.valueOf(Regions.class, regionString); if (region == null) { return FormValidation.error("Missing valid Region"); } List<ApplicationDescription> apps = AWSEBUtils.getApplications(credentials.getAwsCredentials(), region); StringBuilder sb = new StringBuilder(); for (ApplicationDescription app : apps) { sb.append(app.getApplicationName()); sb.append("\n"); } return FormValidation.ok(sb.toString()); } } }
mit
facebook/redex
test/instr/UsesNamesTest.java
1626
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.redex.test.instr; import java.lang.Runnable; import com.facebook.redex.annotations.UsesNames; import com.facebook.redex.annotations.UsesNamesTransitive; import com.facebook.annotations.OkToExtend; class Callsite { void use(@UsesNames ClassA a) { } void use2(@UsesNames InterB b, @UsesNames SubC c) { } void uses3(@UsesNamesTransitive ClassD d) { } // Check no strange behavior for external class void uses4(@UsesNamesTransitive Object o) { } // Check no strange behavior for primitive type void uses4(@UsesNamesTransitive int x) { } } class ClassA { int aField1; FieldAType aField2; int method1() { return 2; } static int method0() { return 6; } } @OkToExtend class SubA extends ClassA { int aField2; int method2() { return 1; } } class FieldAType { } interface InterB { abstract public int method3(); } class SubB implements InterB { int bField4; public int method3() { return 3; } } class C { int field6; int method6() { return 3; } } @OkToExtend class SubC extends C { int field7; int method7() { return 3; } } class ClassD { FieldDType field1; Runnable field2; int method9() { return 3; } } class FieldDType { int field; ClassD d2; // D->FieldDType->D is a cycle int method() { return 3; } } class FieldDType2 implements Runnable { public void run() { } } class NotUsed { int field5; public int method5() { return 3; } }
mit
arjanvlek/cyanogen-update-tracker-app
app/src/main/java/com/arjanvlek/cyngnotainfo/Support/UpdateDownloader.java
13204
package com.arjanvlek.cyngnotainfo.Support; import android.app.Activity; import android.app.DownloadManager; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.os.Handler; import com.arjanvlek.cyngnotainfo.Model.CyanogenOTAUpdate; import com.arjanvlek.cyngnotainfo.Model.DownloadProgressData; import com.arjanvlek.cyngnotainfo.R; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static android.app.DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR; import static android.app.DownloadManager.COLUMN_REASON; import static android.app.DownloadManager.COLUMN_STATUS; import static android.app.DownloadManager.COLUMN_TOTAL_SIZE_BYTES; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED; import static android.app.DownloadManager.STATUS_PAUSED; import static android.app.DownloadManager.STATUS_PENDING; import static android.app.DownloadManager.STATUS_RUNNING; import static android.os.Environment.DIRECTORY_DOWNLOADS; import static com.arjanvlek.cyngnotainfo.Support.SettingsManager.PROPERTY_DOWNLOAD_ID; import static com.arjanvlek.cyngnotainfo.Support.UpdateDownloader.DownloadSpeedUnits.BYTES; import static com.arjanvlek.cyngnotainfo.Support.UpdateDownloader.DownloadSpeedUnits.KILO_BYTES; import static com.arjanvlek.cyngnotainfo.Support.UpdateDownloader.DownloadSpeedUnits.MEGA_BYTES; import static java.math.BigDecimal.ROUND_CEILING; public class UpdateDownloader { private final Activity baseActivity; private final DownloadManager downloadManager; private final SettingsManager settingsManager; private UpdateDownloadListener listener; private List<Double> measurements = new ArrayList<>(); public final static int NOT_SET = -1; private boolean initialized; private long previousBytesDownloadedSoFar = NOT_SET; private long previousTimeStamp; private DownloadSpeedUnits previousSpeedUnits = BYTES; private double previousDownloadSpeed = NOT_SET; private long previousNumberOfSecondsRemaining = NOT_SET; public UpdateDownloader(Activity baseActivity) { this.baseActivity = baseActivity; this.downloadManager = (DownloadManager) baseActivity.getSystemService(Context.DOWNLOAD_SERVICE); this.settingsManager = new SettingsManager(baseActivity.getApplicationContext()); } public UpdateDownloader setUpdateDownloadListener(UpdateDownloadListener listener) { this.listener = listener; if(!initialized) { listener.onDownloadManagerInit(); initialized = true; } return this; } public void downloadUpdate(CyanogenOTAUpdate cyanogenOTAUpdate) { if(cyanogenOTAUpdate != null) { if(!cyanogenOTAUpdate.getDownloadUrl().contains("http")) { listener.onDownloadError(404); } else { Uri downloadUri = Uri.parse(cyanogenOTAUpdate.getDownloadUrl()); DownloadManager.Request request = new DownloadManager.Request(downloadUri) .setDescription(baseActivity.getString(R.string.download_description)) .setTitle(cyanogenOTAUpdate.getName() != null && !cyanogenOTAUpdate.getName().equals("null") && !cyanogenOTAUpdate.getName().isEmpty() ? cyanogenOTAUpdate.getName() : baseActivity.getString(R.string.download_unknown_update_name)) .setDestinationInExternalPublicDir(DIRECTORY_DOWNLOADS, cyanogenOTAUpdate.getFileName()) .setVisibleInDownloadsUi(false) .setNotificationVisibility(VISIBILITY_VISIBLE); long downloadID = downloadManager.enqueue(request); previousBytesDownloadedSoFar = NOT_SET; settingsManager.saveLongPreference(PROPERTY_DOWNLOAD_ID, downloadID); checkDownloadProgress(cyanogenOTAUpdate); listener.onDownloadStarted(downloadID); } } } public void cancelDownload() { if(settingsManager.containsPreference(PROPERTY_DOWNLOAD_ID)) { downloadManager.remove(settingsManager.getLongPreference(PROPERTY_DOWNLOAD_ID)); clearUp(); listener.onDownloadCancelled(); } } public void checkDownloadProgress(CyanogenOTAUpdate cyanogenOTAUpdate) { final long downloadId = settingsManager.getLongPreference(PROPERTY_DOWNLOAD_ID); if(settingsManager.containsPreference(PROPERTY_DOWNLOAD_ID)) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); Cursor cursor = downloadManager.query(query); if (cursor != null && cursor.moveToFirst()) { int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS)); switch (status) { case STATUS_PENDING: listener.onDownloadPending(); recheckDownloadProgress(cyanogenOTAUpdate, 1); break; case STATUS_PAUSED: listener.onDownloadPaused(cursor.getInt(cursor.getColumnIndex(COLUMN_REASON))); recheckDownloadProgress(cyanogenOTAUpdate, 5); break; case STATUS_RUNNING: int bytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(COLUMN_BYTES_DOWNLOADED_SO_FAR)); int totalSizeBytes = cursor.getInt(cursor.getColumnIndex(COLUMN_TOTAL_SIZE_BYTES)); DownloadProgressData eta = calculateDownloadETA(bytesDownloadedSoFar, totalSizeBytes); listener.onDownloadProgressUpdate(eta); previousBytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(COLUMN_BYTES_DOWNLOADED_SO_FAR)); recheckDownloadProgress(cyanogenOTAUpdate, 1); break; case DownloadManager.STATUS_SUCCESSFUL: clearUp(); listener.onDownloadComplete(); verifyDownload(cyanogenOTAUpdate); break; case DownloadManager.STATUS_FAILED: clearUp(); listener.onDownloadError(cursor.getInt(cursor.getColumnIndex(COLUMN_REASON))); break; } cursor.close(); } } } public void verifyDownload(CyanogenOTAUpdate cyanogenOTAUpdate) { new DownloadVerifier().execute(cyanogenOTAUpdate); } public boolean makeDownloadDirectory() { File downloadDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); return downloadDirectory.mkdirs(); } private void recheckDownloadProgress(final CyanogenOTAUpdate cyanogenOTAUpdate, int secondsDelay) { new Handler().postDelayed(new Runnable() { @Override public void run() { checkDownloadProgress(cyanogenOTAUpdate); } }, (secondsDelay * 1000)); } private void clearUp() { previousTimeStamp = NOT_SET; previousBytesDownloadedSoFar = NOT_SET; previousSpeedUnits = BYTES; previousDownloadSpeed = NOT_SET; previousNumberOfSecondsRemaining = NOT_SET; settingsManager.deletePreference(PROPERTY_DOWNLOAD_ID); } private DownloadProgressData calculateDownloadETA(long bytesDownloadedSoFar, long totalSizeBytes) { double bytesDownloadedInSecond; boolean validMeasurement = false; double downloadSpeed = NOT_SET; long numberOfSecondsRemaining = NOT_SET; long averageBytesPerSecond = NOT_SET; long currentTimeStamp = System.currentTimeMillis(); long bytesRemainingToDownload = totalSizeBytes - bytesDownloadedSoFar; DownloadSpeedUnits speedUnits = BYTES; if(previousBytesDownloadedSoFar != NOT_SET) { double numberOfElapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(currentTimeStamp - previousTimeStamp); if(numberOfElapsedSeconds > 0.0) { bytesDownloadedInSecond = (bytesDownloadedSoFar - previousBytesDownloadedSoFar) / (numberOfElapsedSeconds); } else { bytesDownloadedInSecond = 0; } // DownloadManager.query doesn't always have new data. If no new data is available, return the previously stored data to keep the UI showing that. validMeasurement = bytesDownloadedInSecond > 0 || numberOfElapsedSeconds > 5; if (validMeasurement) { // In case of no network, clear all measurements to allow displaying the now-unknown ETA... if (bytesDownloadedInSecond == 0) { measurements.clear(); } // Remove old measurements to keep the average calculation based on 5 measurements if (measurements.size() >= 5) { measurements.subList(0, 1).clear(); } measurements.add(bytesDownloadedInSecond); } // Calculate number of seconds remaining based off average download spead. averageBytesPerSecond = (long) calculateAverageBytesDownloadedInSecond(measurements); if (averageBytesPerSecond > 0) { numberOfSecondsRemaining = bytesRemainingToDownload / averageBytesPerSecond; } else { numberOfSecondsRemaining = NOT_SET; } } if(averageBytesPerSecond != NOT_SET) { if (averageBytesPerSecond >= 0 && averageBytesPerSecond < 1024) { downloadSpeed = averageBytesPerSecond; speedUnits = BYTES; } else if (averageBytesPerSecond >= 1024 && averageBytesPerSecond < 1048576) { downloadSpeed = new BigDecimal(averageBytesPerSecond).setScale(0, ROUND_CEILING).divide(new BigDecimal(1024), ROUND_CEILING).doubleValue(); speedUnits = KILO_BYTES; } else if (averageBytesPerSecond >= 1048576) { downloadSpeed = new BigDecimal(averageBytesPerSecond).setScale(2, ROUND_CEILING).divide(new BigDecimal(1048576), ROUND_CEILING).doubleValue(); speedUnits = MEGA_BYTES; } if(validMeasurement) { previousNumberOfSecondsRemaining = numberOfSecondsRemaining; previousTimeStamp = currentTimeStamp; previousDownloadSpeed = downloadSpeed; previousSpeedUnits = speedUnits; } else { downloadSpeed = previousDownloadSpeed; speedUnits = previousSpeedUnits; numberOfSecondsRemaining = previousNumberOfSecondsRemaining; } } previousBytesDownloadedSoFar = bytesDownloadedSoFar; int progress = 0; if(totalSizeBytes > 0.0) { progress = (int) ((bytesDownloadedSoFar * 100) / totalSizeBytes); } return new DownloadProgressData(downloadSpeed, speedUnits, numberOfSecondsRemaining, progress); } private double calculateAverageBytesDownloadedInSecond(List<Double> measurements) { if(measurements == null || measurements.isEmpty()) { return 0; } else { double totalBytesDownloadedInSecond = 0; for (Double measurementData : measurements) { totalBytesDownloadedInSecond += measurementData; } return totalBytesDownloadedInSecond / measurements.size(); } } private class DownloadVerifier extends AsyncTask<CyanogenOTAUpdate, Integer, Boolean> { @Override protected void onPreExecute() { listener.onVerifyStarted(); } @Override protected Boolean doInBackground(CyanogenOTAUpdate... params) { String filename = params[0].getFileName(); File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + filename); return params[0] == null || params[0].getMD5Sum() == null || MD5.checkMD5(params[0].getMD5Sum(), file); } @Override protected void onPostExecute(Boolean result) { if (result) { listener.onVerifyComplete(); clearUp(); } else { listener.onVerifyError(); clearUp(); } } } public enum DownloadSpeedUnits { BYTES("B/s"), KILO_BYTES("KB/s"), MEGA_BYTES("MB/s"); String stringValue; DownloadSpeedUnits(String stringValue) { this.stringValue = stringValue; } public String getStringValue() { return stringValue; } } }
mit
bafomdad/realfilingcabinet
com/bafomdad/realfilingcabinet/items/ItemManaFolder.java
3184
package com.bafomdad.realfilingcabinet.items; import java.util.List; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.GameRegistry; import vazkii.botania.api.mana.IManaItem; import vazkii.botania.api.mana.IManaTooltipDisplay; import com.bafomdad.realfilingcabinet.RealFilingCabinet; import com.bafomdad.realfilingcabinet.TabRFC; import com.bafomdad.realfilingcabinet.api.IFolder; import com.bafomdad.realfilingcabinet.integration.BotaniaRFC; import com.bafomdad.realfilingcabinet.utils.NBTUtils; public class ItemManaFolder extends Item implements IFolder, IManaItem, IManaTooltipDisplay { private static final String TAG_MANA_COUNT = "manaCount"; private static final String TAG_MAX_MANA_COUNT = "maxManaCount"; private static final int maxCount = 1000000000; public ItemManaFolder() { setRegistryName("folder_mana"); setTranslationKey(RealFilingCabinet.MOD_ID + ".manafolder"); setMaxStackSize(1); setCreativeTab(TabRFC.instance); } @Override public void addInformation(ItemStack stack, World player, List list, ITooltipFlag whatisthis) { int count = getManaSize(stack); list.add(BotaniaRFC.formatMana(count)); } public static void setManaSize(ItemStack stack, int count) { NBTUtils.setInt(stack, TAG_MANA_COUNT, Math.max(0, count)); } public static int getManaSize(ItemStack stack) { return NBTUtils.getInt(stack, TAG_MANA_COUNT, 0); } public static void addManaToFolder(ItemStack stack, int count) { int current = getManaSize(stack); setManaSize(stack, current + count); } public static boolean isManaFolderFull(ItemStack stack) { return getManaSize(stack) >= maxCount; } public static int getMaxManaFolder() { return maxCount; } // BOTANIA IMPLEMENTATION @Override public void addMana(ItemStack stack, int count) { this.addManaToFolder(stack, count); } @Override public boolean canExportManaToItem(ItemStack stack, ItemStack otherstack) { return true; } @Override public boolean canExportManaToPool(ItemStack stack, TileEntity pool) { return true; } @Override public boolean canReceiveManaFromItem(ItemStack stack, ItemStack otherstack) { return true; } @Override public boolean canReceiveManaFromPool(ItemStack stack, TileEntity pool) { return true; } @Override public int getMana(ItemStack stack) { return this.getManaSize(stack); } @Override public int getMaxMana(ItemStack stack) { return getMaxManaFolder(); } @Override public boolean isNoExport(ItemStack stack) { return false; } @Override public float getManaFractionForDisplay(ItemStack stack) { return (float)getManaSize(stack) / (float) getMaxMana(stack); } @Override public ItemStack isFolderEmpty(ItemStack stack) { return ItemStack.EMPTY; } @Override public boolean shouldCauseReequipAnimation(ItemStack oldstack, ItemStack newstack, boolean slotchanged) { return oldstack.getItem() != newstack.getItem(); } }
mit
AgileEAP/aglieEAP
agileEAP-core/src/main/java/com/agileEAP/utils/Cryptos.java
5621
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.agileEAP.utils; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.agileEAP.utils.Exceptions; /** * 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类. * * 支持Hex与Base64两种编码方式. * * @author calvin */ public class Cryptos { private static final String AES = "AES"; private static final String AES_CBC = "AES/CBC/PKCS5Padding"; private static final String HMACSHA1 = "HmacSHA1"; private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401 private static final int DEFAULT_AES_KEYSIZE = 128; private static final int DEFAULT_IVSIZE = 16; private static SecureRandom random = new SecureRandom(); //-- HMAC-SHA1 funciton --// /** * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节. * * @param input 原始输入字符数组 * @param key HMAC-SHA1密钥 */ public static byte[] hmacSha1(byte[] input, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, HMACSHA1); Mac mac = Mac.getInstance(HMACSHA1); mac.init(secretKey); return mac.doFinal(input); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 校验HMAC-SHA1签名是否正确. * * @param expected 已存在的签名 * @param input 原始输入字符串 * @param key 密钥 */ public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) { byte[] actual = hmacSha1(input, key); return Arrays.equals(expected, actual); } /** * 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节). * HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节). */ public static byte[] generateHmacSha1Key() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1); keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } //-- AES funciton --// /** * 使用AES加密原始字符串. * * @param input 原始输入字符数组 * @param key 符合AES要求的密钥 */ public static byte[] aesEncrypt(byte[] input, byte[] key) { return aes(input, key, Cipher.ENCRYPT_MODE); } /** * 使用AES加密原始字符串. * * @param input 原始输入字符数组 * @param key 符合AES要求的密钥 * @param iv 初始向量 */ public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) { return aes(input, key, iv, Cipher.ENCRYPT_MODE); } /** * 使用AES解密字符串, 返回原始字符串. * * @param input Hex编码的加密字符串 * @param key 符合AES要求的密钥 */ public static String aesDecrypt(byte[] input, byte[] key) { byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE); return new String(decryptResult); } /** * 使用AES解密字符串, 返回原始字符串. * * @param input Hex编码的加密字符串 * @param key 符合AES要求的密钥 * @param iv 初始向量 */ public static String aesDecrypt(byte[] input, byte[] key, byte[] iv) { byte[] decryptResult = aes(input, key, iv, Cipher.DECRYPT_MODE); return new String(decryptResult); } /** * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果. * * @param input 原始字节数组 * @param key 符合AES要求的密钥 * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE */ private static byte[] aes(byte[] input, byte[] key, int mode) { try { SecretKey secretKey = new SecretKeySpec(key, AES); Cipher cipher = Cipher.getInstance(AES); cipher.init(mode, secretKey); return cipher.doFinal(input); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果. * * @param input 原始字节数组 * @param key 符合AES要求的密钥 * @param iv 初始向量 * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE */ private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) { try { SecretKey secretKey = new SecretKeySpec(key, AES); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance(AES_CBC); cipher.init(mode, secretKey, ivSpec); return cipher.doFinal(input); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 生成AES密钥,返回字节数组, 默认长度为128位(16字节). */ public static byte[] generateAesKey() { return generateAesKey(DEFAULT_AES_KEYSIZE); } /** * 生成AES密钥,可选长度为128,192,256位. */ public static byte[] generateAesKey(int keysize) { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(AES); keyGenerator.init(keysize); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 生成随机向量,默认大小为cipher.getBlockSize(), 16字节. */ public static byte[] generateIV() { byte[] bytes = new byte[DEFAULT_IVSIZE]; random.nextBytes(bytes); return bytes; } }
mit
adelolmo/mine-sync
minesync-app/src/main/java/org/ado/minesync/commons/ZipArchiver.java
6874
/* * The MIT License (MIT) * * Copyright (c) 2015 Andoni del Olmo * * 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.ado.minesync.commons; import android.util.Log; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import java.io.*; import java.util.Date; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import static org.ado.minesync.config.AppConstants.L; import static org.apache.commons.io.FileUtils.forceMkdir; import static org.apache.commons.lang.Validate.notNull; public class ZipArchiver { private static final String TAG = ZipArchiver.class.getName(); private static final int BUFFER = 2048; public ZipArchiver() { super(); } public void zip(List<File> fileList, File zipFile) throws IOException { notNull(fileList, "fileList cannot be null"); notNull(zipFile, "zipFile cannot be null"); ALog.d(TAG, "Zip into [" + zipFile.getAbsolutePath() + "] elements [" + fileList + "]."); FileOutputStream dest = null; ZipOutputStream zout = null; Date startDate = new Date(); try { dest = new FileOutputStream(zipFile); zout = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for (File file : fileList) { if (L) Log.v(TAG, "Adding: " + file); if (file.isDirectory()) { for (File fileInDir : getSafeFiles(file)) { zipFile(zout, data, fileInDir, file.getName()); } } else { zipFile(zout, data, file, null); } } ALog.d(TAG, "Compression of [" + zipFile.getName() + "] took [" + (new Date().getTime() - startDate.getTime()) / 1000 + "]s"); } finally { IOUtils.closeQuietly(zout); IOUtils.closeQuietly(dest); } } public void unpackZip(String path, String zipname) throws IOException { this.unpackZip(new FileInputStream(path + zipname), null); } public void unpackZip(File zipFile, File outputDir) throws IOException { ALog.d(TAG, "unzip file [" + zipFile.getName() + "] to [" + outputDir.getAbsolutePath() + "]"); this.unpackZip(new FileInputStream(zipFile), outputDir); if (!zipFile.setLastModified(outputDir.lastModified())) { Log.w(TAG, "Unable to change modification date to cached zip file [" + zipFile.getName() + "]."); } } public void unpackZip(FileInputStream inputStream, File outputDir) throws IOException { notNull(inputStream, "inputStream cannot be null"); notNull(outputDir, "outputDir cannot be null"); ALog.d(TAG, "unzip stream to [" + outputDir.getAbsolutePath() + "]"); ZipInputStream zipInputStream = null; FileOutputStream fileOutputStream = null; try { String filename; zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry zipEntry; byte[] buffer = new byte[BUFFER]; int count; while ((zipEntry = zipInputStream.getNextEntry()) != null) { filename = zipEntry.getName(); ALog.v(TAG, "creating file [" + filename + "]."); if (isZipEntryInDirectory(zipEntry)) { File directory = new File(outputDir, getDirectoryName(filename)); forceMkdir(directory); } File file = new File(outputDir, filename); fileOutputStream = new FileOutputStream(file); while ((count = zipInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, count); } zipInputStream.closeEntry(); } } finally { IOUtils.closeQuietly(fileOutputStream); IOUtils.closeQuietly(zipInputStream); IOUtils.closeQuietly(inputStream); } } private File[] getSafeFiles(File file) { File[] files = file.listFiles(); if (files == null) { return new File[]{}; } return files; } private boolean isZipEntryInDirectory(ZipEntry zipEntry) { return zipEntry.getName().contains(File.separator); } private String getDirectoryName(String filename) { return filename.substring(0, filename.indexOf(File.separator)); } private void zipFile(ZipOutputStream zout, byte[] data, File file, String directoryName) throws IOException { BufferedInputStream origin = null; FileInputStream fi = null; try { if (file.exists()) { fi = new FileInputStream(file); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(getFilePath(file, directoryName)); zout.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zout.write(data, 0, count); } } else { ALog.w(TAG, "file \"%s\" does not exist.", file.getName()); } } finally { IOUtils.closeQuietly(fi); IOUtils.closeQuietly(origin); } } private String getFilePath(File file, String directoryName) { if (StringUtils.isNotEmpty(directoryName)) { return file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(directoryName), file.getAbsolutePath().length()); } else { return file.getName().substring(file.getName().lastIndexOf("/") + 1); } } }
mit
cliffano/swaggy-jenkins
clients/java-undertow-server/generated/src/main/java/org/openapitools/model/GithubOrganization.java
3859
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI document version: 1.1.2-pre.0 * Maintained by: blah@cliffano.com * * AUTO-GENERATED FILE, DO NOT MODIFY! */ package org.openapitools.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.GithubOrganizationlinks; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaUndertowServerCodegen", date = "2022-02-13T02:18:20.173053Z[Etc/UTC]") public class GithubOrganization { private String propertyClass; private GithubOrganizationlinks links; private Boolean jenkinsOrganizationPipeline; private String name; /** */ public GithubOrganization propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } @ApiModelProperty(value = "") @JsonProperty("_class") public String getPropertyClass() { return propertyClass; } public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } /** */ public GithubOrganization links(GithubOrganizationlinks links) { this.links = links; return this; } @ApiModelProperty(value = "") @JsonProperty("_links") public GithubOrganizationlinks getLinks() { return links; } public void setLinks(GithubOrganizationlinks links) { this.links = links; } /** */ public GithubOrganization jenkinsOrganizationPipeline(Boolean jenkinsOrganizationPipeline) { this.jenkinsOrganizationPipeline = jenkinsOrganizationPipeline; return this; } @ApiModelProperty(value = "") @JsonProperty("jenkinsOrganizationPipeline") public Boolean getJenkinsOrganizationPipeline() { return jenkinsOrganizationPipeline; } public void setJenkinsOrganizationPipeline(Boolean jenkinsOrganizationPipeline) { this.jenkinsOrganizationPipeline = jenkinsOrganizationPipeline; } /** */ public GithubOrganization name(String name) { this.name = name; return this; } @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GithubOrganization githubOrganization = (GithubOrganization) o; return Objects.equals(propertyClass, githubOrganization.propertyClass) && Objects.equals(links, githubOrganization.links) && Objects.equals(jenkinsOrganizationPipeline, githubOrganization.jenkinsOrganizationPipeline) && Objects.equals(name, githubOrganization.name); } @Override public int hashCode() { return Objects.hash(propertyClass, links, jenkinsOrganizationPipeline, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class GithubOrganization {\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append(" links: ").append(toIndentedString(links)).append("\n"); sb.append(" jenkinsOrganizationPipeline: ").append(toIndentedString(jenkinsOrganizationPipeline)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
mit
Tombio/Trafalert
Server/src/main/java/com/studiowannabe/trafalert/util/CollectionUtils.java
1076
package com.studiowannabe.trafalert.util; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class CollectionUtils { public static <T, K> List<T> map(final Collection<K> from, final Mapper<T, K> mapper) { final List<T> to = new ArrayList<T>(from.size()); for (final K k : from) { to.add(mapper.map(k)); } return to; } public static <T, K> List<T> mapWithoutNulls(final Collection<K> from, final Mapper<T, K> mapper) { if(org.springframework.util.CollectionUtils.isEmpty(from)){ return Collections.emptyList(); } final List<T> to = new ArrayList<>(); for (final K k : from) { if(k == null){ continue; } final T t = mapper.map(k); if(t != null) { to.add(t); } } return to; } public interface Mapper<K, T> extends Serializable { K map(final T t); } }
mit
kazi-mifta/Campus-App
app/src/main/java/com/campusapp/cuet/MyFirebaseMessagingService.java
2335
package com.campusapp.cuet; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import agency.tango.materialintro.R; //Firebase Service is For Sending Push Notification Instantly From Google Servers. public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "FROM:" + remoteMessage.getFrom()); //Check if the message contains data if(remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data: " + remoteMessage.getData()); } //Check if the message contains notification if(remoteMessage.getNotification() != null) { Log.d(TAG, "Mesage body:" + remoteMessage.getNotification().getBody()); sendNotification(remoteMessage.getNotification().getBody()); } } /** * Dispay the notification * @param body */ private void sendNotification(String body) { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT); //Set sound of notification Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.cuet) .setContentTitle("CUET Campus") .setContentText(body) .setAutoCancel(true) .setSound(notificationSound) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /*ID of notification*/, notifiBuilder.build()); } }
mit
koher/Variance4J
src/org/koherent/variance/Variance.java
1626
package org.koherent.variance; import javax.lang.model.element.TypeParameterElement; public enum Variance { INVARIANT, COVARIANT, CONTRAVARIANT, BIVARIANT; private boolean covariant; private boolean contravariant; static { COVARIANT.covariant = true; CONTRAVARIANT.contravariant = true; BIVARIANT.covariant = true; BIVARIANT.contravariant = true; } public static Variance of(boolean covariant, boolean contravariant) { return covariant ? (contravariant ? BIVARIANT : COVARIANT) : (contravariant ? CONTRAVARIANT : INVARIANT); } public static Variance of(TypeParameterElement typeParameter) throws IllegalArgumentException { if (typeParameter == null) { throw new IllegalArgumentException( "'typeParameter' cannot be null."); } return of(typeParameter.getAnnotation(Out.class) != null, typeParameter.getAnnotation(In.class) != null); } public boolean isCovariant() { return covariant; } public boolean isContravariant() { return contravariant; } public boolean isValidCovariantly() { return !contravariant; } public boolean isValidContravariantly() { return !covariant; } public Variance transpose() { return of(contravariant, covariant); } public Variance not() { return of(!covariant, !contravariant); } public static Variance and(Variance left, Variance right) { return Variance.of(left.covariant && right.covariant, left.contravariant && right.contravariant); } public static Variance or(Variance left, Variance right) { return Variance.of(left.covariant || right.covariant, left.contravariant || right.contravariant); } }
mit
yazeed44/CdpneIntroTelegramBot
src/net/yazeed44/cdpnebot/CdpneIntroBot.java
8214
package net.yazeed44.cdpnebot; import java.util.ArrayList; import java.util.HashMap; import org.telegram.BotConfig; import org.telegram.SenderHelper; import org.telegram.api.ForceReplyKeyboard; import org.telegram.api.Message; import org.telegram.api.Update; import org.telegram.methods.SendMessage; import org.telegram.updateshandlers.UpdatesCallback; import org.telegram.updatesreceivers.UpdatesThread; public class CdpneIntroBot implements UpdatesCallback { public static final String TOKEN = BotConfig.TOKEN_CDPNE; public static final SendMessage DEFAULT_MESSAGE = new SendMessage(); public static final ForceReplyKeyboard DEFAULT_FORCE_REPLY = new ForceReplyKeyboard(); public static final HashMap<Integer,Introduction> INTROS = new HashMap<>(); public CdpneIntroBot(){ SenderHelper.SendWebhook("", TOKEN); new UpdatesThread(TOKEN, this); setup(); } @Override public void onUpdateReceived(Update update) { if (update.getMessage().getNewChatParticipant() != null){ sendWelcomeMessage(update.getMessage()); } if (update.getMessage() != null && update.getMessage().hasText()){ final Message message = update.getMessage(); if (hasCommandedToStart(message)){ handleStartCommand(message); } else if (hasCommandedToDeleteIntro(message)){ deleteIntro(message); } else if (hasCommandedToBrowseAllIntros(message)){ queryAllIntrosAndShowThem(message); } else if (hasCommandedToSearchSpectifcIntro(message)){ queryUserAndShowIntro(message); } else if (message.hasReplayMessage()){ handleAnswers(message); } } } private void sendWelcomeMessage(final Message message) { DEFAULT_MESSAGE.setText("أهلا بك يا " + message.getNewChatParticipant().getFirstName() + " " + CustomMessages.MESSAGE_WELCOME_NEW_MEMBER); replyWithoutForce(message); } private void setup(){ DEFAULT_FORCE_REPLY.setForceReply(true); DEFAULT_FORCE_REPLY.setSelective(true); DEFAULT_MESSAGE.setReplayMarkup(DEFAULT_FORCE_REPLY); } private void queryAllIntrosAndShowThem(final Message message) { final ArrayList<Introduction> intros = DbUtil.getIntros(); if (intros.isEmpty()){ DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_THERE_IS_NO_INTROS); replyWithoutForce(message); } else { final StringBuilder introsTextBuilder = new StringBuilder(); for(final Introduction intro : intros){ introsTextBuilder.append(intro.generateIntroText()) .append("\n \n") ; } DEFAULT_MESSAGE.setText(introsTextBuilder.toString()); replyWithoutForce(message); intros.clear(); } } private boolean hasCommandedToBrowseAllIntros(final Message message) { return message.getText().startsWith(Commands.COMMAND_BROWSE_ALL_INTRODUCTIONS); } private void queryUserAndShowIntro(final Message message) { final String command = message.getText(); final String username; if (command.contains(" ")){ username = command.split(" ")[1]; if (!DbUtil.isUserInsertedInDb(username)){ DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_USER_HAS_NO_INTRO); replyWithoutForce(message); return; } } else { //By default the username is the caller username if (DbUtil.isUserInsertedInDb(message.getFrom().getId())){ username = message.getFrom().getUserName(); } else { handleStartCommand(message); return; } } final Introduction intro = DbUtil.getIntro(username); DEFAULT_MESSAGE.setText(intro.generateIntroText()); replyWithoutForce(message); } private boolean hasCommandedToSearchSpectifcIntro(final Message message) { return message.getText().startsWith(Commands.COMMAND_SEARCH_FOR_SPECTIFC_INTRODUCTION); } private void handleStartCommand(final Message message){ if (!DbUtil.isUserInsertedInDb(message.getFrom().getId())){ //He isn't registerd in db if (message.getFrom().getUserName().isEmpty()){ //Has no username tellCallerToCreateUsername(message); return; } else { askAboutCity(message); } } else { explainHowToDeleteIntro(message); } } private void tellCallerToCreateUsername(final Message message) { DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_CALLER_HAS_NO_USERNAME); replyWithoutForce(message); } private void explainHowToDeleteIntro(final Message message) { DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_YOU_ALREADY_CREATED_AN_INTRO); replyWithoutForce(message); } private void deleteIntro(Message message) { DbUtil.deleteIntro(message.getFrom().getId()); DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_AFTER_DELETE_INTRO); replyWithoutForce(message); } private boolean hasCommandedToDeleteIntro(Message message) { return message.getText().startsWith(Commands.COMMAND_DELETE_INTRO); } private void handleAnswers(final Message message){ if (hasAnswerdAboutCity(message)){ final Introduction intro = new Introduction(message.getFrom().getId(),message.getText()); intro.setUsername(message.getFrom().getUserName()); INTROS.put(message.getFrom().getId(), intro); askAboutHobbies(message); } else if (hasAnsweredAboutHobbies(message)){ INTROS.get(message.getFrom().getId()).setHobbies(message.getText()); askAboutPreferedTraitsInRoommate(message); } else if (hasAnsweredAboutPreferedTraitsInRoommate(message)){ INTROS.get(message.getFrom().getId()).setPreferedTraitsInRoommate(message.getText()); askAboutUnpreferedTraitsInRoomate(message); } else if (hasAnsweredAboutUnpreferedTraitsInRoommate(message)){ final Introduction intro = INTROS.get(message.getFrom().getId()); if (intro == null){ return; } intro.setUnpreferedTraitsInRoommate(message.getText()); DbUtil.insertIntro(intro); INTROS.remove(message.getFrom().getId()); congratulateOnCompletation(message); } } private void congratulateOnCompletation(Message message) { DEFAULT_MESSAGE.setText(CustomMessages.MESSAGE_CONGRATS_ON_COMPILATION); DEFAULT_MESSAGE.setReplayMarkup(null); replyAndSend(message); DEFAULT_MESSAGE.setReplayMarkup(DEFAULT_FORCE_REPLY); } private boolean hasAnsweredAboutUnpreferedTraitsInRoommate(final Message message) { return CustomMessages.QUESTION_UNPREFERED_TRAITS_IN_ROOMMATE.equals(message.getReplyToMessage().getText()); } private void askAboutUnpreferedTraitsInRoomate(final Message message) { DEFAULT_MESSAGE.setText(CustomMessages.QUESTION_UNPREFERED_TRAITS_IN_ROOMMATE); replyAndSend(message); } private boolean hasAnsweredAboutPreferedTraitsInRoommate(final Message message) { return CustomMessages.QUESTION_PREFERED_TRAITS_IN_ROOMMATE.equals(message.getReplyToMessage().getText()); } private void askAboutPreferedTraitsInRoommate(final Message message) { DEFAULT_MESSAGE.setText(CustomMessages.QUESTION_PREFERED_TRAITS_IN_ROOMMATE); replyAndSend(message); } private boolean hasAnsweredAboutHobbies(final Message message) { return CustomMessages.QUESTION_HOBBIES.equals(message.getReplyToMessage().getText()); } private void askAboutHobbies(Message message) { DEFAULT_MESSAGE.setText(CustomMessages.QUESTION_HOBBIES); replyAndSend(message); } private boolean hasAnswerdAboutCity(Message message) { return CustomMessages.QUESTION_CITY.equals(message.getReplyToMessage().getText()); } private boolean hasCommandedToStart(final Message message){ return message.getText().startsWith(Commands.COMMAND_START); } private void askAboutCity(final Message message){ DEFAULT_MESSAGE.setText(CustomMessages.QUESTION_CITY); replyAndSend(message); } private void replyAndSend(final Message message){ DEFAULT_MESSAGE.setChatId(message.getChatId()); DEFAULT_MESSAGE.setReplayToMessageId(message.getMessageId()); SenderHelper.SendMessage(DEFAULT_MESSAGE, TOKEN); } private void replyWithoutForce(final Message mesasge){ DEFAULT_MESSAGE.setReplayMarkup(null); replyAndSend(mesasge); DEFAULT_MESSAGE.setReplayMarkup(DEFAULT_FORCE_REPLY); } }
mit
martindisch/KnowledgeBase
app/src/main/java/com/martin/knowledgebase/PlainStorage.java
939
package com.martin.knowledgebase; import java.util.ArrayList; public class PlainStorage { private static PlainStorage instance; private boolean mNewInstance; private ArrayList<Entry> mEntries; // Restrict the constructor from being instantiated private PlainStorage() { } public static synchronized PlainStorage getInstance() { if (instance == null) { instance = new PlainStorage(); instance.mNewInstance = true; instance.mEntries = new ArrayList<Entry>(); } else { instance.mNewInstance = false; } return instance; } public boolean isNew() { boolean before = mNewInstance; mNewInstance = false; return before; } public ArrayList<Entry> getmEntries() { return mEntries; } public void setmEntries(ArrayList<Entry> mEntries) { this.mEntries = mEntries; } }
mit
asofdate/batch-scheduler
auth/src/main/java/com/asofdate/utils/factory/AuthDTOFactory.java
274
package com.asofdate.utils.factory; import com.asofdate.hauth.dto.AuthDto; /** * Created by hzwy23 on 2017/6/29. */ public class AuthDTOFactory { public static AuthDto getAuthDTO(Boolean status, String message) { return new AuthDto(status, message); } }
mit
vincentzhang96/HearthCaptureLib
src/main/java/co/phoenixlab/hearthstone/hearthcapturelib/packets/Packet019GameState.java
2149
/* * The MIT License (MIT) * * Copyright (c) 2014 Vincent Zhang * * 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 co.phoenixlab.hearthstone.hearthcapturelib.packets; import co.phoenixlab.hearthstone.hearthcapturelib.GameEnums; import co.phoenixlab.hearthstone.hearthcapturelib.packets.encoding.FieldNumber; import co.phoenixlab.hearthstone.hearthcapturelib.packets.encoding.FieldType; import co.phoenixlab.hearthstone.hearthcapturelib.packets.structs.powerhistory.GameState; /** * Contains information about the current game state since the last game state packet. Server to Client only. * * @author Vincent Zhang */ public class Packet019GameState extends CapturePacket { @FieldNumber(1) @FieldType(GameEnums.DataType.STRUCT) private GameState[] states; public Packet019GameState() { states = new GameState[0]; } /** * A sequence of GameStates detailing various aspects of the game. * * @see co.phoenixlab.hearthstone.hearthcapturelib.packets.structs.powerhistory.GameState */ public GameState[] getStates() { return states; } }
mit
boggad/jdk9-sample
sample-catalog/spring-jdk9/src/spring.jdbc/org/springframework/jdbc/core/simple/SimpleJdbcInsertOperations.java
6559
/* * Copyright 2002-2016 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.springframework.jdbc.core.simple; import java.util.Map; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor; /** * Interface specifying the API for a Simple JDBC Insert implemented by {@link SimpleJdbcInsert}. * This interface is not often used directly, but provides the option to enhance testability, * as it can easily be mocked or stubbed. * * @author Thomas Risberg * @since 2.5 */ public interface SimpleJdbcInsertOperations { /** * Specify the table name to be used for the insert. * @param tableName the name of the stored table * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations withTableName(String tableName); /** * Specify the schema name, if any, to be used for the insert. * @param schemaName the name of the schema * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations withSchemaName(String schemaName); /** * Specify the catalog name, if any, to be used for the insert. * @param catalogName the name of the catalog * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations withCatalogName(String catalogName); /** * Specify the column names that the insert statement should be limited to use. * @param columnNames one or more column names * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations usingColumns(String... columnNames); /** * Specify the names of any columns that have auto generated keys. * @param columnNames one or more column names * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations usingGeneratedKeyColumns(String... columnNames); /** * Turn off any processing of column meta data information obtained via JDBC. * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations withoutTableColumnMetaDataAccess(); /** * Include synonyms for the column meta data lookups via JDBC. * Note: this is only necessary to include for Oracle since other * databases supporting synonyms seems to include the synonyms * automatically. * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations includeSynonymsForTableColumnMetaData(); /** * Use a the provided NativeJdbcExtractor during the column meta data * lookups via JDBC. * Note: this is only necessary to include when running with a connection pool * that wraps the meta data connection and when using a database like Oracle * where it is necessary to access the native connection to include synonyms. * @return the instance of this SimpleJdbcInsert */ SimpleJdbcInsertOperations useNativeJdbcExtractorForMetaData(NativeJdbcExtractor nativeJdbcExtractor); /** * Execute the insert using the values passed in. * @param args Map containing column names and corresponding value * @return the number of rows affected as returned by the JDBC driver */ int execute(Map<String, ?> args); /** * Execute the insert using the values passed in. * @param parameterSource SqlParameterSource containing values to use for insert * @return the number of rows affected as returned by the JDBC driver */ int execute(SqlParameterSource parameterSource); /** * Execute the insert using the values passed in and return the generated key. * <p>This requires that the name of the columns with auto generated keys have been specified. * This method will always return a KeyHolder but the caller must verify that it actually * contains the generated keys. * @param args Map containing column names and corresponding value * @return the generated key value */ Number executeAndReturnKey(Map<String, ?> args); /** * Execute the insert using the values passed in and return the generated key. * <p>This requires that the name of the columns with auto generated keys have been specified. * This method will always return a KeyHolder but the caller must verify that it actually * contains the generated keys. * @param parameterSource SqlParameterSource containing values to use for insert * @return the generated key value. */ Number executeAndReturnKey(SqlParameterSource parameterSource); /** * Execute the insert using the values passed in and return the generated keys. * <p>This requires that the name of the columns with auto generated keys have been specified. * This method will always return a KeyHolder but the caller must verify that it actually * contains the generated keys. * @param args Map containing column names and corresponding value * @return the KeyHolder containing all generated keys */ KeyHolder executeAndReturnKeyHolder(Map<String, ?> args); /** * Execute the insert using the values passed in and return the generated keys. * <p>This requires that the name of the columns with auto generated keys have been specified. * This method will always return a KeyHolder but the caller must verify that it actually * contains the generated keys. * @param parameterSource SqlParameterSource containing values to use for insert * @return the KeyHolder containing all generated keys */ KeyHolder executeAndReturnKeyHolder(SqlParameterSource parameterSource); /** * Execute a batch insert using the batch of values passed in. * @param batch an array of Maps containing a batch of column names and corresponding value * @return the array of number of rows affected as returned by the JDBC driver */ @SuppressWarnings("unchecked") int[] executeBatch(Map<String, ?>... batch); /** * Execute a batch insert using the batch of values passed in. * @param batch an array of SqlParameterSource containing values for the batch * @return the array of number of rows affected as returned by the JDBC driver */ int[] executeBatch(SqlParameterSource... batch); }
mit
thewinniewu/lightmeter
app/src/main/java/com/www/lightmeter/Variable.java
2111
package com.www.lightmeter; import android.util.Log; import java.util.HashMap; import java.util.Map; public class Variable { double[] keys; Map<Double, String> vals = new HashMap<>(); int currentIndex; public Variable(double[] keys, String[] strings) { currentIndex = 0; this.keys = keys; if (strings == null) { for (int i = 0, maplen = keys.length; i < maplen; i++) { Log.e("www", "making new variable. keys[i] : " + keys[i] + "Double: " + Double.valueOf(keys[i])); vals.put(Double.valueOf(keys[i]), formatDoubleString("" + keys[i])); } } else { for (int i = 0, maplen = Math.min(keys.length, strings.length); i < maplen; i++) { vals.put(Double.valueOf(keys[i]), strings[i]); } } } public double getCurrentVal() { return keys[currentIndex]; } public String getCurrentValAsString() { return valToString(keys[currentIndex]); } public double nextVal() { currentIndex = Math.min(currentIndex + 1, keys.length - 1); return keys[currentIndex]; } public double prevVal() { currentIndex = Math.max(currentIndex - 1, 0); return keys[currentIndex]; } String valToString(double val) { return vals.get(val); } private String formatDoubleString(String string) { String newString = ""; for (int i = 0; i < string.length(); i++) { if (i < string.length() - 1 && string.charAt(i) == '.' && string.charAt(i + 1) == '0') { i++; continue; } newString += string.charAt(i); } return newString; } double setQuantizedValue(double actual) { double correctVal = -1; for (int i = 0; i < keys.length; i++) { if (actual > keys[i]) { continue; } else { correctVal = keys[i]; currentIndex = i; break; } } return correctVal; } }
mit
yourtion/LearningFunctionalProgramming
Java/src/com/yourtion/Pattern11/ex1/VideoService.java
479
/*** * Excerpted from "Functional Programming Patterns", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/mbfpp for more book information. ***/ package com.yourtion.Pattern11.ex1; public class VideoService { }
mit
fingo/urlopia
src/main/java/info/fingo/urlopia/api/v2/reports/attendance/resolver/handlers/user/params/resolver/MonthlyAttendanceListReportDayHandler.java
3832
package info.fingo.urlopia.api.v2.reports.attendance.resolver.handlers.user.params.resolver; import info.fingo.urlopia.api.v2.presence.PresenceConfirmationService; import info.fingo.urlopia.holidays.HolidayService; import info.fingo.urlopia.reports.ReportStatusFromRequestType; import info.fingo.urlopia.request.Request; import info.fingo.urlopia.request.RequestService; import info.fingo.urlopia.user.User; import java.text.DecimalFormat; import java.time.DateTimeException; import java.time.LocalDate; public class MonthlyAttendanceListReportDayHandler { private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(); private static final String DEFAULT_VALUE = "-"; private static final String EMPTY_VALUE = ""; private final HolidayService holidayService; private final RequestService requestService; private final PresenceConfirmationService presenceConfirmationService; public MonthlyAttendanceListReportDayHandler(HolidayService holidayService, RequestService requestService, PresenceConfirmationService presenceConfirmationService) { this.holidayService = holidayService; this.requestService = requestService; this.presenceConfirmationService = presenceConfirmationService; } public String handle(int year, int month, int dayOfMonth, User user) { if (user == null) { return EMPTY_VALUE; } var currentDate = LocalDate.now(); try { var handleDate = LocalDate.of(year, month, dayOfMonth); var isDateInPast = handleDate.isBefore(currentDate); if (holidayService.isWorkingDay(handleDate)) { var resolvedValue = requestService .getByUserAndDate(user.getId(), handleDate).stream() .filter(req -> req.getStatus() == Request.Status.ACCEPTED) .map(this::handleRequest) .findFirst() .orElse(handlePresence(handleDate, user)); if (shouldReturnEmptyValue(resolvedValue, isDateInPast)) { return EMPTY_VALUE; } return resolvedValue; } } catch (DateTimeException e) { // if day does not exist then default value } return DEFAULT_VALUE; } private String handleRequest(Request request) { var requestType = request.getType(); var specialTypeInfo = request.getSpecialTypeInfo(); return switch (requestType) { case NORMAL -> ReportStatusFromRequestType.NORMAL.getMonthlyPresenceReportStatus(); case OCCASIONAL -> ReportStatusFromRequestType.OCCASIONAL.getMonthlyPresenceReportStatus(); case SPECIAL -> ReportStatusFromRequestType.valueOf(specialTypeInfo).getMonthlyPresenceReportStatus(); }; } private String handlePresence(LocalDate date, User user) { var presenceConfirmations = presenceConfirmationService.getByUserAndDate(user.getId(), date); if (presenceConfirmations.isEmpty()) { return DEFAULT_VALUE; } return DECIMAL_FORMAT.format(presenceConfirmationService.countWorkingHoursInDay(presenceConfirmations.get(0))); } private boolean isDefault(String resolvedValue) { return DEFAULT_VALUE.equals(resolvedValue); } private boolean shouldReturnEmptyValue(String resolvedValue, boolean isDayInPast) { return isDefault(resolvedValue) && !isDayInPast; } }
mit
fingo/urlopia
src/main/java/info/fingo/urlopia/config/mail/send/HandlebarsHelper.java
352
package info.fingo.urlopia.config.mail.send; import com.github.jknack.handlebars.Options; import java.io.IOException; public class HandlebarsHelper { public String ifeq(Object val, String val2, Options options) throws IOException { return val.equals(val2) ? options.fn().toString().trim() : ""; } }
mit
zyhndesign/DesignCompetition
src/main/java/com/cidic/design/exception/CaptchaException.java
480
package com.cidic.design.exception; import org.apache.shiro.authc.AuthenticationException; public class CaptchaException extends AuthenticationException { private static final long serialVersionUID = 1L; public CaptchaException() { super(); } public CaptchaException(String message, Throwable cause) { super(message, cause); } public CaptchaException(String message) { super(message); } public CaptchaException(Throwable cause) { super(cause); } }
mit
Azure/azure-sdk-for-java
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/models/AttachedDatabaseConfiguration.java
12695
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.models; import com.azure.core.management.Region; import com.azure.core.management.SystemData; import com.azure.core.util.Context; import com.azure.resourcemanager.synapse.fluent.models.AttachedDatabaseConfigurationInner; import java.util.List; /** An immutable client-side representation of AttachedDatabaseConfiguration. */ public interface AttachedDatabaseConfiguration { /** * Gets the id property: Fully qualified resource Id for the resource. * * @return the id value. */ String id(); /** * Gets the name property: The name of the resource. * * @return the name value. */ String name(); /** * Gets the type property: The type of the resource. * * @return the type value. */ String type(); /** * Gets the location property: Resource location. * * @return the location value. */ String location(); /** * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. * * @return the systemData value. */ SystemData systemData(); /** * Gets the provisioningState property: The provisioned state of the resource. * * @return the provisioningState value. */ ResourceProvisioningState provisioningState(); /** * Gets the databaseName property: The name of the database which you would like to attach, use * if you want to * follow all current and future databases. * * @return the databaseName value. */ String databaseName(); /** * Gets the kustoPoolResourceId property: The resource id of the kusto pool where the databases you would like to * attach reside. * * @return the kustoPoolResourceId value. */ String kustoPoolResourceId(); /** * Gets the attachedDatabaseNames property: The list of databases from the clusterResourceId which are currently * attached to the kusto pool. * * @return the attachedDatabaseNames value. */ List<String> attachedDatabaseNames(); /** * Gets the defaultPrincipalsModificationKind property: The default principals modification kind. * * @return the defaultPrincipalsModificationKind value. */ DefaultPrincipalsModificationKind defaultPrincipalsModificationKind(); /** * Gets the tableLevelSharingProperties property: Table level sharing specifications. * * @return the tableLevelSharingProperties value. */ TableLevelSharingProperties tableLevelSharingProperties(); /** * Gets the region of the resource. * * @return the region of the resource. */ Region region(); /** * Gets the name of the resource region. * * @return the name of the resource region. */ String regionName(); /** * Gets the inner com.azure.resourcemanager.synapse.fluent.models.AttachedDatabaseConfigurationInner object. * * @return the inner object. */ AttachedDatabaseConfigurationInner innerModel(); /** The entirety of the AttachedDatabaseConfiguration definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { } /** The AttachedDatabaseConfiguration definition stages. */ interface DefinitionStages { /** The first stage of the AttachedDatabaseConfiguration definition. */ interface Blank extends WithParentResource { } /** The stage of the AttachedDatabaseConfiguration definition allowing to specify parent resource. */ interface WithParentResource { /** * Specifies workspaceName, kustoPoolName, resourceGroupName. * * @param workspaceName The name of the workspace. * @param kustoPoolName The name of the Kusto pool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @return the next definition stage. */ WithCreate withExistingKustoPool(String workspaceName, String kustoPoolName, String resourceGroupName); } /** * The stage of the AttachedDatabaseConfiguration definition which contains all the minimum required properties * for the resource to be created, but also allows for any other optional properties to be specified. */ interface WithCreate extends DefinitionStages.WithLocation, DefinitionStages.WithDatabaseName, DefinitionStages.WithKustoPoolResourceId, DefinitionStages.WithDefaultPrincipalsModificationKind, DefinitionStages.WithTableLevelSharingProperties { /** * Executes the create request. * * @return the created resource. */ AttachedDatabaseConfiguration create(); /** * Executes the create request. * * @param context The context to associate with this operation. * @return the created resource. */ AttachedDatabaseConfiguration create(Context context); } /** The stage of the AttachedDatabaseConfiguration definition allowing to specify location. */ interface WithLocation { /** * Specifies the region for the resource. * * @param location Resource location. * @return the next definition stage. */ WithCreate withRegion(Region location); /** * Specifies the region for the resource. * * @param location Resource location. * @return the next definition stage. */ WithCreate withRegion(String location); } /** The stage of the AttachedDatabaseConfiguration definition allowing to specify databaseName. */ interface WithDatabaseName { /** * Specifies the databaseName property: The name of the database which you would like to attach, use * if * you want to follow all current and future databases.. * * @param databaseName The name of the database which you would like to attach, use * if you want to follow * all current and future databases. * @return the next definition stage. */ WithCreate withDatabaseName(String databaseName); } /** The stage of the AttachedDatabaseConfiguration definition allowing to specify kustoPoolResourceId. */ interface WithKustoPoolResourceId { /** * Specifies the kustoPoolResourceId property: The resource id of the kusto pool where the databases you * would like to attach reside.. * * @param kustoPoolResourceId The resource id of the kusto pool where the databases you would like to attach * reside. * @return the next definition stage. */ WithCreate withKustoPoolResourceId(String kustoPoolResourceId); } /** * The stage of the AttachedDatabaseConfiguration definition allowing to specify * defaultPrincipalsModificationKind. */ interface WithDefaultPrincipalsModificationKind { /** * Specifies the defaultPrincipalsModificationKind property: The default principals modification kind. * * @param defaultPrincipalsModificationKind The default principals modification kind. * @return the next definition stage. */ WithCreate withDefaultPrincipalsModificationKind( DefaultPrincipalsModificationKind defaultPrincipalsModificationKind); } /** * The stage of the AttachedDatabaseConfiguration definition allowing to specify tableLevelSharingProperties. */ interface WithTableLevelSharingProperties { /** * Specifies the tableLevelSharingProperties property: Table level sharing specifications. * * @param tableLevelSharingProperties Table level sharing specifications. * @return the next definition stage. */ WithCreate withTableLevelSharingProperties(TableLevelSharingProperties tableLevelSharingProperties); } } /** * Begins update for the AttachedDatabaseConfiguration resource. * * @return the stage of resource update. */ AttachedDatabaseConfiguration.Update update(); /** The template for AttachedDatabaseConfiguration update. */ interface Update extends UpdateStages.WithDatabaseName, UpdateStages.WithKustoPoolResourceId, UpdateStages.WithDefaultPrincipalsModificationKind, UpdateStages.WithTableLevelSharingProperties { /** * Executes the update request. * * @return the updated resource. */ AttachedDatabaseConfiguration apply(); /** * Executes the update request. * * @param context The context to associate with this operation. * @return the updated resource. */ AttachedDatabaseConfiguration apply(Context context); } /** The AttachedDatabaseConfiguration update stages. */ interface UpdateStages { /** The stage of the AttachedDatabaseConfiguration update allowing to specify databaseName. */ interface WithDatabaseName { /** * Specifies the databaseName property: The name of the database which you would like to attach, use * if * you want to follow all current and future databases.. * * @param databaseName The name of the database which you would like to attach, use * if you want to follow * all current and future databases. * @return the next definition stage. */ Update withDatabaseName(String databaseName); } /** The stage of the AttachedDatabaseConfiguration update allowing to specify kustoPoolResourceId. */ interface WithKustoPoolResourceId { /** * Specifies the kustoPoolResourceId property: The resource id of the kusto pool where the databases you * would like to attach reside.. * * @param kustoPoolResourceId The resource id of the kusto pool where the databases you would like to attach * reside. * @return the next definition stage. */ Update withKustoPoolResourceId(String kustoPoolResourceId); } /** * The stage of the AttachedDatabaseConfiguration update allowing to specify defaultPrincipalsModificationKind. */ interface WithDefaultPrincipalsModificationKind { /** * Specifies the defaultPrincipalsModificationKind property: The default principals modification kind. * * @param defaultPrincipalsModificationKind The default principals modification kind. * @return the next definition stage. */ Update withDefaultPrincipalsModificationKind( DefaultPrincipalsModificationKind defaultPrincipalsModificationKind); } /** The stage of the AttachedDatabaseConfiguration update allowing to specify tableLevelSharingProperties. */ interface WithTableLevelSharingProperties { /** * Specifies the tableLevelSharingProperties property: Table level sharing specifications. * * @param tableLevelSharingProperties Table level sharing specifications. * @return the next definition stage. */ Update withTableLevelSharingProperties(TableLevelSharingProperties tableLevelSharingProperties); } } /** * Refreshes the resource to sync with Azure. * * @return the refreshed resource. */ AttachedDatabaseConfiguration refresh(); /** * Refreshes the resource to sync with Azure. * * @param context The context to associate with this operation. * @return the refreshed resource. */ AttachedDatabaseConfiguration refresh(Context context); }
mit
MobClub/ShareSDK-for-Android
SampleFresh/app/src/main/java/cn/sharesdk/demo/ui/AuthorizationFragment.java
5204
package cn.sharesdk.demo.ui; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.OrientationHelper; import androidx.recyclerview.widget.RecyclerView; import cn.sharesdk.demo.R; import cn.sharesdk.demo.adapter.AuthorizationAdapter; import cn.sharesdk.demo.entity.PlatformEntity; import cn.sharesdk.demo.entity.PlatformMananger; import cn.sharesdk.demo.entity.ResourcesManager; import cn.sharesdk.demo.entity.ShareInEntityManager; import cn.sharesdk.demo.platform.PlatformAuthorizeUserInfoManager; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; import static cn.sharesdk.demo.utils.CommomDialog.dialog; /** * Created by yjin on 2017/5/9. */ public class AuthorizationFragment extends BaseFragment implements AuthorizationAdapter.AuthorizationOnItemClickListener, PlatformActionListener { private View view; private RecyclerView recyclerView; private AuthorizationAdapter adapter; private List<PlatformEntity> lists; private Platform plat; private int curentPostion = 0; TextView textView = null; private PlatformAuthorizeUserInfoManager platAuth; public void initView(View view) { recyclerView = (RecyclerView) view.findViewById(R.id.mAuthorization); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); linearLayoutManager.setOrientation(RecyclerView.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); adapter = new AuthorizationAdapter(getContext(), lists); recyclerView.setAdapter(adapter); adapter.setAuthorizationOnItemClickListener(this); recyclerView.setItemAnimator(new DefaultItemAnimator()); } public void initData() { if (lists == null) { lists = new ArrayList<>(); } lists.add(ShareInEntityManager.createNormalInLand(getContext())); lists.addAll(PlatformMananger.getInstance(getContext()).getChinaListNormal()); lists.add(ShareInEntityManager.createNormalInternational(getContext())); lists.addAll(PlatformMananger.getInstance(getContext()).getNormalList()); lists.add(ShareInEntityManager.createNormalSystem(getContext())); lists.addAll(PlatformMananger.getInstance(getContext()).getSystemListNormal()); } @Override public int getLayoutId() { return R.layout.authorization_fragment; } @Override public void OnItemClickListener(View view, int position) { PlatformEntity entity = lists.get(position); curentPostion = position; if (view instanceof TextView) { textView = (TextView) view; } if (entity != null) { plat = entity.getmPlatform(); } if (plat.getName().equals("Dingding")) { String tempCode = lists.get(position).getmPlatform().getDb().get("tmp_auth_code"); if (tempCode != null && tempCode.length() > 0) { plat.removeAccount(true); textView.setText(getActivity().getString(R.string.authorization_txt)); return; } } if (plat.getName().equals("Snapchat")) { int lengthInt = lists.get(position).getmPlatform().getDb().exportData().length(); if (lengthInt > 2) { plat.removeAccount(true); textView.setText(getActivity().getString(R.string.authorization_txt)); return; } } if (plat.isAuthValid()) { plat.removeAccount(true); textView.setText(getActivity().getString(R.string.authorization_txt)); return; } //这里开启一下SSO,防止OneKeyShare分享时调用了oks.disableSSOWhenAuthorize();把SSO关闭了 //plat.SSOSetting(false); //plat.setPlatformActionListener(this); if (platAuth == null) { platAuth = new PlatformAuthorizeUserInfoManager(getActivity()); } platAuth.doAuthorize(plat, getActivity()); } @Override public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) { if (textView != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { textView.setText(getActivity().getString(R.string.authorization_txt_delete)); } }); } String msg = ResourcesManager.actionToString(i); String text = plat.getName() + " completed at " + msg; if (getActivity() != null) { dialog(getActivity(), text); } else { Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show(); } adapter.notifyItemChanged(curentPostion); adapter.notifyDataSetChanged(); } @Override public void onError(Platform platform, int i, Throwable throwable) { String msg = ResourcesManager.actionToString(i); String text = plat.getName() + " caught error at " + msg; Log.e("qqq", "onError text===> "); if (getActivity() != null) { dialog(getActivity(), text); } else { Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show(); } } @Override public void onCancel(Platform platform, int i) { String msg = ResourcesManager.actionToString(i); String text = plat.getName() + " canceled at " + msg; if (getActivity() != null) { dialog(getActivity(), text); } else { Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show(); } } }
mit
sammy8806/adminbot
src/de/steven_tappert/adminbot/components/xmpp/ChatCommands/status.java
1310
package de.steven_tappert.adminbot.components.xmpp.ChatCommands; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.chat2.Chat; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Presence; public class status extends XmppChatCmd { protected String defaultStatus = "Chat Helper V2"; public status() { setCommandName("status"); setCommandDescription("Set the Status"); setCommandSyntax("!status [Status]"); setCommandAuthLevel(4); } @Override public void runCommand(XMPPConnection conn, Chat chat, Message message) { String parameters = message.getBody().replaceFirst("^!"+commandName, ""); String s = parameters.length() > 1 ? parameters.substring(1) : defaultStatus; Presence status = new Presence(Presence.Type.available); status.setMode(Presence.Mode.chat); status.setStatus("<body><gameStatus>outOfGame</gameStatus><level>42</level><wins>1337</wins><statusMsg>" + s + "</statusMsg><profileIcon>28</profileIcon></body>"); try { conn.sendStanza(status); } catch (InterruptedException | SmackException.NotConnectedException e) { e.printStackTrace(); } } }
mit
SquidDev-CC/CCTweaks-Runtimes
src/main/java/org/squiddev/cctweaks/runtimes/Config.java
1097
package org.squiddev.cctweaks.runtimes; import net.minecraftforge.common.config.Configuration; import org.squiddev.configgen.DefaultBoolean; import org.squiddev.configgen.DefaultInt; import org.squiddev.configgen.Range; import org.squiddev.luaj.luajc.CompileOptions; @org.squiddev.configgen.Config(languagePrefix = "gui.config.cctweaks-runtimes.", propertyPrefix = "cctweaks-runtimes") public class Config { public static Configuration configuration; /** * Compile Lua bytecode to Java bytecode. * This speeds up code execution. Use the "cobalt.luajc" or "luaj.luajc" runtimes to enable this. */ public static class LuaJC { /** * Verify sources on generation. * This will slow down compilation. * If you have errors, please turn this and debug on and * send it with the bug report. */ @DefaultBoolean(false) public static boolean verify; /** * Number of calls required before compiling: * 1 compiles when first called, * 0 or less compiles when loaded */ @DefaultInt(CompileOptions.THRESHOLD) @Range(min = 0) public static int threshold; } }
mit
ControlSystemStudio/diirt
pvmanager/datasource-integration/src/main/java/org/diirt/datasource/integration/PVReaderValueCondition.java
807
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.integration; import org.diirt.datasource.PVReader; import org.diirt.datasource.PVReaderEvent; /** * * @author carcassi */ public class PVReaderValueCondition extends PVReaderCondition<Object> { private final VTypeMatchMask mask; private final Object expectedValue; public PVReaderValueCondition(VTypeMatchMask mask, Object value) { this.mask = mask; this.expectedValue = value; } @Override public boolean accept(PVReader<Object> reader, PVReaderEvent<Object> event) { Object actualValue = reader.getValue(); return mask.match(expectedValue, actualValue) == null; } }
mit
stickfigure/postguice
postguice/src/main/java/com/voodoodyne/postguice/SimpleFullTextSearchFunction.java
1289
package com.voodoodyne.postguice; import com.google.common.base.Preconditions; import org.hibernate.QueryException; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.engine.spi.Mapping; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.type.BooleanType; import org.hibernate.type.Type; import java.util.List; /** * Expects two arguments - the name of the field, and the search query. * Always uses 'simple' config. */ public class SimpleFullTextSearchFunction implements SQLFunction { @Override public boolean hasArguments() { return true; } @Override public boolean hasParenthesesIfNoArguments() { return false; } @Override public Type getReturnType(final Type firstArgumentType, final Mapping mapping) throws QueryException { return new BooleanType(); } @Override public String render(final Type firstArgumentType, final List arguments, final SessionFactoryImplementor factory) throws QueryException { Preconditions.checkState(arguments.size() == 2, "The function must be passed 2 arguments: field, query"); final String field = (String)arguments.get(0); final String query = (String)arguments.get(1); return String.format("to_tsvector('simple', %s) @@ to_tsquery('simple', %s)", field, query); } }
mit
LGoodDatePicker/LGoodDatePicker
Project/src/test/java/com/github/lgooddatepicker/components/TestTimePicker.java
14160
/* * The MIT License * * * 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.lgooddatepicker.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.github.lgooddatepicker.TestHelpers; import com.github.lgooddatepicker.components.TimePickerSettings.TimeArea; import com.github.lgooddatepicker.optionalusertools.TimeChangeListener; import com.github.lgooddatepicker.zinternaltools.TimeChangeEvent; import java.awt.Color; import java.time.Clock; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.Locale; import org.junit.Test; /** Tests for the TimePicker component features */ public class TestTimePicker { @Test(expected = Test.None.class /* no exception expected */) public void TestCustomClockTimeSettings() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { TimePickerSettings settings = new TimePickerSettings(); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); settings = new TimePickerSettings(Locale.ENGLISH); assertTrue("Default clock must be available", settings.getClock() != null); assertTrue( "Default clock must be in system default time zone", settings.getClock().getZone().equals(ZoneId.systemDefault())); Clock myClock = Clock.systemUTC(); settings.setClock(myClock); assertTrue("Set clock must be returned", settings.getClock() == myClock); LocalTime initialTime = (LocalTime) TestHelpers.readPrivateField(TimePickerSettings.class, settings, "initialTime"); assertTrue( "intialtime is null as long as setInitialTimeToNow() has not been called", initialTime == null); settings.setClock(TestHelpers.getClockFixedToInstant(2000, Month.JANUARY, 1, 15, 55)); settings.setInitialTimeToNow(); initialTime = (LocalTime) TestHelpers.readPrivateField(TimePickerSettings.class, settings, "initialTime"); assertTrue( "intialtime is not null after call to as long as setInitialTimeToNow()", initialTime != null); assertTrue("intialtime must be 15:55 / 3:55pm", initialTime.equals(LocalTime.of(15, 55))); } @Test(expected = Test.None.class /* no exception expected */) public void TestCustomClockTimePicker() { TimePicker picker = new TimePicker(); assertTrue(picker.getTime() == null); TimePickerSettings settings = new TimePickerSettings(Locale.ENGLISH); settings.setClock(TestHelpers.getClockFixedToInstant(1995, Month.OCTOBER, 31, 14, 33)); picker = new TimePicker(settings); picker.setTimeToNow(); assertTrue( "Picker must have set a time of 14:33 / 2:33pm", picker.getTime().equals(LocalTime.of(14, 33))); } /** Basic test of the time picker functions */ @Test(expected = Test.None.class /* no exception expected */) public void verifyTimePickerBasics() { TimePicker picker = new TimePicker(); // Test the range of Local times picker.setTime(LocalTime.MIN); assertEquals("minium local time could not be used", LocalTime.MIN, picker.getTime()); picker.setTime(LocalTime.NOON); assertEquals("noon local time could not be used", LocalTime.NOON, picker.getTime()); picker.setTime(LocalTime.MAX); assertEquals( "maximum local time could not be used", LocalTime.MAX.truncatedTo(ChronoUnit.MINUTES), picker.getTime()); // test clearing the component by setting the time to null picker.setTime(null); assertNull("null time could not be used", picker.getTime()); // reset the the picker back to noon picker.setTime(LocalTime.NOON); // ensure it can be set again after set to null assertEquals("noon local time could not be used", LocalTime.NOON, picker.getTime()); // clear it again picker.clear(); // ensure that clear also sets time to null assertNull("Clear did not make the time null", picker.getTime()); } /** Tests that the various parts of the TimePicker can be enabled and disabled as expected */ @Test(expected = Test.None.class /* no exception expected */) public void verifyTimePickerEnabled() { TimePicker picker = new TimePicker(); picker.setEnableArrowKeys(true); assertTrue("Arrow keys not enabled", picker.getEnableArrowKeys()); picker.setEnableArrowKeys(false); assertFalse("Arrow keys not disabled", picker.getEnableArrowKeys()); assertNotNull("Picker settings were null", picker.getSettings()); picker.setEnabled(false); assertFalse("Picker was not disabled", picker.isEnabled()); assertFalse( "Menu component was not disabled", picker.getComponentToggleTimeMenuButton().isEnabled()); assertFalse( "TextField component was not disabled", picker.getComponentTimeTextField().isEnabled()); picker.setEnabled(true); assertTrue("Picker was not disabled", picker.isEnabled()); assertTrue( "Menu component was not enabled", picker.getComponentToggleTimeMenuButton().isEnabled()); assertTrue( "TextField component was not enabled", picker.getComponentTimeTextField().isEnabled()); } /** * Test to ensure that the parsing and strings work as expected. Here Locale.ENGLISH is specified * to ensure the test is consistent when run on systems in other Locales. */ @Test(expected = Test.None.class /* no exception expected */) public void verifyTimePickerParsingAndStrings() { TimePickerSettings settings = new TimePickerSettings(Locale.ENGLISH); settings.useLowercaseForDisplayTime = true; TimePicker picker = new TimePicker(settings); // valid text picker.setText("12:22"); assertTrue("Expected time to be valid", picker.isTextValid("12:22")); assertTrue("Expected field to be valid", picker.isTextFieldValid()); assertEquals("Did not retain user text", "12:22", picker.getText()); assertEquals( "Entered time not translated to local time", LocalTime.of(12, 22), picker.getTime()); assertEquals( "Expected time string for valid time", "12:22", picker.getTimeStringOrSuppliedString("supply")); // invalid text picker.setText("44:17"); assertFalse("Expected time to be invalid", picker.isTextValid("44:17")); assertFalse("Expected timefield to be invalid", picker.isTextFieldValid()); assertEquals("Did not retain user text", "44:17", picker.getText()); // because time is invalid the old local time should still be present assertEquals( "Invalid time was translated to local time", LocalTime.of(12, 22), picker.getTime()); // null time picker.setTime(null); assertEquals("Expected empty string for null time", "", picker.getTimeStringOrEmptyString()); assertEquals( "Expected supplied string for null time", "supply", picker.getTimeStringOrSuppliedString("supply")); // null text assertFalse("null text was considered valid", picker.isTextValid(null)); picker.setText(null); assertEquals("null text did not become blank text", "", picker.getText()); // empty text assertTrue("spaces only text was considered valid", picker.isTextValid(" ")); picker.setText(" "); assertEquals("spaces text was not returned", " ", picker.getText()); // toString picker.setTime(LocalTime.of(8, 32)); assertEquals( "toString should match toTime", picker.getTimeStringOrEmptyString(), picker.toString()); picker.setTime(LocalTime.of(8, 32, 12)); assertEquals( "toString should match toTime", picker.getTimeStringOrEmptyString(), picker.toString()); assertTrue("Expect noon to be an allowed time", picker.isTimeAllowed(LocalTime.NOON)); } /** Tests to ensure that the TimeChangeListener works as expected. */ @Test(expected = Test.None.class /* no exception expected */) public void verifyTimeChangeListeners() { TimePicker picker = new TimePicker(); TestableTimeChangeListener listener = new TestableTimeChangeListener(); picker.addTimeChangeListener(listener); assertNull("listener event not null at start", listener.getLastEvent()); picker.setTime(LocalTime.MIN); assertEquals( "Listener did not receive new time", LocalTime.MIN, listener.getLastEvent().getNewTime()); assertNull("Listener did not remember old time", listener.getLastEvent().getOldTime()); assertEquals( "Event did not originate from time picker", picker, listener.getLastEvent().getSource()); TimeChangeEvent lastEvent = listener.getLastEvent(); picker.setTime(LocalTime.MIN); assertTrue("Event updated when time did not change", lastEvent == listener.getLastEvent()); picker.setTime(LocalTime.NOON); assertEquals( "Listener did not remember old time", LocalTime.MIN, listener.getLastEvent().getOldTime()); assertEquals( "Listener did not receive new time", LocalTime.NOON, listener.getLastEvent().getNewTime()); picker.setTime(null); assertNull("Listener did not receive null time", listener.getLastEvent().getNewTime()); assertTrue( "Listener was not in the list of listeners", picker.getTimeChangeListeners().contains(listener)); picker.removeTimeChangeListener(listener); picker.setTime(LocalTime.NOON); assertNull( "Listener received an update after being uninstalled", listener.getLastEvent().getNewTime()); } /** Test to ensure that the custom colors for the disabled time picker work as excepcted */ @Test(expected = Test.None.class /* no exception expected */) public void verifyCustomDisabledColors() { final Color defaultDisabledText = new TimePickerSettings().getColor(TimeArea.TimePickerTextDisabled); final Color defaultDisabledBackground = new TimePickerSettings().getColor(TimeArea.TextFieldBackgroundDisabled); TimePickerSettings settings = new TimePickerSettings(Locale.ENGLISH); settings.setColor(TimeArea.TimePickerTextDisabled, Color.yellow); settings.setColor(TimeArea.TextFieldBackgroundDisabled, Color.blue); TimePicker picker = new TimePicker(settings); validateTimePickerDisabledColor(picker, Color.yellow, Color.blue); picker.setEnabled(false); validateTimePickerDisabledColor(picker, Color.yellow, Color.blue); picker = new TimePicker(new TimePickerSettings(Locale.ENGLISH)); validateTimePickerDisabledColor(picker, defaultDisabledText, defaultDisabledBackground); picker.setEnabled(false); validateTimePickerDisabledColor(picker, defaultDisabledText, defaultDisabledBackground); picker.getSettings().setColor(TimeArea.TimePickerTextDisabled, Color.yellow); validateTimePickerDisabledColor(picker, Color.yellow, defaultDisabledBackground); picker.getSettings().setColor(TimeArea.TextFieldBackgroundDisabled, Color.blue); validateTimePickerDisabledColor(picker, Color.yellow, Color.blue); picker.setEnabled(true); validateTimePickerDisabledColor(picker, Color.yellow, Color.blue); } void validateTimePickerDisabledColor( TimePicker picker, Color disabledTextColor, Color disabledBackground) { final Color validText = new TimePickerSettings().getColor(TimeArea.TimePickerTextValidTime); final Color enabledBackground = new TimePickerSettings().getColor(TimeArea.TextFieldBackgroundValidTime); assertTrue(picker.getComponentTimeTextField().getForeground().equals(validText)); assertFalse(picker.getComponentTimeTextField().getForeground().equals(disabledTextColor)); assertTrue(picker.getComponentTimeTextField().getDisabledTextColor().equals(disabledTextColor)); assertFalse(picker.getComponentTimeTextField().getDisabledTextColor().equals(validText)); if (picker.isEnabled()) { assertTrue(picker.getComponentTimeTextField().getBackground().equals(enabledBackground)); assertFalse(picker.getComponentTimeTextField().getBackground().equals(disabledBackground)); } else { assertTrue(picker.getComponentTimeTextField().getBackground().equals(disabledBackground)); assertFalse(picker.getComponentTimeTextField().getBackground().equals(enabledBackground)); } } // helper class private class TestableTimeChangeListener implements TimeChangeListener { TimeChangeEvent lastEvent; @Override public void timeChanged(TimeChangeEvent event) { lastEvent = event; } TimeChangeEvent getLastEvent() { return lastEvent; } } }
mit
liebig/lighthouse
src/main/java/de/liebig/lighthouse/accounts/AccountController.java
1831
package de.liebig.lighthouse.accounts; import java.util.Optional; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.myjeeva.digitalocean.DigitalOcean; import com.myjeeva.digitalocean.exception.DigitalOceanException; import com.myjeeva.digitalocean.exception.RequestUnsuccessfulException; import de.liebig.lighthouse.api.ApiManager; import de.liebig.lighthouse.exceptions.ApiException; @RestController @RequestMapping(value = "/account", name = "AccountController") public class AccountController { @Autowired AccountService accountService; @Autowired ApiManager apiManager; @RequestMapping(name = "get", method = RequestMethod.GET) public com.myjeeva.digitalocean.pojo.Account getAccount() throws ApiException { DigitalOcean digitalOcean = apiManager.getDigitalOcean(); try { return digitalOcean.getAccountInfo(); } catch (DigitalOceanException | RequestUnsuccessfulException e) { throw new ApiException("Could not load account", e); } } @RequestMapping(name = "create", method = RequestMethod.POST) public Account createAccount(@RequestBody AccountDto accountDto) { if(apiManager.isDigitalOceanApiKeyValid(accountDto.getApiKey())) { Optional<Account> createdAccount = accountService.createAccount(accountDto.getApiKey()); if(createdAccount.isPresent()) { apiManager.setDigitalOceanApiKey(accountDto.getApiKey()); return createdAccount.get(); } } return null; } }
mit
TheHolyWaffle/TeamSpeak-3-Java-API
src/main/java/com/github/theholywaffle/teamspeak3/commands/ChannelCommands.java
3767
package com.github.theholywaffle.teamspeak3.commands; /* * #%L * TeamSpeak 3 Java API * %% * Copyright (C) 2017 Bert De Geyter, Roger Baumgartner * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.github.theholywaffle.teamspeak3.api.ChannelProperty; import com.github.theholywaffle.teamspeak3.commands.parameter.KeyValueParam; import com.github.theholywaffle.teamspeak3.commands.parameter.OptionParam; import java.util.Map; public final class ChannelCommands { private ChannelCommands() { throw new Error("No instances"); } public static Command channelCreate(String name, Map<ChannelProperty, String> options) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Channel name must be a non-empty string"); } CommandBuilder builder = new CommandBuilder("channelcreate", 2); builder.add(new KeyValueParam("channel_name", name)); builder.addProperties(options); return builder.build(); } public static Command channelDelete(int channelId, boolean force) { CommandBuilder builder = new CommandBuilder("channeldelete", 2); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("force", force)); return builder.build(); } public static Command channelEdit(int channelId, Map<ChannelProperty, String> options) { CommandBuilder builder = new CommandBuilder("channeledit", 2); builder.add(new KeyValueParam("cid", channelId)); builder.addProperties(options); return builder.build(); } public static Command channelFind(String pattern) { if (pattern == null || pattern.isEmpty()) { throw new IllegalArgumentException("Channel name pattern must be a non-empty string"); } return new CommandBuilder("channelfind", 1).add(new KeyValueParam("pattern", pattern)).build(); } public static Command channelInfo(int channelId) { return new CommandBuilder("channelinfo", 1).add(new KeyValueParam("cid", channelId)).build(); } public static Command channelList() { CommandBuilder builder = new CommandBuilder("channellist", 7); builder.add(new OptionParam("topic")); builder.add(new OptionParam("flags")); builder.add(new OptionParam("voice")); builder.add(new OptionParam("limits")); builder.add(new OptionParam("icon")); builder.add(new OptionParam("secondsempty")); builder.add(new OptionParam("banners")); return builder.build(); } public static Command channelMove(int channelId, int channelParentId, int order) { CommandBuilder builder = new CommandBuilder("channelmove", 3); builder.add(new KeyValueParam("cid", channelId)); builder.add(new KeyValueParam("cpid", channelParentId)); builder.add(new KeyValueParam("order", order < 0 ? 0 : order)); return builder.build(); } }
mit
marcokrikke/icalendar-aggregator
src/main/java/nl/marcokrikke/icalendaraggregator/Application.java
324
package nl.marcokrikke.icalendaraggregator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
mit
hpe-idol/java-content-parameter-api
src/test/java/com/hp/autonomy/aci/content/fieldtext/NOTSTRINGTest.java
7712
/* * Copyright 2009-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.aci.content.fieldtext; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import static com.hp.autonomy.aci.content.fieldtext.NOTSTRING.NOTSTRING; import static org.junit.Assert.assertEquals; /** * Tests for the <tt>NOTSTRING</tt> class. * * @author darrelln * @version $Revision$ $Date$ */ public class NOTSTRINGTest { @Test public void testStringStrings() { final NOTSTRING match = new NOTSTRING("ns:field", "20%", "10%", "1,2"); assertEquals("String, String... constructor", "NOTSTRING{20%25,10%25,1%2C2}:ns%3Afield", match.toString()); assertEquals("String, String... - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String, String... - getFields", Collections.singletonList("ns:field"), match.getFields()); } @Test public void testStringArray() { final NOTSTRING match = new NOTSTRING("ns:field", new String[]{"20%", "10%", "1,2"}); assertEquals("String, String[] constructor", "NOTSTRING{20%25,10%25,1%2C2}:ns%3Afield", match.toString()); assertEquals("String, String[] - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String, String[] - getFields", Collections.singletonList("ns:field"), match.getFields()); } @Test public void testStringIterable() { final NOTSTRING match = new NOTSTRING("ns:field", Arrays.asList("20%", "10%", "1,2")); assertEquals("String, Iterable<String> constructor", "NOTSTRING{20%25,10%25,1%2C2}:ns%3Afield", match.toString()); assertEquals("String, Iterable<String> - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String, Iterable<String> - getFields", Collections.singletonList("ns:field"), match.getFields()); } @Test public void testArrayStrings() { final NOTSTRING match = new NOTSTRING(new String[]{"FIELD1", "FIELD2", "ns:field"}, "20%", "10%", "1,2"); assertEquals("String[], String... constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("String[], String... - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String[], String... - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testArrayArray() { final NOTSTRING match = new NOTSTRING(new String[]{"FIELD1", "FIELD2", "ns:field"}, new String[]{"20%", "10%", "1,2"}); assertEquals("String[], String[] constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("String[], String[] - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String[], String[] - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testArrayIterable() { final NOTSTRING match = new NOTSTRING(new String[]{"FIELD1", "FIELD2", "ns:field"}, Arrays.asList("20%", "10%", "1,2")); assertEquals("String[], Iterable<String> constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("String[], Iterable<String> - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("String[], Iterable<String> - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testIterableStrings() { final NOTSTRING match = new NOTSTRING(Arrays.asList("FIELD1", "FIELD2", "ns:field"), "20%", "10%", "1,2"); assertEquals("Iterable<String>, String... constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("Iterable<String>, String... - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("Iterable<String>, String... - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testIterableArray() { final NOTSTRING match = new NOTSTRING(Arrays.asList("FIELD1", "FIELD2", "ns:field"), new String[]{"20%", "10%", "1,2"}); assertEquals("Iterable<String>, String[] constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("Iterable<String>, String[] - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("Iterable<String>, String[] - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testIterableIterable() { final NOTSTRING match = new NOTSTRING(Arrays.asList("FIELD1", "FIELD2", "ns:field"), Arrays.asList("20%", "10%", "1,2")); assertEquals("Iterable<String>, Iterable<String> constructor", "NOTSTRING{20%25,10%25,1%2C2}:FIELD1:FIELD2:ns%3Afield", match.toString()); assertEquals("Iterable<String>, Iterable<String> - getValues", Arrays.asList("20%", "10%", "1,2"), match.getValues()); assertEquals("Iterable<String>, Iterable<String> - getFields", Arrays.asList("FIELD1", "FIELD2", "ns:field"), match.getFields()); } @Test public void testFactoryMethods() { assertEquals("NOTSTRING{val1,val2}:field", NOTSTRING.NOTSTRING("field", "val1", "val2").toString()); assertEquals("NOTSTRING{val1,val2}:field", NOTSTRING.NOTSTRING("field", new String[]{"val1", "val2"}).toString()); assertEquals("NOTSTRING{val1,val2}:field", NOTSTRING.NOTSTRING("field", Arrays.asList("val1", "val2")).toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(new String[]{"field", "title"}, "val1", "val2").toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(new String[]{"field", "title"}, new String[]{"val1", "val2"}).toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(new String[]{"field", "title"}, Arrays.asList("val1", "val2")).toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(Arrays.asList("field", "title"), "val1", "val2").toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(Arrays.asList("field", "title"), new String[]{"val1", "val2"}).toString()); assertEquals("NOTSTRING{val1,val2}:field:title", NOTSTRING.NOTSTRING(Arrays.asList("field", "title"), Arrays.asList("val1", "val2")).toString()); } @Test(expected = IllegalArgumentException.class) public void testNoValues1() { new NOTSTRING("FIELD", new String[0]); } @Test(expected = IllegalArgumentException.class) public void testNoValues2() { new NOTSTRING("FIELD", Collections.<String>emptyList()); } @Test(expected = IllegalArgumentException.class) public void testNoValues3() { new NOTSTRING(new String[]{"FIELD"}, new String[0]); } @Test(expected = IllegalArgumentException.class) public void testNoValues4() { new NOTSTRING(new String[]{"FIELD"}, Collections.<String>emptyList()); } @Test(expected = IllegalArgumentException.class) public void testNoValues5() { new NOTSTRING(Collections.singletonList("FIELD"), new String[0]); } @Test(expected = IllegalArgumentException.class) public void testNoValues6() { new NOTSTRING(Collections.singletonList("FIELD"), Collections.<String>emptyList()); } }
mit
tsdl2013/SimpleFlatMapper
sfm/src/main/java/org/sfm/map/error/RethrowMapperBuilderErrorHandler.java
702
package org.sfm.map.error; import org.sfm.map.FieldKey; import org.sfm.map.MapperBuilderErrorHandler; import org.sfm.map.MapperBuildingException; import java.lang.reflect.Type; public final class RethrowMapperBuilderErrorHandler implements MapperBuilderErrorHandler { @Override public void getterNotFound(final String msg) { throw new MapperBuildingException(msg); } @Override public void propertyNotFound(final Type target, final String property) { throw new MapperBuildingException("Injection point for " + property + " on " + target + " not found"); } @Override public void customFieldError(FieldKey<?> key, String message) { throw new MapperBuildingException(message); } }
mit
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/model/response/list/InvoiceStatementBatchListWrapper.java
441
package com.bullhornsdk.data.model.response.list; import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatementBatch; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"data", "count", "start"}) public class InvoiceStatementBatchListWrapper extends StandardListWrapper<InvoiceStatementBatch> { }
mit
rentianhua/tsf_android
houseAd/HouseGo/src/com/dumu/housego/util/GetYHQlistJSONParse.java
1599
package com.dumu.housego.util; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.dumu.housego.entity.YHQ; public class GetYHQlistJSONParse { public static List<YHQ> parseSearch(String json) throws JSONException { JSONArray array = new JSONArray(json); List<YHQ> yhqs = new ArrayList<YHQ>(); for (int i = 0; i < array.length(); i++) { JSONObject j = array.getJSONObject(i); YHQ n = new YHQ(); n.setId(j.getString("id")); n.setBuyname(j.getString("buyname")); n.setBuytel(j.getString("buytel")); n.setCoupon_id(j.getString("coupon_id")); n.setCoupon_name(j.getString("coupon_name")); n.setDifu(j.getString("difu")); n.setHouse_id(j.getString("house_id")); n.setHouse_title(j.getString("house_title")); n.setInputtime(j.getString("inputtime")); n.setOrder_no(j.getString("order_no")); n.setShifu(j.getString("shifu")); n.setTrade_status(j.getString("trade_status")); n.setUserid(j.getString("userid")); n.setPay_status(j.getString("pay_status")); n.setBuyer_email(j.getString("buyer_email")); n.setTrade_no(j.getString("trade_no")); n.setPaytime(j.getString("paytime")); n.setDescription(j.getString("description")); n.setIsused(j.getString("isused")); yhqs.add(n); } return yhqs; } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/Encryption.java
2552
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.compute.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Encryption at rest settings for disk or snapshot. */ @Fluent public final class Encryption { @JsonIgnore private final ClientLogger logger = new ClientLogger(Encryption.class); /* * ResourceId of the disk encryption set to use for enabling encryption at * rest. */ @JsonProperty(value = "diskEncryptionSetId") private String diskEncryptionSetId; /* * The type of key used to encrypt the data of the disk. */ @JsonProperty(value = "type", required = true) private EncryptionType type; /** * Get the diskEncryptionSetId property: ResourceId of the disk encryption set to use for enabling encryption at * rest. * * @return the diskEncryptionSetId value. */ public String diskEncryptionSetId() { return this.diskEncryptionSetId; } /** * Set the diskEncryptionSetId property: ResourceId of the disk encryption set to use for enabling encryption at * rest. * * @param diskEncryptionSetId the diskEncryptionSetId value to set. * @return the Encryption object itself. */ public Encryption withDiskEncryptionSetId(String diskEncryptionSetId) { this.diskEncryptionSetId = diskEncryptionSetId; return this; } /** * Get the type property: The type of key used to encrypt the data of the disk. * * @return the type value. */ public EncryptionType type() { return this.type; } /** * Set the type property: The type of key used to encrypt the data of the disk. * * @param type the type value to set. * @return the Encryption object itself. */ public Encryption withType(EncryptionType type) { this.type = type; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (type() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property type in model Encryption")); } } }
mit
nicolas-amiot/dta-formation
apps/pizzeria-app/pizzeria-console/src/main/java/fr/pizzeria/ihm/option/AfficherPizzaUltime.java
1119
package fr.pizzeria.ihm.option; import java.util.Comparator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import fr.pizzeria.dao.Dao; import fr.pizzeria.exception.DaoException; import fr.pizzeria.modele.Pizza; @Controller public class AfficherPizzaUltime extends OptionMenu { private Dao<Pizza, String> pizzaDao; @Autowired public AfficherPizzaUltime(@Qualifier("pizzaDao") Dao<Pizza, String> pizzaDao) { super("Afficher la pizza la plus cher"); this.pizzaDao = pizzaDao; } @Override public boolean execute() { try { List<Pizza> pizzas = pizzaDao.findAll(); Pizza pizza = pizzas.stream().max(Comparator.comparing(Pizza::getPrix)).get(); System.out.println(pizza); } catch (DaoException e) { Logger logger = Logger.getLogger(this.getClass().getName()); logger.log(Level.SEVERE, e.getMessage(), e); } return false; } }
mit
camilstaps/OO1415
Week16 Ice Cream/src/com/camilstaps/icecream/IceCream.java
1700
/* * The MIT License (MIT) * * Copyright (c) 2015 Camil Staps <info@camilstaps.nl> * * 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.camilstaps.icecream; /** * A general ice cream * @author Camil Staps */ public abstract class IceCream { /** * Set this attribute in the constructor of your subclass */ protected String description = "Unknown ice cream"; /** * The description of the ice cream * @return */ public String getDescription() { return description; } /** * The price of the ice cream in cents * @return */ abstract public int getPrice(); }
mit
jessepav/jedit-macros
macrolib/src/com/illcode/jedit/MarkdownUtils.java
13932
package com.illcode.jedit; import org.gjt.sp.jedit.jEdit; import org.gjt.sp.jedit.Buffer; import org.gjt.sp.jedit.View; import org.gjt.sp.jedit.textarea.JEditTextArea; import org.gjt.sp.jedit.textarea.Selection; import org.apache.commons.lang3.StringUtils; import java.util.regex.Pattern; import java.util.regex.Matcher; @SuppressWarnings("unchecked") public final class MarkdownUtils { // "(?: *(?:[\*\+\-:~]|(?:\d+|#)\.) +|\[\^\S{2})" public static final Pattern LIST_ITEM_PATTERN = Pattern.compile("(?: *(?:[\\*\\+\\-:~]|(?:\\d+|#)\\.) +|\\[\\^\\S{2})"); /** * Tests if a line is the start of some sort of list item, and if so, return the text * up until the end of the start pattern; otherwise return {@code null}. */ private String getListStartText(String s) { Matcher m = LIST_ITEM_PATTERN.matcher(s); if (m.lookingAt()) return m.group(); else return null; } /** * Returns true if a given line is a paragraph delimeter. */ private boolean isParagraphDelimiter(String line) { int n = line.length(); char firstChar = firstNonSpaceChar(line); return n == 0 || // empty line ((firstChar == '<' || line.charAt(0) == ' ') && line.charAt(n-1) == '>') || // HTML tag StringUtils.isWhitespace(line) || // blank line (firstChar == ':' && line.trim().startsWith(":::")) || // Pandoc div (firstChar == '>' && line.trim().equals(">")); // paragraph break in blockquote } /** * Return true if the given line is the start of a paragraph. */ private boolean isParagraphStart(String line) { char c = firstNonSpaceChar(line); if (c == 0xA0 || c == 0x2003 || c == 0x2002) { // formatting indendation return true; } else if (c == '&') { line = line.trim(); return line.startsWith("&nbsp;") || line.startsWith("&emsp;") || line.startsWith("&ensp;"); } else { return false; } } /** * Return true if the given line is the last line of a paragraph. */ private boolean isParagraphEnd(String line) { return line.endsWith("<br>") || line.endsWith("<br />") || line.endsWith("\\"); } /** * Return the first non-space character in a line, or '\0' if the line is empty or has no * non-space characters. */ private char firstNonSpaceChar(String line) { char c = '\0'; int n = line.length(); for (int i = 0; i < n; i++) { char c2 = line.charAt(i); if (c2 != ' ') { c = c2; break; } } return c; } /** * Returns the leading whitespace of a string. */ private String getLeadingWhitespace(String s) { for (int i = 0; i < s.length(); i++) { if (!Character.isWhitespace(s.charAt(i))) return s.substring(0, i); } // If we reach here, the string was all whitespace return s; } /** * Gets the text and line boundary information about the paragraph that holds the caret. The format * of the returned Object array is: * <pre> * Index 0 - paragraph text (String) * Index 1 - starting line of the paragraph (Integer) * Index 2 - ending line of the paragraph (Integer) * </pre> * @return paragraph text and line boundaries */ private Object[] getParagraphText(JEditTextArea textArea) { Object[] oa = new Object[3]; int parStartLine, parEndLine; String parText; int numLines = textArea.getLineCount(); int currentLine = textArea.getCaretLine(); String trimmedLine = textArea.getLineText(currentLine).trim(); // If the current line is all whitespace or an empty blockquote line, there's nothing to be done if (trimmedLine.isEmpty() || trimmedLine.equals(">")) { oa[0] = ""; oa[1] = oa[2] = currentLine; return oa; } if (numLines == 1) { // degenerate case oa[0] = textArea.getBuffer().getText(); oa[1] = oa[2] = 0; return oa; } // First we scan up looking for the paragraph start line for (parStartLine = currentLine; parStartLine >= 0; parStartLine--) { String lineText = textArea.getLineText(parStartLine); if (isParagraphDelimiter(lineText) || (parStartLine != currentLine && isParagraphEnd(lineText))) { if (parStartLine != currentLine) parStartLine++; // the previously-scanned line is the paragraph start break; } else if (getListStartText(lineText) != null || isParagraphStart(lineText)) { break; } } parStartLine = Math.max(parStartLine, 0); // Now scan down looking for the paragraph end line if (isParagraphEnd(textArea.getLineText(currentLine))) { parEndLine = currentLine; } else { for (parEndLine = currentLine + 1; parEndLine < numLines; parEndLine++) { String lineText = textArea.getLineText(parEndLine); if (getListStartText(lineText) != null || isParagraphDelimiter(lineText)) { parEndLine--; // the previously-scanned line is the paragraph end break; } else if (isParagraphEnd(lineText)) { break; } } } parEndLine = Math.min(parEndLine, numLines - 1); int startOffset = textArea.getLineStartOffset(parStartLine); int endOffset = textArea.getLineEndOffset(parEndLine); // getLineEndOffset() always returns an offset 1 past the end of the // line's (non-newline) text, so we subtract 1 below parText = textArea.getText(startOffset, endOffset - startOffset - 1); oa[0] = parText; oa[1] = parStartLine; oa[2] = parEndLine; return oa; } /** * Used by formatParagraph() to reflow text. */ private void reflowText(String parText, StringBuilder sb, int wrapMargin, boolean isBlockquote) { // The fraction by which words are allowed to overflow the margin int OVERFLOW_DIVISOR = jEdit.getIntegerProperty("JP.overflowDivisor", 4); String prefix = getListStartText(parText); if (prefix == null) prefix = getLeadingWhitespace(parText); int indent = prefix.length(); String indentSpace = StringUtils.repeat(' ', indent); String text = parText.substring(indent).trim(); String[] words = StringUtils.split(text); if (isBlockquote) { int pwsi = getLeadingWhitespace(prefix).length(); // prefix white-space indent prefix = StringUtils.repeat(' ', pwsi) + "> " + prefix.substring(pwsi); indentSpace = StringUtils.repeat(' ', pwsi) + "> " + StringUtils.repeat(' ', indent - pwsi); indent += 2; } int n = words.length; int col = 0; // column at which we're inserting words sb.append(prefix).append(words[0]); col = indent + words[0].length(); for (int i = 1; i < n; i++) { String word = words[i]; int wordlen = word.length(); int remaining = wrapMargin - col + 1; int overflow = wordlen + 1 - remaining; if (overflow < wordlen/OVERFLOW_DIVISOR) { sb.append(' ').append(word); col += 1 + wordlen; } else { // go to a new line sb.append('\n').append(indentSpace).append(word); col = indent + wordlen; } } } /** Returns true if the first non-whitespace character in {@code text} is a {@code '>'} */ private boolean checkForBlockquote(String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (!Character.isWhitespace(c)) return c == '>'; } return false; } // (?<=(?:^|\n) *)> ? public static final Pattern BLOCKQUOTE_PATTERN = Pattern.compile("(?<=(?:^|\\n) {0,8})> ?"); /** * Reflow selected text (if a selection is active) or the current paragraph * to fit within the wrapMargin. * * If wrapMargin == 0, the margin will be taken from the JP.wrapLen buffer property, or, if that property is not defined, the buffer's maxLineLen property. * If wrapMargin == -1, the margin will be taken from the length of the first line of * the text to wrap. */ public void formatParagraph(View view, JEditTextArea textArea, Buffer buffer, int wrapMargin) { int parStartLine = -1, parEndLine = -1; String parText; boolean usingSelection; boolean trailingNewline; String selectedText = textArea.getSelectedText(); usingSelection = selectedText != null; int startOffset, endOffset, nonWhitespaceCount, extraSpaceCount; // used for caret positioning if (usingSelection) { parText = selectedText; startOffset = endOffset = nonWhitespaceCount = extraSpaceCount = -1; } else { Object[] parInfo = getParagraphText(textArea); parText = (String) parInfo[0]; parStartLine = (Integer) parInfo[1]; parEndLine = (Integer) parInfo[2]; startOffset = textArea.getLineStartOffset(parStartLine); endOffset = textArea.getLineEndOffset(parEndLine) - 1; // see comment in getParagraphText() // We are going to count the number of non-whitespace characters between the start of the // paragraph and the caret, to be used later in repositioning the caret. int caretPos = textArea.getCaretPosition(); int caretOffset = caretPos - startOffset; nonWhitespaceCount = 0; for (int i = 0; i < caretOffset; i++) { if (!Character.isWhitespace(parText.charAt(i))) nonWhitespaceCount++; } // If the caret is in the middle of the paragraph and is immediately after a space, // place it after the space in the wrapped paragraph too. extraSpaceCount = (caretPos != startOffset && caretPos != endOffset && parText.charAt(caretOffset-1) == ' ') ? 1 : 0; } if (StringUtils.isWhitespace(parText)) return; trailingNewline = parText.endsWith("\n"); int tabSize = buffer.getIntegerProperty("tabSize", 8); parText = parText.replace("\t", StringUtils.repeat(' ', tabSize)); StringBuilder sb = new StringBuilder(parText.length() + 100); if (wrapMargin == 0) { wrapMargin = buffer.getIntegerProperty("JP.wrapLen", buffer.getIntegerProperty("maxLineLen", 72)); } else if (wrapMargin == -1) { wrapMargin = parText.indexOf("\n"); if (wrapMargin == -1) wrapMargin = buffer.getIntegerProperty("JP.wrapLen", buffer.getIntegerProperty("maxLineLen", 72)); } boolean isBlockquote = checkForBlockquote(parText); if (isBlockquote) { parText = BLOCKQUOTE_PATTERN.matcher(parText).replaceAll(""); } reflowText(parText, sb, wrapMargin, isBlockquote); // Save our reformatted text back to parText if (trailingNewline) sb.append('\n'); parText = sb.toString(); // Finally, modify the text of the buffer if (usingSelection) { textArea.setSelectedText(parText); } else { textArea.setSelection(new Selection.Range(startOffset, endOffset)); textArea.setSelectedText(parText); // Reposition the caret based on the earlier tally of non-whitespace characters. int i = 0; while (nonWhitespaceCount > 0) { if (!Character.isWhitespace(parText.charAt(i++))) nonWhitespaceCount--; } textArea.moveCaretPosition(startOffset + Math.min(i + extraSpaceCount, parText.length())); } } public void toggleBlockquote(View view, JEditTextArea textArea, Buffer buffer) { int caretLine = textArea.getCaretLine(); int lineOffset = textArea.getLineStartOffset(caretLine); int caretCol = textArea.getCaretPosition() - lineOffset; String text = textArea.getSelectedText(); if (text == null) { textArea.selectParagraph(); text = textArea.getSelectedText(); } if (text == null || text.isEmpty()) { textArea.setSelectedText("> "); return; } String[] lines = StringUtils.split(text, "\r\n"); boolean addBlock = !checkForBlockquote(lines[0]); int tabSize = buffer.getIntegerProperty("tabSize", 8); text = text.replace("\t", StringUtils.repeat(' ', tabSize)); if (addBlock) { // Let's get minimum indentation int minIndent = text.length(); for (String line : lines) minIndent = Math.min(minIndent, getLeadingWhitespace(line).length()); for (int i = 0; i < lines.length; i++) lines[i] = lines[i].substring(0, minIndent) + "> " + lines[i].substring(minIndent); textArea.setSelectedText(StringUtils.join(lines, '\n')); } else { textArea.setSelectedText(BLOCKQUOTE_PATTERN.matcher(text).replaceAll("")); } textArea.moveCaretPosition(textArea.getLineStartOffset(caretLine) + caretCol + (addBlock ? 2 : -2)); } }
mit
etki/grac
src/main/java/me/etki/grac/io/SynchronousSerializationManager.java
1033
package me.etki.grac.io; import com.google.common.net.MediaType; import me.etki.grac.exception.SerializationException; import me.etki.grac.utility.TypeSpec; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; /** * @author Etki {@literal <etki@etki.name>} * @version %I%, %G% * @since 0.1.0 */ public interface SynchronousSerializationManager { <T> SerializationResult serialize(T object, MediaType mimeType) throws IOException, SerializationException; <T> DeserializationResult<T> deserialize( InputStream stream, MediaType mimeType, TypeSpec expectedType, List<TypeSpec> fallbackTypes) throws IOException, SerializationException; default <T> DeserializationResult<T> deserialize(InputStream stream, MediaType mimeType, TypeSpec expectedType) throws IOException, SerializationException { return deserialize(stream, mimeType, expectedType, Collections.emptyList()); } }
mit
popitsch/varan-gie
src/org/broad/igv/track/RenderContext.java
5732
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.track; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.sam.InsertionMarker; import org.broad.igv.ui.panel.ReferenceFrame; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.broad.igv.prefs.Constants.ENABLE_ANTIALISING; /** * @author jrobinso */ public class RenderContext { private Graphics2D graphics; private Map<Object, Graphics2D> graphicCache; private ReferenceFrame referenceFrame; private JComponent panel; private Rectangle visibleRect; private boolean merged = false; public transient int translateX; private List<InsertionMarker> insertionMarkers; public boolean multiframe = false; public RenderContext(JComponent panel, Graphics2D graphics, ReferenceFrame referenceFrame, Rectangle visibleRect) { this.graphics = graphics; this.panel = panel; this.graphicCache = new HashMap(); this.referenceFrame = referenceFrame; this.visibleRect = visibleRect; if (PreferencesManager.getPreferences().getAsBoolean(ENABLE_ANTIALISING) && graphics != null) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } } public RenderContext(RenderContext context) { this.graphics = context.getGraphics(); this.graphicCache = new HashMap<>(); this.referenceFrame = new ReferenceFrame(context.referenceFrame); this.panel = context.panel; this.visibleRect = new Rectangle(context.visibleRect); if (PreferencesManager.getPreferences().getAsBoolean(ENABLE_ANTIALISING) && graphics != null) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } } public Graphics2D getGraphics() { return graphics; } public void clearGraphicsCache() { graphicCache.clear(); } public Graphics2D getGraphics2D(Object key) { Graphics2D g = graphicCache.get(key); if (g == null) { g = (Graphics2D) graphics.create(); if (PreferencesManager.getPreferences().getAsBoolean(ENABLE_ANTIALISING)) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } graphicCache.put(key, g); } return g; } public Graphics2D getGraphic2DForColor(Color color) { Graphics2D g = getGraphics2D(color); g.setColor(color); return g; } public Color getBackgroundColor() { return panel.getBackground(); } public String getChr() { return referenceFrame.getChrName(); } public double getOrigin() { return referenceFrame.getOrigin(); } public double getEndLocation() { return referenceFrame.getEnd(); } public double getScale() { return referenceFrame.getScale(); } public Rectangle getVisibleRect() { return visibleRect; } public JComponent getPanel() { return panel; } public int getZoom() { return referenceFrame.getZoom(); } public ReferenceFrame getReferenceFrame() { return referenceFrame; } public boolean isMerged() { return merged; } public void setMerged(boolean merged) { this.merged = merged; } /** * Release graphics objects * * @throws java.lang.Throwable */ @Override protected void finalize() throws Throwable { super.finalize(); dispose(); } public void dispose() { // Note: don't dispose of "this.graphics", its used later to paint the border for (Graphics2D g : graphicCache.values()) { g.dispose(); } graphicCache.clear(); } public void setInsertionMarkers(List<InsertionMarker> insertionMarkers) { this.insertionMarkers = insertionMarkers; } public List<InsertionMarker> getInsertionMarkers() { return insertionMarkers; } }
mit
Feolive/EmploymentWebsite
src/main/java/com/charmyin/cmstudio/basic/authorize/service/impl/MenuServiceImpl.java
1729
package com.charmyin.cmstudio.basic.authorize.service.impl; import java.util.List; import javax.annotation.Resource; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Service; import com.charmyin.cmstudio.basic.authorize.persistence.MenuMapper; import com.charmyin.cmstudio.basic.authorize.service.MenuService; import com.charmyin.cmstudio.basic.authorize.vo.Menu; @Service public class MenuServiceImpl implements MenuService { @Resource private MenuMapper menuMapper ; @Override /*@RequiresPermissions("menu:getallxx")*/ public List<Menu> getAllMenu() { List<Menu> menuList = menuMapper.getAllMenu(); return menuList; } @Override public List<Menu> getChildrenMenus(int parentId) { Menu menu = new Menu(); menu.setParentId(parentId); List<Menu> menuList = menuMapper.getMenuEqual(menu); return menuList; } @Override public void insertMenu(Menu menu){ menuMapper.insertMenu(menu); } @Override public void updateMenu(Menu menu) { menuMapper.updateMenu(menu); } @Override public void deleteMenu(int[] ids) { for(int id : ids){ menuMapper.deleteMenu(id); } } @Override public List<Menu> searchMenu(Menu menu) { List<Menu> menuList = menuMapper.getMenuEqual(menu); return menuList; } @Override public Menu getMenuById(int id) { Menu menu = menuMapper.getMenuById(id); return menu; } @Override public List<Menu> getMenuByRole() { return null; } @Override public List<Menu> getMenuByUser() { // TODO Auto-generated method stub return null; } public MenuMapper getMenuMapper() { return menuMapper; } public void setMenuMapper(MenuMapper menuMapper) { this.menuMapper = menuMapper; } }
mit
doe300/jactiverecord-extensions
test/de/doe300/activerecord/record/bean/TestJavaBeanRecord.java
1814
/* * The MIT License * * Copyright 2015 doe300. * * 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.doe300.activerecord.record.bean; import de.doe300.activerecord.record.RecordType; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * * @author doe300 */ @RecordType(defaultColumns = {"id", "name", "age"}, typeName = "javaBeans") public interface TestJavaBeanRecord extends JavaBeanRecord { public String getName(); public void setName(String name); public int getAge(); public void setAge(int age); } class TestPropertyChangeListener implements PropertyChangeListener { private int count = 0; @Override public void propertyChange( PropertyChangeEvent evt ) { count++; } int getCount() { return count; } }
mit
SaberRobotics2506/Robot2017
src/src/org/usfirst/frc/team2506/robot/Shooter.java
1971
package org.usfirst.frc.team2506.robot; import com.ctre.CANTalon; import com.ctre.CANTalon.FeedbackDevice; import com.ctre.CANTalon.TalonControlMode; import edu.wpi.first.wpilibj.*; public class Shooter { //Used to set the speed of the bad shooter final double ENCODER_FULL_SPEED = 200; final double ENCODER_HALF_SPEED = ENCODER_FULL_SPEED / 2; final double HOPPER_SPEED = -0.5; private CANTalon shooter; private Victor hopper; public Shooter(int shooter, int hopper) { this.shooter = new CANTalon(shooter); this.hopper = new Victor(hopper); this.shooter.changeControlMode(TalonControlMode.Speed); this.shooter.setFeedbackDevice(FeedbackDevice.CtreMagEncoder_Relative); this.shooter.reverseSensor(true); this.shooter.configNominalOutputVoltage(+0.0f, -0.0f); this.shooter.configPeakOutputVoltage(+12.0f, -12.0f); this.shooter.setProfile(0); this.shooter.setF(.02); this.shooter.setP(-30); this.shooter.setI(0); this.shooter.setD(0); // setShooterResting(); } //For debugging shooter encoder public void printRPM() { System.out.println("speed " + shooter.getSpeed()); System.out.println("Error " + shooter.getClosedLoopError()); System.out.println("shooter.get: " + shooter.get()); //System.out.println(shooter.getOutputVoltage() / shooter.getBusVoltage()); } //Returns if the shooter is ready to fire public boolean readyToFire() { setShooterFiring(); return shooter.getSpeed() >= ENCODER_FULL_SPEED; } public void reset() { shooter.reset(); } public void startShooting() { hopper.set(HOPPER_SPEED); setShooterFiring(); } public void stopShooting() { hopper.set(0); setShooterResting(); } //stops shooter from shooting and puts shooter system to rest private void setShooterResting() { shooter.set(0); } //starts shooting systems at speed of 2000 private void setShooterFiring() { // this.shooter.changeControlMode(TalonControlMode.Speed); shooter.set(2000); } }
mit
tobias-vogel/mergecontacts
src/main/java/com/github/tobias_vogel/mergecontacts/data/AdditionalData.java
5008
package com.github.tobias_vogel.mergecontacts.data; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.github.tobias_vogel.mergecontacts.data.CardDavContact.CardDavContactAttributes; import com.google.common.base.Joiner; public abstract class AdditionalData { protected CardDavContactAttributes attribute; protected String value; private static final String NOTES_SPLIT_TOKEN = "<|>"; private static final Pattern NOTES_SPLIT_PATTERN = Pattern.compile(NOTES_SPLIT_TOKEN); // TODO use named capturing groups private static final Pattern IS_ADDITIONAL_DATA_PATTERN = Pattern .compile("((" + OldData.IDENTIFIER + "|" + AlternativeData.IDENTIFIER + "))-(.+)=(.+)"); /** * Parses the provided notes field value and extracts all additional data * fields. These fields are added to the provided additional data list. If * it is null, it is created. The notes field value is essentially clensed * from additional data and returned. * * @param notesValue * the value from the notes field * @param additionalData * a (possibly <code>null</code>) list of already known * additional data items * @return the notes field value without additional data */ public static String parseNotesAndMergeWithAdditionalDataAndEnrichAdditionalData(String notesValue, List<AdditionalData> additionalData) { if (notesValue == null) { return null; } List<String> noteFragments = new ArrayList<>(); if (additionalData == null) { additionalData = new ArrayList<>(); } String[] parts = NOTES_SPLIT_PATTERN.split(notesValue); for (String part : parts) { if (isAdditionalData(part)) { AdditionalData additionalDataElement = createAdditionalDataFromString(part); additionalData.add(additionalDataElement); } else { noteFragments.add(part); } } String joinedNoteFragments = Joiner.on(", ").join(noteFragments); return joinedNoteFragments; } private static AdditionalData createAdditionalDataFromString(String serializedAdditionalData) { Matcher matcher = IS_ADDITIONAL_DATA_PATTERN.matcher(serializedAdditionalData); boolean matchSuccessful = matcher.matches(); if (matchSuccessful) { String type = matcher.group("type"); String attributeAsString = matcher.group("attribute"); String value = matcher.group("value"); CardDavContactAttributes attribute = CardDavContactAttributes.valueOf(attributeAsString); AdditionalData additionalData; switch (type) { case AlternativeData.IDENTIFIER: additionalData = new AlternativeData(attribute, value); break; case OldData.IDENTIFIER: additionalData = new OldData(attribute, value); break; default: throw new RuntimeException("The provided additional data type (\"" + type + "\" is unknown."); } return additionalData; } else throw new RuntimeException("The provided string (\"" + serializedAdditionalData + "\") should have been a serialized additional data portion, but was not."); } private static boolean isAdditionalData(String part) { return IS_ADDITIONAL_DATA_PATTERN.matcher(part).matches(); } public static String generateNotesFieldContent(List<AdditionalData> additionalDataItems, String currentNotesFieldContent) { List<String> resultTokens = new ArrayList<>(1 + additionalDataItems.size()); resultTokens.add(currentNotesFieldContent); // TODO use java8 magic for (AdditionalData additionalDataItem : additionalDataItems) { resultTokens.add(additionalDataItem.createKeyValuePair()); } return Joiner.on(NOTES_SPLIT_TOKEN).join(resultTokens); } private String createKeyValuePair() { return getIdentifier() + "-" + attribute + "=" + value; } public static List<String> getFilteredCopyOfAdditionalData(CardDavContactAttributes filterAttribute, Class<? extends AdditionalData> filterTypeOfAdditionalData, List<AdditionalData> additionalData) { // TODO use java8 magic List<String> result = new ArrayList<>(); for (AdditionalData additionalDataItem : additionalData) { if (additionalDataItem.getClass() == filterTypeOfAdditionalData) { if (additionalDataItem.attribute == filterAttribute) { result.add(additionalDataItem.value); } } } return result; } public abstract String getIdentifier(); }
mit