repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
sourceress-project/archestica | src/games/stendhal/server/entity/npc/ConversationPhrases.java | 3366 | /* $Id: ConversationPhrases.java,v 1.25 2013/04/25 20:59:08 kiheru Exp $ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.entity.npc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* Common phrases used by players to interact with a SpeakerNPC.
*
* @author hendrik
*/
public class ConversationPhrases {
// define "no" trigger to be exactly matched while ignoring case
// (for available matching option strings see ExpressionMatcher)
public static final String NO_EXPRESSION = "|EXACT|ICASE|no";
// do not use a mutable list here
public static final List<String> EMPTY = Arrays.asList(new String[0]);
public static final List<String> GREETING_MESSAGES = Arrays.asList("hi",
"hello", "hallo", "greetings", "hola");
public static final List<String> JOB_MESSAGES = Arrays.asList("job", "work", "occupation");
public static final List<String> HELP_MESSAGES = Arrays.asList("help",
"ayuda");
public static final List<String> QUEST_MESSAGES = Arrays.asList("task",
"quest", "favor", "favour");
public static final List<String> FINISH_MESSAGES = Arrays.asList("done",
"finish", "complete");
public static final List<String> ABORT_MESSAGES = Arrays.asList("another", "abort");
public static final List<String> OFFER_MESSAGES = Arrays.asList("offer", "deal", "trade");
public static final List<String> YES_MESSAGES = Arrays.asList("yes", "ok", "yep", "sure");
public static final List<String> NO_MESSAGES = Arrays.asList(NO_EXPRESSION, "nope",
"nothing", "none");
public static final List<String> GOODBYE_MESSAGES = Arrays.asList("bye", "goodbye",
"farewell", "cya", "adios");
/**
* Combine a string collection (list) with additional strings.
*
* @param list
* @param args additional strings
* @return new list with the contents of the list and all the additional
* strings
*/
public static final List<String> combine(Collection<String> list, String ...args) {
List<String> ret = new ArrayList<String>(list);
for(String s : args) {
ret.add(s);
}
return ret;
}
/**
* Combine a string collection with other collections.
*
* @param list1
* @param lists
* @return a new list with contents of all the collections
*/
public static final List<String> combine(Collection<String> list1, Collection<String>... lists) {
List<String> ret = new LinkedList<String>(list1);
for (Collection<String> list : lists) {
ret.addAll(list);
}
return ret;
}
}
| gpl-2.0 |
jiangchanghong/Mycat2 | src/main/java/io/mycat/web/webconfig/DBconfig.java | 2760 | package io.mycat.web.webconfig;
import io.mycat.config.model.SchemaConfig;
import io.mycat.web.config.MyConfigLoader;
import io.mycat.web.config.MyReloadConfig;
import io.mycat.web.model.ReturnMessage;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Map;
/**
* Created by jiang on 2016/12/3 0003.
* 逻辑数据库的功能
*/
@SuppressWarnings("Duplicates")
@RestController
public class DBconfig {
/**
* Gets .
* 得到所有的数据库
*
* @return the
*/
@GetMapping(value = "/getdbs")
public ReturnMessage getsys() {
ReturnMessage returnMessage = new ReturnMessage();
Map<String, SchemaConfig> systemConfig = MyConfigLoader.getInstance().getSchemaConfigs();
returnMessage.setObject(systemConfig.values().toArray());
returnMessage.setError(false);
return returnMessage;
}
/**
* Sets .删除一个数据库
*dbname为需要删除的数据库的名字
* @param d the d
* @param result the result
* @return
*/
@PostMapping(value = "/removedb/{dbname}")
public ReturnMessage setsysconfig(@PathVariable String dbname) {
ReturnMessage returnMessage = new ReturnMessage();
MyConfigLoader.getInstance().getSchemaConfigs().remove(dbname);
MyConfigLoader.getInstance().save();
String dd= MyReloadConfig.reloadconfig(false);
if (dd == null) {
returnMessage.setError(false);
}
else {
returnMessage.setMessage(dd);
returnMessage.setError(true);
}
return returnMessage;
}
/**
* Sets .增加一个数据库。
*
* @param d the d
* @param result the result
* @return the
*/
@PostMapping(value = "/adddatabase")
public ReturnMessage setsysconfig(@Valid @RequestBody SchemaConfig schemaConfig, BindingResult result) {
ReturnMessage returnMessage = new ReturnMessage();
if (result.hasErrors()) {
returnMessage.setError(true);
returnMessage.setMessage(result.toString());
return returnMessage;
}
Map<String,SchemaConfig> map = MyConfigLoader.getInstance().getSchemaConfigs();
map.put(schemaConfig.getName(), schemaConfig);
MyConfigLoader.getInstance().setSchemaConfigMap(map);
MyConfigLoader.getInstance().save();
String dd = MyReloadConfig.reloadconfig(false);
if (dd == null) {
returnMessage.setError(false);
} else {
returnMessage.setMessage(dd);
returnMessage.setError(true);
}
return returnMessage;
}
}
| gpl-2.0 |
Opencontent/OCParchiTn | src/it/opencontent/android/ocparchitn/SOAPMappings/SOAPGioco.java | 4556 | package it.opencontent.android.ocparchitn.SOAPMappings;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable;
public class SOAPGioco implements KvmSerializable {
public String descrizioneArea;
public String descrizioneGioco;
public String descrizioneMarca;
public String dtAcquisto;
public String dtInstallazione;
public String dtPosizionamentoAl;
public String dtPosizionamentoDal;
public String dtProssimaManutenzione;
public String dtProssimaVerifica;
public String gpsx;
public String gpsy;
public String idGioco;
public String idModello;
public String idScheda;
public String idTipoGioco;
public String note;
public int numeroFotografie;
public String numeroSerie;
public String posizioneRfid;
public String rfid;
public String rfidArea;
public String rifCartografia;
@Override
public Object getProperty(int arg0) {
switch(arg0){
case 0:
return descrizioneArea;
case 1:
return descrizioneGioco;
case 2:
return descrizioneMarca;
case 3:
return dtAcquisto;
case 4:
return dtInstallazione;
case 5:
return dtPosizionamentoAl;
case 6:
return dtPosizionamentoDal;
case 7:
return dtProssimaManutenzione;
case 8:
return dtProssimaVerifica;
case 9:
return gpsx;
case 10:
return gpsy;
case 11:
return idGioco;
case 12:
return idModello;
case 13:
return idScheda;
case 14:
return idTipoGioco;
case 15:
return note;
case 16:
return numeroFotografie;
case 17:
return numeroSerie;
case 18:
return posizioneRfid;
case 19:
return rfid;
case 20:
return rfidArea;
case 21:
return rifCartografia;
}
return null;
}
@Override
public int getPropertyCount() {
return 22;
}
@Override
public void getPropertyInfo(int arg0, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo arg2) {
arg2.type = PropertyInfo.STRING_CLASS;
switch(arg0){
case 0:
arg2.name = "descrizioneArea";
break;
case 1:
arg2.name = "descrizioneGioco";
break;
case 2:
arg2.name = "descrizioneMarca";
break;
case 3:
arg2.name = "dtAcquisto";
break;
case 4:
arg2.name = "dtInstallazione";
break;
case 5:
arg2.name = "dtPosizionamentoAl";
break;
case 6:
arg2.name = "dtPosizionamentoDal";
break;
case 7:
arg2.name = "dtProssimaManutenzione";
break;
case 8:
arg2.name = "dtProssimaVerifica";
break;
case 9:
arg2.name = "gpsx";
break;
case 10:
arg2.name = "gpsy";
break;
case 11:
arg2.name = "idGioco";
break;
case 12:
arg2.name = "idModello";
break;
case 13:
arg2.name = "idScheda";
break;
case 14:
arg2.name = "idTipoGioco";
break;
case 15:
arg2.name = "note";
break;
case 16:
arg2.name = "numeroFotografie";
arg2.type = PropertyInfo.INTEGER_CLASS;
break;
case 17:
arg2.name = "numeroSerie";
break;
case 18:
arg2.name = "posizioneRfid";
break;
case 19:
arg2.name = "rfid";
break;
case 20:
arg2.name = "rfidArea";
break;
case 21:
arg2.name = "rifCartografia";
break;
}
}
@Override
public void setProperty(int arg0, Object arg1) {
if(arg1 == null){
arg1 = "";
}
switch(arg0){
case 0:
descrizioneArea = arg1.toString();
break;
case 1:
descrizioneGioco= arg1.toString();
break;
case 2:
descrizioneMarca= arg1.toString();
break;
case 3:
dtAcquisto= arg1.toString();
break;
case 4:
dtInstallazione= arg1.toString();
break;
case 5:
dtPosizionamentoAl= arg1.toString();
break;
case 6:
dtPosizionamentoDal= arg1.toString();
break;
case 7:
dtProssimaManutenzione = arg1.toString();
break;
case 8:
dtProssimaVerifica= arg1.toString();
break;
case 9:
gpsx= arg1.toString();
break;
case 10:
gpsy= arg1.toString();
break;
case 11:
idGioco= arg1.toString();
break;
case 12:
idModello= arg1.toString();
break;
case 13:
idScheda = arg1.toString();
break;
case 14:
idTipoGioco= arg1.toString();
break;
case 15:
note= arg1.toString();
break;
case 16:
numeroFotografie= Integer.parseInt(arg1.toString());
break;
case 17:
numeroSerie= arg1.toString();
break;
case 18:
posizioneRfid= arg1.toString();
break;
case 19:
rfid= arg1.toString();
break;
case 20:
rfidArea= arg1.toString();
break;
case 21:
rifCartografia= arg1.toString();
break;
}
}
} | gpl-2.0 |
ireyoner/SensorDataAquisitor | src/project/data/Datagram.java | 824 | package project.data;
import java.math.BigDecimal;
public class Datagram {
private BigDecimal id;
private final String data;
private boolean dataSend;
public Datagram(BigDecimal id, String data) {
this.id = id;
this.data = data;
this.dataSend = false;
}
public Datagram(String data){
this.id = null;
this.data = data;
this.dataSend = false;
}
public boolean isDataSend() {
return dataSend;
}
public void setDataSend(boolean dataSend) {
this.dataSend = dataSend;
}
public void setId(BigDecimal id) throws Exception {
if (id == null) {
this.id = id;
} else {
throw new Exception("Id is already set [current id: ("
+ this.id
+ ") new id: ("
+ id
+ ")]");
}
}
public BigDecimal getId() {
return id;
}
public String getData() {
return data;
}
}
| gpl-2.0 |
carvalhomb/tsmells | sample/anastacia/anastacia/messenger/Yahoo/YahooPacketFactory.java | 4006 | /** Anastacia is a Java ICQ/MSN/Yahoo Instant Messenger
* Copyright (C) 2002,2003 Benny Van Aerschot, Bart Van Rompaey
* Made as a project in 3th year computer science at the university of Antwerp (UA)
*
* This file is part of Anastacia.
*
* Anastacia is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Anastacia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Anastacia; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact authors:
* Benny Van Aerschot - bennyva@pi.be
* Bart Van Rompaey - bart@perfectpc.be
*/
package messenger.Yahoo;
import messenger.IPacketFactory;
import messenger.IPacket;
import messenger.UnknownPacketException;
import messenger.BadArgumentException;
import messenger.Utils;
import java.util.Vector;
/**
* @author Bart Van Rompaey
* @version $Revision: 1.4 $
* @date $Date: 2003/05/25 10:15:50 $
*
*
*/
public class YahooPacketFactory implements IPacketFactory {
/**
* @see messenger.IPacketFactory#createOutgoingPacket(java.lang.String, java.util.Vector)
*/
public IPacket createOutgoingPacket(String packet, Vector arg) throws UnknownPacketException, BadArgumentException {
if(packet.equals("CLI_HELLO")) {
return new YahooCLI_HELLOPacket(arg);
}
else if(packet.equals("CLI_AUTH")) {
return new YahooCLI_AUTHPacket(arg);
}
else if(packet.equals("CLI_AUTH_RESP")) {
return new YahooCLI_AUTH_RESPPacket(arg);
}
else if(packet.equals("CLI_PASSTHROUGH2")) {
return new YahooCLI_PASSTHROUGH2Packet(arg);
}
else if(packet.equals("CLI_0015")) {
return new YahooCLI_0015Packet(arg);
}
else if(packet.equals("CLI_ISBACK")) {
return new YahooCLI_ISBACKPacket(arg);
}
else if(packet.equals("CLI_ISAWAY")) {
return new YahooCLI_ISAWAYPacket(arg);
}
else if(packet.equals("CLI_MESSAGE")) {
return new YahooCLI_MESSAGEPacket(arg);
}
else {
throw new UnknownPacketException();
}
}
/**
* @see messenger.IPacketFactory#createIncomingPacket(java.lang.String)
*/
public IPacket createIncomingPacket(String s) throws UnknownPacketException {
//System.out.println("creaeteincomingpacket");
if(s.length() < 23) {
//System.out.println("short message:");
//System.out.println(Utils.printableHexString(s));
throw new UnknownPacketException();
}
else if((s.charAt(22) == '0') && (s.charAt(23) == '1')) {
return new YahooSRV_LOGONPacket(s);
}
else if((s.charAt(22) == '0')&&(s.charAt(23) == '2')) {
return new YahooSRV_LOGOFFPacket(s);
}
else if((s.charAt(22) == '0')&&(s.charAt(23) == '4')) {
return new YahooSRV_ISBACKACKPacket(s);
}
else if((s.charAt(22) == '0')&&(s.charAt(23) == '6')) {
return new YahooSRV_MESSAGEPacket(s);
}
else if((s.charAt(22) == '4')&&(s.charAt(23) == 'b')) {
return new YahooSRV_NOTIFYPacket(s);
}
else if((s.charAt(22) == '4')&&(s.charAt(23) == 'c')) {
System.out.println("server - hello");
return new YahooSRV_HELLOPacket(s);
}
else if((s.charAt(22) == '5') && (s.charAt(23) == '4')) {
return new YahooSRV_AUTH_RESPPacket(s);
}
else if((s.charAt(22) == '5') && (s.charAt(23) == '5')) {
return new YahooSRV_LISTPacket(s);
}
else if((s.charAt(22) == '5')&&(s.charAt(23) == '7')) {
return new YahooSRV_AUTHPacket(s);
}
else {
System.out.println("creaeteincomingpacket - unknown: "+s.charAt(22)+" "+s.charAt(23));
throw new UnknownPacketException();
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/rngom/ast/builder/Scope.java | 1787 | /*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.xml.internal.rngom.ast.builder;
import com.sun.xml.internal.rngom.ast.om.Location;
import com.sun.xml.internal.rngom.ast.om.ParsedPattern;
import com.sun.xml.internal.rngom.ast.om.ParsedElementAnnotation;
public interface Scope<
P extends ParsedPattern,
E extends ParsedElementAnnotation,
L extends Location,
A extends Annotations<E,L,CL>,
CL extends CommentList<L> > extends GrammarSection<P,E,L,A,CL> {
P makeParentRef(String name, L loc, A anno) throws BuildException;
P makeRef(String name, L loc, A anno) throws BuildException;
}
| gpl-2.0 |
DigohD/CR | src/com/cr/engine/graphics/ColorRGBA.java | 514 | package com.cr.engine.graphics;
public class ColorRGBA {
public static final int BLACK = 0;
public static final int WHITE = 0xffffffff;
public static final int RED = 0xffff0000;
public static final int GREEN = 0xff00ff00;
public static final int BLUE = 0xff0000ff;
public static final int YELLOW = 0xffffff00;
public static final int PINK = 0xffff00ff;
public static final int GRAY = 0xff808080;
public static final int BROWN = 0xff7f0000;
public static final int ORANGE = 0xffff6a00;
}
| gpl-2.0 |
iWantMoneyMore/ykj | ykj-api/src/main/java/com/gnet/app/design/DesignController.java | 13343 | package com.gnet.app.design;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.rest.webmvc.RepositoryLinksResource;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
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.multipart.MultipartFile;
import com.gnet.app.clerk.Clerk;
import com.gnet.app.orderService.OrderSer;
import com.gnet.app.orderService.OrderServiceErrorBuilder;
import com.gnet.app.orderService.OrderServiceResource;
import com.gnet.app.orderServiceAttachment.OrderServiceAttachment;
import com.gnet.app.orderServiceAttachment.OrderServiceAttachmentController;
import com.gnet.app.orderServiceAttachment.OrderServiceAttachmentErrorBuilder;
import com.gnet.app.orderServiceAttachment.OrderServiceAttachmentService;
import com.gnet.resource.boolResource.BooleanResourceAssembler;
import com.gnet.security.user.CustomUser;
import com.gnet.upload.FileUploadService;
import com.gnet.utils.download.DownResponseBuilder;
import com.gnet.utils.spring.SpringContextHolder;
@RepositoryRestController
@ExposesResourceFor(OrderSer.class)
@RequestMapping("/api/designs")
public class DesignController implements ResourceProcessor<RepositoryLinksResource> {
@Autowired
private DesignService designService;
@Autowired
private OrderServiceAttachmentService orderServiceAttachmentService;
/**
* 设计详细信息
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getDesign(
@PathVariable("id") String id
){
if(StringUtils.isBlank(id)){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_ID_NULL, "设计服务编号为空").build());
}
OrderSer design = designService.findById(id);
if (design == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_SERVICE_NULL, "找不到设计服务").build());
}
DesignResourceAssembler orderServiceResourceAssembler = new DesignResourceAssembler();
OrderServiceResource orderServiceResource = orderServiceResourceAssembler.toResource(design);
return ResponseEntity.ok(orderServiceResource);
}
/**
* 增加设计服务
* @param design
* @param authentication
* @return
*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createDesign(
@RequestBody OrderSer design,
Authentication authentication
) {
CustomUser customUser = (CustomUser) authentication.getPrincipal();
Clerk clerk = customUser.getClerk();
Date date = new Date();
design.setCreateDate(date);
design.setModifyDate(date);
design.setType(OrderSer.TYPE_DESIGN);
design.setIsDel(Boolean.FALSE);
design.setIsClear(Boolean.FALSE);
Map<String, Object> error = DesignValidator.validateBeforeCreateDesign(design, clerk.getBusinessId());
if (error != null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new OrderServiceErrorBuilder(Integer.valueOf(error.get("code").toString()), error.get("msg").toString()).build());
}
Boolean result = designService.create(design);
if (result) {
return ResponseEntity.created(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DesignController.class).getDesign(design.getId())).toUri()).build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_CREATED, "创建错误").build());
}
/**
* 更新设计服务
* @param id
* @param design
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateDesign(
@PathVariable("id") String id,
@RequestBody OrderSer design,
Authentication authentication
){
CustomUser customUser = (CustomUser) authentication.getPrincipal();
Clerk clerk = customUser.getClerk();
Date date = new Date();
design.setModifyDate(date);
design.setId(id);
Map<String, Object> error = DesignValidator.validateBeforeUpdateDesign(design, clerk.getBusinessId());
if (error != null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new OrderServiceErrorBuilder(Integer.valueOf(error.get("code").toString()), error.get("msg").toString()).build());
}
Boolean result = designService.update(design);
if (result) {
return ResponseEntity.noContent().location(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DesignController.class).getDesign(id)).toUri()).build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_EDITED, "更新错误").build());
}
/**
* 结算设计服务
* @param id
* @param measure
* @return
*/
@RequestMapping(value = "/{id}/statement", method = RequestMethod.PATCH)
public ResponseEntity<?> stateDesign(
@PathVariable("id") String id
){
if(StringUtils.isBlank(id)){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_ID_NULL, "设计服务编号为空").build());
}
OrderSer design = designService.findById(id);
if (design == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_SERVICE_NULL, "找不到测量服务").build());
}
Map<String, Object> error = DesignValidator.validateBeforeUpdateState(design);
if (error != null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new OrderServiceErrorBuilder(Integer.valueOf(error.get("code").toString()), error.get("msg").toString()).build());
}
Date date = new Date();
design.setModifyDate(date);
design.setIsClear(Boolean.TRUE);
Boolean result = designService.update(design);
if (result) {
return ResponseEntity.noContent().location(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DesignController.class).getDesign(id)).toUri()).build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_EDITED, "更新错误").build());
}
/**
* 取消结算设计服务
* @param id
* @param measure
* @return
*/
@RequestMapping(value = "/{id}/cancelStatement", method = RequestMethod.PATCH)
public ResponseEntity<?> cacelStateDesign(
@PathVariable("id") String id
){
if(StringUtils.isBlank(id)){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_ID_NULL, "设计服务编号为空").build());
}
OrderSer design = designService.findById(id);
if (design == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_SERVICE_NULL, "找不到设计服务").build());
}
Map<String, Object> error = DesignValidator.validateBeforeUpdateCancelState(design);
if (error != null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new OrderServiceErrorBuilder(Integer.valueOf(error.get("code").toString()), error.get("msg").toString()).build());
}
Date date = new Date();
design.setModifyDate(date);
design.setIsClear(Boolean.FALSE);
Boolean result = designService.update(design);
if (result) {
return ResponseEntity.noContent().location(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DesignController.class).getDesign(id)).toUri()).build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_EDITED, "更新错误").build());
}
/**
* 上传附件
* @param fileType
* @param file
* @param authentication
* @return
*/
@RequestMapping(path = "/attachment_upload", method = RequestMethod.POST)
public ResponseEntity<?> upload(
@Param("fileType") String fileType,
@RequestParam("file") MultipartFile file,
Authentication authentication
){
CustomUser customUser = (CustomUser) authentication.getPrincipal();
if (file == null) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_UPLOAD, "未获得上传文件").build());
}
FileUploadService fileUploadService = SpringContextHolder.getBean(FileUploadService.class);
Resource uploadResource = fileUploadService.getResource(file, fileType);
if(uploadResource == null){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_UPLOAD, "上传失败").build());
}
String path = null;
try {
path = uploadResource.getFile().getPath();
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_UPLOAD, "上传失败").build());
}
Date date = new Date();
OrderServiceAttachment attachment = new OrderServiceAttachment();
attachment.setCreateDate(date);
attachment.setModifyDate(date);
attachment.setAttachmentRoot(fileUploadService.getRelativePath(path));
attachment.setAttachmentSize(String.valueOf(file.getSize()));
attachment.setAttachmentFilename(file.getOriginalFilename());
attachment.setUploadDate(date);
attachment.setUploadPersonId(customUser.getId());
Boolean result = orderServiceAttachmentService.create(attachment);
if (result) {
return ResponseEntity.created(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(OrderServiceAttachmentController.class).getOrderServiceAttachment(attachment.getId())).toUri()).build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_UPLOAD, "上传失败").build());
}
/**
* 下载附件
* @param id
* @return
*/
@RequestMapping(path = "/{id}/attachment_download", method = RequestMethod.GET)
public ResponseEntity<?> download(
@PathVariable("id") String id,
HttpServletResponse response
){
FileUploadService fileUploadService = SpringContextHolder.getBean(FileUploadService.class);
if(StringUtils.isBlank(id)){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new OrderServiceAttachmentErrorBuilder(OrderServiceAttachmentErrorBuilder.ERROR_ID_NULL, "附件编号为空").build());
}
OrderServiceAttachment attachment = orderServiceAttachmentService.findById(id);
FileSystemResource resource = new FileSystemResource(fileUploadService.getUploadRootPath() + attachment.getAttachmentRoot());
try {
DownResponseBuilder.buildFile(response, resource, attachment.getAttachmentFilename());
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_DOWNLOAD, "下载附件失败").build());
}
return ResponseEntity.ok(null);
}
/**
* 删除设计服务
* @param id
* @param authentication
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteMeasure(
@PathVariable("id") String id
){
Map<String, Object> error = DesignValidator.validateBeforeDeleteOrderService(id);
if (error != null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new OrderServiceErrorBuilder(Integer.valueOf(error.get("code").toString()), error.get("msg").toString()).build());
}
if (designService.delete(id, new Date())) {
BooleanResourceAssembler booleanResourceAssembler = new BooleanResourceAssembler();
return ResponseEntity.ok(booleanResourceAssembler.toResource(Boolean.TRUE));
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new OrderServiceErrorBuilder(OrderServiceErrorBuilder.ERROR_DELETED, "删除错误").build());
}
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(ControllerLinkBuilder.linkTo(DesignController.class).withRel("measures"));
return resource;
}
} | gpl-2.0 |
sdyy1990/NSim | NSimMSG/src/SmallWorld/SmallworldBed.java | 2402 | package SmallWorld;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Vector;
import Jellyfish.JellyfishBed;
import Jellyfish.Jellyfish_Topo;
import SimpleBed.SimpleBed;
import Support.Entity;
import Support.EventManager;
import Support.Simusys;
import TCP.TCPBony;
public class SmallworldBed {
public static void main(String args[]) {
if (args.length <5) {
System.out.println("Smallworld Simulator");
System.out.println("arg0 : dim ");
System.out.println("arg1 : width ");
System.out.println("arg2 : height ,can be 0");
System.out.println("arg3 : depth, can be 0");
System.out.println("arg4 : flow per link");
System.out.println("arg5 : flow size in KB");
System.out.println("arg6 : end time in e-5 s");
System.out.println("arg7 : tot port number / switch");
System.out.println("arg8 : tot hosts");
System.out.println("arg9 : loadAware > 0");
}
int dim = Integer.parseInt(args[0]);
int width = Integer.parseInt(args[1]);
int height = Integer.parseInt(args[2]);
int depth = Integer.parseInt(args[3]);
SmallWorldTopo topo = new SmallWorldTopo(dim,width, height, depth,Integer.parseInt(args[7]),Integer.parseInt(args[8]));
//SmallWorldTopo topo = new SmallWorldTopo(1,128,10,0);
int hosts = topo.hosts.length;
int flowperhost = Integer.parseInt(args[4]);
int flows = (int) (topo.hosts.length) * flowperhost;
TCPBony[] tcpc = new TCPBony[flows];
TCPBony[] tcps = new TCPBony[flows];
int permu[] = Simusys.getpermu(hosts,hosts);
for (int i = 0 ; i < flows; i++) {
tcpc[i] = new TCPBony(topo.hosts[permu[i % hosts]],(short)(i+1),Integer.parseInt(args[5]));
tcps[i] = new TCPBony(topo.hosts[permu[(i+1) % hosts]],(short) (i+1));
}
for (int i = 0 ; i < flows; i++) {
tcpc[i].setPeer(tcps[i], true);
tcps[i].setPeer(tcpc[i], false);
}
Simusys.reset();
Simusys.setLink(topo.links);
long end = Integer.parseInt(args[6]);
for (int i = 0; i < flows; i++)
tcpc[i].send();
SimpleBed simplebed = new SimpleBed();
simplebed.bedrun(end, tcpc,hosts,Integer.parseInt(args[9])>0);
}
}
| gpl-2.0 |
Beriol/IUM_Project_SwimDroid | src/com/roomorama/caldroid/CaldroidGridAdapter.java | 8153 | package com.roomorama.caldroid;
import hirondelle.date4j.DateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.swimdroid.R;
/**
* The CaldroidGridAdapter provides customized view for the dates gridview
*
* @author thomasdao
*
*/
public class CaldroidGridAdapter extends BaseAdapter {
protected ArrayList<DateTime> datetimeList;
protected int month;
protected int year;
protected Context context;
protected ArrayList<DateTime> selectedDates;
// Use internally, to make the search for date faster instead of using
// indexOf methods on ArrayList
protected HashMap<DateTime, Integer> selectedDatesMap = new HashMap<DateTime, Integer>();
protected DateTime minDateTime;
protected DateTime maxDateTime;
protected DateTime today;
protected int startDayOfWeek;
protected boolean sixWeeksInCalendar;
protected Resources resources;
/**
* caldroidData belongs to Caldroid
*/
protected HashMap<String, Object> caldroidData;
/**
* extraData belongs to client
*/
protected HashMap<String, Object> extraData;
public void setAdapterDateTime(DateTime dateTime) {
this.month = dateTime.getMonth();
this.year = dateTime.getYear();
this.datetimeList = CalendarHelper.getFullWeeks(this.month, this.year,
startDayOfWeek, sixWeeksInCalendar);
}
// GETTERS AND SETTERS
public ArrayList<DateTime> getDatetimeList() {
return datetimeList;
}
public DateTime getMinDateTime() {
return minDateTime;
}
public void setMinDateTime(DateTime minDateTime) {
this.minDateTime = minDateTime;
}
public DateTime getMaxDateTime() {
return maxDateTime;
}
public void setMaxDateTime(DateTime maxDateTime) {
this.maxDateTime = maxDateTime;
}
public ArrayList<DateTime> getSelectedDates() {
return selectedDates;
}
public void setSelectedDates(ArrayList<DateTime> selectedDates) {
this.selectedDates = selectedDates;
}
public HashMap<String, Object> getCaldroidData() {
return caldroidData;
}
public void setCaldroidData(HashMap<String, Object> caldroidData) {
this.caldroidData = caldroidData;
// Reset parameters
populateFromCaldroidData();
}
public HashMap<String, Object> getExtraData() {
return extraData;
}
public void setExtraData(HashMap<String, Object> extraData) {
this.extraData = extraData;
}
/**
* Constructor
*
* @param context
* @param month
* @param year
* @param caldroidData
* @param extraData
*/
public CaldroidGridAdapter(Context context, int month, int year,
HashMap<String, Object> caldroidData,
HashMap<String, Object> extraData) {
super();
this.month = month;
this.year = year;
this.context = context;
this.caldroidData = caldroidData;
this.extraData = extraData;
this.resources = context.getResources();
// Get data from caldroidData
populateFromCaldroidData();
}
/**
* Retrieve internal parameters from caldroid data
*/
@SuppressWarnings("unchecked")
private void populateFromCaldroidData() {
selectedDates = (ArrayList<DateTime>) caldroidData.get(CaldroidFragment.SELECTED_DATES);
if (selectedDates != null) {
selectedDatesMap.clear();
for (DateTime dateTime : selectedDates) {
selectedDatesMap.put(dateTime, 1);
}
}
minDateTime = (DateTime) caldroidData.get(CaldroidFragment._MIN_DATE_TIME);
maxDateTime = (DateTime) caldroidData.get(CaldroidFragment._MAX_DATE_TIME);
startDayOfWeek = (Integer) caldroidData.get(CaldroidFragment.START_DAY_OF_WEEK);
sixWeeksInCalendar = (Boolean) caldroidData.get(CaldroidFragment.SIX_WEEKS_IN_CALENDAR);
this.datetimeList = CalendarHelper.getFullWeeks(this.month, this.year,startDayOfWeek, sixWeeksInCalendar);
}
protected DateTime getToday() {
if (today == null) {
today = CalendarHelper.convertDateToDateTime(new Date());
}
return today;
}
@SuppressWarnings("unchecked")
protected void setCustomResources(DateTime dateTime, TextView textView) {
// Set custom background resource
HashMap<DateTime, Integer> backgroundForDateTimeMap = (HashMap<DateTime, Integer>) caldroidData.get(CaldroidFragment._BACKGROUND_FOR_DATETIME_MAP);
if (backgroundForDateTimeMap != null) {
// Get background resource for the dateTime
Integer backgroundResource = backgroundForDateTimeMap.get(dateTime);
// Set it
if (backgroundResource != null) {
textView.setBackgroundResource(backgroundResource.intValue());
}
}
// Set custom text color
HashMap<DateTime, Integer> textColorForDateTimeMap = (HashMap<DateTime, Integer>) caldroidData
.get(CaldroidFragment._TEXT_COLOR_FOR_DATETIME_MAP);
if (textColorForDateTimeMap != null) {
// Get textColor for the dateTime
Integer textColorResource = textColorForDateTimeMap.get(dateTime);
// Set it
if (textColorResource != null) {
textView.setTextColor(resources.getColor(textColorResource
.intValue()));
}
}
}
/**
* Customize colors of text and background based on states of the cell
* (disabled, active, selected, etc)
*
* To be used only in getView method
*
* @param position
* @param cellView
*/
protected void customizeTextView(int position, TextView cellView) {
cellView.setTextColor(Color.BLACK);
// Get dateTime of this cell
DateTime dateTime = this.datetimeList.get(position);
// Set color of the dates in previous / next month
if (dateTime.getMonth() != month) {
cellView.setTextColor(resources
.getColor(R.color.caldroid_darker_gray));
}
boolean shouldResetDiabledView = false;
boolean shouldResetSelectedView = false;
// Customize for disabled dates and date outside min/max dates
if ((minDateTime != null && dateTime.lt(minDateTime)) || (maxDateTime != null && dateTime.gt(maxDateTime))) {
cellView.setTextColor(CaldroidFragment.disabledTextColor);
if (CaldroidFragment.disabledBackgroundDrawable == -1) {
cellView.setBackgroundResource(R.drawable.disable_cell);
} else {
cellView.setBackgroundResource(CaldroidFragment.disabledBackgroundDrawable);
}
if (dateTime.equals(getToday())) {
cellView.setBackgroundResource(R.drawable.today_border_grey);
}
} else {
shouldResetDiabledView = true;
}
// Customize for selected dates
if (selectedDates != null && selectedDatesMap.containsKey(dateTime)) {
if (CaldroidFragment.selectedBackgroundDrawable != -1) {
cellView.setBackgroundResource(CaldroidFragment.selectedBackgroundDrawable);
} else {
cellView.setBackgroundColor(resources.getColor(R.color.caldroid_sky_blue));
}
cellView.setTextColor(CaldroidFragment.selectedTextColor);
} else {
shouldResetSelectedView = true;
}
if (shouldResetDiabledView && shouldResetSelectedView) {
// Customize for today
if (dateTime.equals(getToday())) {
cellView.setBackgroundResource(R.drawable.today_without_border_selector);
} else {
cellView.setBackgroundResource(R.drawable.cell_bg);
}
}
cellView.setText("" + dateTime.getDay());
// Set custom color if required
setCustomResources(dateTime, cellView);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return this.datetimeList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView cellView = (TextView) convertView;
// For reuse
if (convertView == null) {
cellView = (TextView) inflater.inflate(R.layout.date_cell, null);
}
customizeTextView(position, cellView);
return cellView;
}
@Override
public void notifyDataSetChanged() {
this.selectedDates = selectedDates;
super.notifyDataSetChanged();
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/widget/src/com/mediatek/common/widget/tests/listview/ListItemFocusableAboveUnfocusable.java | 1661 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mediatek.common.widget.tests.listview;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.mediatek.common.widget.tests.util.ListItemFactory;
import com.mediatek.common.widget.tests.util.ListScenario;
/**
* A list where the items may befocusable, but the second item isn't actually focusabe.
*/
public class ListItemFocusableAboveUnfocusable extends ListScenario {
protected void init(Params params) {
params.setNumItems(2)
.setItemsFocusable(true)
.setItemScreenSizeFactor(0.2)
.setMustFillScreen(false);
}
@Override
protected View createView(int position, ViewGroup parent, int desiredHeight) {
if (position == 0) {
return ListItemFactory.button(
position, parent.getContext(), getValueAtPosition(position), desiredHeight);
} else {
return super.createView(position, parent, desiredHeight);
}
}
}
| gpl-2.0 |
chfoo/areca-backup-release-mirror | src/com/application/areca/impl/handler/DefaultArchiveHandler.java | 3185 | package com.application.areca.impl.handler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.application.areca.ApplicationException;
import com.application.areca.context.ProcessContext;
import com.application.areca.impl.FileSystemRecoveryEntry;
import com.application.areca.impl.copypolicy.AbstractCopyPolicy;
import com.application.areca.impl.tools.RecoveryFilterMap;
import com.application.areca.metadata.transaction.TransactionPoint;
import com.myJava.file.FileTool;
import com.myJava.file.driver.DriverAlreadySetException;
import com.myJava.file.driver.FileSystemDriver;
import com.myJava.object.Duplicable;
import com.myJava.util.taskmonitor.TaskCancelledException;
/**
* Default handler : handles standard files.
* <BR>
* @author Olivier PETRUCCI
* <BR>
*
*/
/*
Copyright 2005-2015, Olivier PETRUCCI.
This file is part of Areca.
Areca is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Areca is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Areca; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
public class DefaultArchiveHandler
extends AbstractArchiveHandler {
public void store(FileSystemRecoveryEntry entry, InputStream in, OutputStream out, ProcessContext context)
throws ApplicationException, IOException, TaskCancelledException {
FileTool.getInstance().copy(in, out, true, false, context.getTaskMonitor());
}
public void recoverRawData(
File[] archivesToRecover,
RecoveryFilterMap filtersByArchive,
AbstractCopyPolicy policy,
File referenceTrace,
short mode,
ProcessContext context
) throws IOException, ApplicationException, TaskCancelledException {
// Simply recover the files
medium.ensureLocalCopy(
archivesToRecover,
true,
context.getRecoveryDestination(),
filtersByArchive,
policy,
context
);
}
public void archiveDeleted(File archive)
throws IOException {
}
public void close(ProcessContext context)
throws IOException {
}
public void init(ProcessContext context, TransactionPoint transactionPoint)
throws IOException {
}
public void initializeSimulationDriverData(FileSystemDriver initialDriver, ProcessContext context) throws IOException, DriverAlreadySetException {
}
public Duplicable duplicate() {
return new DefaultArchiveHandler();
}
public EntriesDispatcher buildEntriesDispatcher(File[] archives) {
return new DefaultEntriesDispatcher(archives, medium);
}
public boolean supportsImageBackup() {
return true;
}
public File getContentFile(File archive) {
return null;
}
public boolean autonomousArchives() {
return true;
}
}
| gpl-2.0 |
openkm/document-management-system | src/main/java/com/openkm/automation/action/AddCategory.java | 2676 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.automation.action;
import java.util.Map;
import com.openkm.automation.Action;
import com.openkm.automation.AutomationUtils;
import com.openkm.dao.NodeBaseDAO;
import com.openkm.dao.bean.Automation;
import net.xeoh.plugins.base.annotations.PluginImplementation;
/**
* AddCategory
*
* @author jllort
*/
@PluginImplementation
public class AddCategory implements Action {
@Override
public void executePre(Map<String, Object> env, Object... params) throws Exception {
}
@Override
public void executePost(Map<String, Object> env, Object... params) throws Exception {
String catUuid = AutomationUtils.getString(0, params);
String uuid = AutomationUtils.getUuid(env);
if (uuid != null && catUuid != null && !catUuid.isEmpty()) {
NodeBaseDAO.getInstance().addCategory(uuid, catUuid);
}
}
@Override
public boolean hasPost() {
return true;
}
@Override
public boolean hasPre() {
return false;
}
@Override
public String getName() {
return "AddCategory";
}
@Override
public String getParamType00() {
return Automation.PARAM_TYPE_TEXT;
}
@Override
public String getParamSrc00() {
return Automation.PARAM_SOURCE_FOLDER;
}
@Override
public String getParamDesc00() {
return "Category";
}
@Override
public String getParamType01() {
return Automation.PARAM_TYPE_EMPTY;
}
@Override
public String getParamSrc01() {
return Automation.PARAM_SOURCE_EMPTY;
}
@Override
public String getParamDesc01() {
return "";
}
@Override
public String getParamType02() {
return Automation.PARAM_TYPE_EMPTY;
}
@Override
public String getParamSrc02() {
return Automation.PARAM_SOURCE_EMPTY;
}
@Override
public String getParamDesc02() {
return "";
}
} | gpl-2.0 |
ChaosPaladin/TERA_atlascore | java/game/tera/gameserver/network/clientpackets/RequestInventoryInfoItem.java | 4245 | package tera.gameserver.network.clientpackets;
import tera.gameserver.model.Guild;
import tera.gameserver.model.World;
import tera.gameserver.model.equipment.Equipment;
import tera.gameserver.model.equipment.Slot;
import tera.gameserver.model.inventory.Bank;
import tera.gameserver.model.inventory.Cell;
import tera.gameserver.model.inventory.Inventory;
import tera.gameserver.model.items.ItemInstance;
import tera.gameserver.model.playable.Player;
import tera.gameserver.network.serverpackets.InventoryItemInfo;
/**
* Клиенсткий пакет для запроса информации о итеме.
*
* @author Ronn
*/
public class RequestInventoryInfoItem extends ClientPacket
{
/** ид итема */
private int objectId;
/** имя игрока */
private String name;
/** игрок */
private Player player;
@Override
public void finalyze()
{
name = null;
player = null;
}
@Override
public boolean isSynchronized()
{
return false;
}
@Override
public void readImpl()
{
player = owner.getOwner();
readInt();
readShort();
objectId = readInt(); //обжект ид итема для которого узнаём инфу
readLong();
readLong();
readInt();
readShort();
readShort();
name = readString();
}
@Override
public void runImpl()
{
if(player == null || name == null)
return;
// целевой игрок
Player target = null;
// если нужный игрок и есть игрок, который запрашивает
if(name.equals(player.getName()))
target = player;
else
{
// иначе ищим по окружающим
target = World.getAroundByName(Player.class, player, name);
// если не находим
if(target == null)
// пытаемся потянуть из мира
target = World.getPlayer(name);
}
// если не находим, выходим
if(target == null)
return;
// извлекаем экиперовку и инвентарь
Equipment equipment = target.getEquipment();
// если экиперовки нет, выходим
if(equipment == null)
return;
equipment.lock();
try
{
// пытаемся получить слот из экиперовки с этим итемом
Slot slot = equipment.getSlotForObjectId(objectId);
// если такой слот нашелся
if(slot != null)
{
// отправляем пакет и выходимм
player.sendPacket(InventoryItemInfo.getInstance(slot.getIndex(), slot.getItem()), true);
return;
}
}
finally
{
equipment.unlock();
}
Inventory inventory = target.getInventory();
// если инвенторя нет, выходим
if(inventory == null)
return;
inventory.lock();
try
{
// пытаемся получить ячейку из изнвенторя
Cell cell = inventory.getCellForObjectId(objectId);
// если такой нашли
if(cell != null)
{
// отправляем пакет и выходим
player.sendPacket(InventoryItemInfo.getInstance(cell.getIndex(), cell.getItem()), true);
return;
}
}
finally
{
inventory.unlock();
}
Bank bank = target.getBank();
if(bank == null)
return;
bank.lock();
try
{
ItemInstance item = bank.getItemForObjectId(objectId);
if(item != null)
{
// отправляем пакет и выходим
player.sendPacket(InventoryItemInfo.getInstance(0, item), true);
return;
}
}
finally
{
bank.unlock();
}
// получаем гильдию игрока
Guild guild = player.getGuild();
// если гильдии нет, выходим
if(guild == null)
return;
// получаем банк гильдии
bank = guild.getBank();
bank.lock();
try
{
ItemInstance item = bank.getItemForObjectId(objectId);
if(item != null)
{
// отправляем пакет и выходим
player.sendPacket(InventoryItemInfo.getInstance(0, item), true);
return;
}
}
finally
{
bank.unlock();
}
}
} | gpl-2.0 |
lucaswerkmeister/ceylon-compiler | test/src/com/redhat/ceylon/compiler/java/test/metamodel/JavaType.java | 7269 | /*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.metamodel;
class C0 {}
class C1 extends C0 {
public C1() {
super();
}
}
public class JavaType {
public boolean booleanField = true;
public byte byteField = 1;
public short shortField = 2;
public int intField = 3;
public long longField = 4;
public float floatField = 1.0f;
public double doubleField = 2.0;
public char charField = 'a';
public String stringField = "a";
public Object objectField = ceylon.language.String.instance("b");
public JavaType(boolean bo, byte by, short s, int i, long l, float f, double d, char c, String str, Object o){
assertt(bo == true);
assertt(by == 1);
assertt(s == 2);
assertt(i == 3);
assertt(l == 4);
assertt(f == 1.0);
assertt(d == 2.0);
assertt(c == 'a');
assertt(str.equals("a"));
assertt(o instanceof ceylon.language.String && o.toString().equals("b"));
}
public void method(boolean bo, byte by, short s, int i, long l, float f, double d, char c, String str, Object o){
assertt(bo == true);
assertt(by == 1);
assertt(s == 2);
assertt(i == 3);
assertt(l == 4);
assertt(f == 1.0);
assertt(d == 2.0);
assertt(c == 'a');
assertt(str.equals("a"));
assertt(o instanceof ceylon.language.String && o.toString().equals("b"));
}
public boolean methodBoolean() { return true; }
public byte methodByte() { return 1; }
public short methodShort() { return 2; }
public int methodInt() { return 3; }
public long methodLong() { return 4; }
public float methodFloat() { return (float) 1.0; }
public double methodDouble() { return 2.0; }
public char methodChar() { return 'a'; }
public String methodStr() { return "a"; }
public Object methodObject() { return ceylon.language.String.instance("b"); }
public void methodBooleanVarargs(long count, boolean b0, boolean... b){
assertt(b0 == true);
assertt(b != null && b.length == count);
for(boolean bb : b){
assertt(bb == true);
}
}
public void methodByteVarargs(byte b0, byte... b){
assertt(b0 == 1);
assertt(b != null && b.length == 1 && b[0] == 1);
}
public void methodShortVarargs(short b0, short... b){
assertt(b0 == 2);
assertt(b != null && b.length == 1 && b[0] == 2);
}
public void methodIntVarargs(int b0, int... b){
assertt(b0 == 3);
assertt(b != null && b.length == 1 && b[0] == 3);
}
public void methodLongVarargs(long b0, long... b){
assertt(b0 == 4);
assertt(b != null && b.length == 1 && b[0] == 4);
}
public void methodFloatVarargs(float b0, float... b){
assertt(b0 == 1.0);
assertt(b != null && b.length == 1 && b[0] == 1.0);
}
public void methodDoubleVarargs(double b0, double... b){
assertt(b0 == 2.0);
assertt(b != null && b.length == 1 && b[0] == 2.0);
}
public void methodCharVarargs(char b0, char... b){
assertt(b0 == 'a');
assertt(b != null && b.length == 1 && b[0] == 'a');
}
public void methodJavaStringVarargs(String b0, String... b){
assertt(b0.equals("a"));
assertt(b != null && b.length == 1 && b[0].equals("a"));
}
public void methodObjectVarargs(long count, Object b0, Object... b){
assertt(b0.equals(ceylon.language.String.instance("b")));
assertt(b != null && b.length == count);
for(Object bb : b){
assertt(bb.equals(ceylon.language.String.instance("b")));
}
}
public <T extends ceylon.language.Number> void methodBoundObjectVarargs(long count, T b0, T... b){
assertt(b0.equals(ceylon.language.Integer.instance(1)));
assertt(b != null && b.length == count);
for(T t : b){
assertt(t.equals(ceylon.language.Integer.instance(1)));
}
}
public boolean getBoolean(){ return true; }
public void setBoolean(boolean b){
assertt(b == true);
}
public byte getByte(){ return 1; }
public void setByte(byte b){
assertt(b == 1);
}
public short getShort(){ return 2; }
public void setShort(short b){
assertt(b == 2);
}
public int getInt(){ return 3; }
public void setInt(int b){
assertt(b == 3);
}
public long getLong(){ return 4; }
public void setLong(long b){
assertt(b == 4);
}
public float getFloat(){ return (float) 1.0; }
public void setFloat(float b){
assertt(b == 1.0);
}
public double getDouble(){ return 2.0; }
public void setDouble(double b){
assertt(b == 2.0);
}
public char getChar(){ return 'a'; }
public void setChar(char b){
assertt(b == 'a');
}
public String getStr(){ return "a"; }
public void setStr(String b){
assertt(b.equals("a"));
}
public Object getObject(){ return ceylon.language.String.instance("b"); }
public void setObject(Object b){
assertt(ceylon.language.String.instance("b").equals(b));
}
static void assertt(boolean test){
if(!test)
throw new AssertionError();
}
@Override
public String toString() {
return "JavaType is there";
}
public class Member{
public Member(boolean unboxed){
assertt(unboxed == true);
}
}
public class MemberVarargs{
public MemberVarargs(long count, boolean unboxed, boolean... b){
assertt(unboxed == true);
assertt(b != null && b.length == count);
for(boolean bb : b){
assertt(bb == true);
}
}
}
public static int staticField = 2;
private static int staticField2 = 2;
public static int getStaticGetter(){
return staticField2;
}
public static void setStaticGetter(int v){
staticField2 = v;
}
public static int staticMethod(int v){
return v;
}
public static class StaticClass{
public final int v;
public StaticClass(int v){
this.v = v;
}
}
}
| gpl-2.0 |
Lythimus/lptv | apache-solr-3.6.0/solr/core/src/java/org/apache/solr/request/UnInvertedField.java | 38667 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.request;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.SolrException;
import org.apache.solr.core.SolrCore;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.TrieField;
import org.apache.solr.search.*;
import org.apache.solr.util.BoundedTreeSet;
import org.apache.solr.handler.component.StatsValues;
import org.apache.solr.handler.component.StatsValuesFactory;
import org.apache.solr.handler.component.FieldFacetStats;
import org.apache.lucene.util.OpenBitSet;
import org.apache.solr.util.PrimUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* Final form of the un-inverted field:
* Each document points to a list of term numbers that are contained in that document.
*
* Term numbers are in sorted order, and are encoded as variable-length deltas from the
* previous term number. Real term numbers start at 2 since 0 and 1 are reserved. A
* term number of 0 signals the end of the termNumber list.
*
* There is a single int[maxDoc()] which either contains a pointer into a byte[] for
* the termNumber lists, or directly contains the termNumber list if it fits in the 4
* bytes of an integer. If the first byte in the integer is 1, the next 3 bytes
* are a pointer into a byte[] where the termNumber list starts.
*
* There are actually 256 byte arrays, to compensate for the fact that the pointers
* into the byte arrays are only 3 bytes long. The correct byte array for a document
* is a function of it's id.
*
* To save space and speed up faceting, any term that matches enough documents will
* not be un-inverted... it will be skipped while building the un-inverted field structure,
* and will use a set intersection method during faceting.
*
* To further save memory, the terms (the actual string values) are not all stored in
* memory, but a TermIndex is used to convert term numbers to term values only
* for the terms needed after faceting has completed. Only every 128th term value
* is stored, along with it's corresponding term number, and this is used as an
* index to find the closest term and iterate until the desired number is hit (very
* much like Lucene's own internal term index).
*
*/
public class UnInvertedField {
private static int TNUM_OFFSET=2;
static class TopTerm {
Term term;
int termNum;
long memSize() {
return 8 + // obj header
8 + 8 +(term.text().length()<<1) + //term
4; // int
}
}
String field;
int numTermsInField;
int termsInverted; // number of unique terms that were un-inverted
long termInstances; // total number of references to term numbers
final TermIndex ti;
long memsz;
int total_time; // total time to uninvert the field
int phase1_time; // time for phase1 of the uninvert process
final AtomicLong use = new AtomicLong(); // number of uses
int[] index;
byte[][] tnums = new byte[256][];
int[] maxTermCounts;
final Map<Integer,TopTerm> bigTerms = new LinkedHashMap<Integer,TopTerm>();
public long memSize() {
// can cache the mem size since it shouldn't change
if (memsz!=0) return memsz;
long sz = 8*8 + 32; // local fields
sz += bigTerms.size() * 64;
for (TopTerm tt : bigTerms.values()) {
sz += tt.memSize();
}
if (index != null) sz += index.length * 4;
if (tnums!=null) {
for (byte[] arr : tnums)
if (arr != null) sz += arr.length;
}
if (maxTermCounts != null)
sz += maxTermCounts.length * 4;
sz += ti.memSize();
memsz = sz;
return sz;
}
/** Number of bytes to represent an unsigned int as a vint. */
static int vIntSize(int x) {
if ((x & (0xffffffff << (7*1))) == 0 ) {
return 1;
}
if ((x & (0xffffffff << (7*2))) == 0 ) {
return 2;
}
if ((x & (0xffffffff << (7*3))) == 0 ) {
return 3;
}
if ((x & (0xffffffff << (7*4))) == 0 ) {
return 4;
}
return 5;
}
// todo: if we know the size of the vInt already, we could do
// a single switch on the size
static int writeInt(int x, byte[] arr, int pos) {
int a;
a = (x >>> (7*4));
if (a != 0) {
arr[pos++] = (byte)(a | 0x80);
}
a = (x >>> (7*3));
if (a != 0) {
arr[pos++] = (byte)(a | 0x80);
}
a = (x >>> (7*2));
if (a != 0) {
arr[pos++] = (byte)(a | 0x80);
}
a = (x >>> (7*1));
if (a != 0) {
arr[pos++] = (byte)(a | 0x80);
}
arr[pos++] = (byte)(x & 0x7f);
return pos;
}
public UnInvertedField(String field, SolrIndexSearcher searcher) throws IOException {
this.field = field;
this.ti = new TermIndex(field,
TrieField.getMainValuePrefix(searcher.getSchema().getFieldType(field)));
uninvert(searcher);
}
private void uninvert(SolrIndexSearcher searcher) throws IOException {
long startTime = System.currentTimeMillis();
IndexReader reader = searcher.getReader();
int maxDoc = reader.maxDoc();
int[] index = new int[maxDoc]; // immediate term numbers, or the index into the byte[] representing the last number
this.index = index;
final int[] lastTerm = new int[maxDoc]; // last term we saw for this document
final byte[][] bytes = new byte[maxDoc][]; // list of term numbers for the doc (delta encoded vInts)
maxTermCounts = new int[1024];
NumberedTermEnum te = ti.getEnumerator(reader);
SolrIndexSearcher.TermDocsState tdState = new SolrIndexSearcher.TermDocsState();
tdState.tenum = te.tenum;
tdState.tdocs = te.termDocs;
// threshold, over which we use set intersections instead of counting
// to (1) save memory, and (2) speed up faceting.
// Add 2 for testing purposes so that there will always be some terms under
// the threshold even when the index is very small.
int threshold = maxDoc / 20 + 2;
// threshold = 2000000000; //////////////////////////////// USE FOR TESTING
int[] docs = new int[1000];
int[] freqs = new int[1000];
// we need a minimum of 9 bytes, but round up to 12 since the space would
// be wasted with most allocators anyway.
byte[] tempArr = new byte[12];
//
// enumerate all terms, and build an intermediate form of the un-inverted field.
//
// During this intermediate form, every document has a (potential) byte[]
// and the int[maxDoc()] array either contains the termNumber list directly
// or the *end* offset of the termNumber list in it's byte array (for faster
// appending and faster creation of the final form).
//
// idea... if things are too large while building, we could do a range of docs
// at a time (but it would be a fair amount slower to build)
// could also do ranges in parallel to take advantage of multiple CPUs
// OPTIONAL: remap the largest df terms to the lowest 128 (single byte)
// values. This requires going over the field first to find the most
// frequent terms ahead of time.
for (;;) {
Term t = te.term();
if (t==null) break;
int termNum = te.getTermNumber();
if (termNum >= maxTermCounts.length) {
// resize by doubling - for very large number of unique terms, expanding
// by 4K and resultant GC will dominate uninvert times. Resize at end if material
int[] newMaxTermCounts = new int[maxTermCounts.length*2];
System.arraycopy(maxTermCounts, 0, newMaxTermCounts, 0, termNum);
maxTermCounts = newMaxTermCounts;
}
int df = te.docFreq();
if (df >= threshold) {
TopTerm topTerm = new TopTerm();
topTerm.term = t;
topTerm.termNum = termNum;
bigTerms.put(topTerm.termNum, topTerm);
DocSet set = searcher.getPositiveDocSet(new TermQuery(topTerm.term), tdState);
maxTermCounts[termNum] = set.size();
te.next();
continue;
}
termsInverted++;
TermDocs td = te.getTermDocs();
td.seek(te);
for(;;) {
int n = td.read(docs,freqs);
if (n <= 0) break;
maxTermCounts[termNum] += n;
for (int i=0; i<n; i++) {
termInstances++;
int doc = docs[i];
// add 2 to the term number to make room for special reserved values:
// 0 (end term) and 1 (index into byte array follows)
int delta = termNum - lastTerm[doc] + TNUM_OFFSET;
lastTerm[doc] = termNum;
int val = index[doc];
if ((val & 0xff)==1) {
// index into byte array (actually the end of
// the doc-specific byte[] when building)
int pos = val >>> 8;
int ilen = vIntSize(delta);
byte[] arr = bytes[doc];
int newend = pos+ilen;
if (newend > arr.length) {
// We avoid a doubling strategy to lower memory usage.
// this faceting method isn't for docs with many terms.
// In hotspot, objects have 2 words of overhead, then fields, rounded up to a 64-bit boundary.
// TODO: figure out what array lengths we can round up to w/o actually using more memory
// (how much space does a byte[] take up? Is data preceded by a 32 bit length only?
// It should be safe to round up to the nearest 32 bits in any case.
int newLen = (newend + 3) & 0xfffffffc; // 4 byte alignment
byte[] newarr = new byte[newLen];
System.arraycopy(arr, 0, newarr, 0, pos);
arr = newarr;
bytes[doc] = newarr;
}
pos = writeInt(delta, arr, pos);
index[doc] = (pos<<8) | 1; // update pointer to end index in byte[]
} else {
// OK, this int has data in it... find the end (a zero starting byte - not
// part of another number, hence not following a byte with the high bit set).
int ipos;
if (val==0) {
ipos=0;
} else if ((val & 0x0000ff80)==0) {
ipos=1;
} else if ((val & 0x00ff8000)==0) {
ipos=2;
} else if ((val & 0xff800000)==0) {
ipos=3;
} else {
ipos=4;
}
int endPos = writeInt(delta, tempArr, ipos);
if (endPos <= 4) {
// value will fit in the integer... move bytes back
for (int j=ipos; j<endPos; j++) {
val |= (tempArr[j] & 0xff) << (j<<3);
}
index[doc] = val;
} else {
// value won't fit... move integer into byte[]
for (int j=0; j<ipos; j++) {
tempArr[j] = (byte)val;
val >>>=8;
}
// point at the end index in the byte[]
index[doc] = (endPos<<8) | 1;
bytes[doc] = tempArr;
tempArr = new byte[12];
}
}
}
}
te.next();
}
numTermsInField = te.getTermNumber();
te.close();
// free space if outrageously wasteful (tradeoff memory/cpu)
if ((maxTermCounts.length - numTermsInField) > 1024) { // too much waste!
int[] newMaxTermCounts = new int[numTermsInField];
System.arraycopy(maxTermCounts, 0, newMaxTermCounts, 0, numTermsInField);
maxTermCounts = newMaxTermCounts;
}
long midPoint = System.currentTimeMillis();
if (termInstances == 0) {
// we didn't invert anything
// lower memory consumption.
index = this.index = null;
tnums = null;
} else {
//
// transform intermediate form into the final form, building a single byte[]
// at a time, and releasing the intermediate byte[]s as we go to avoid
// increasing the memory footprint.
//
for (int pass = 0; pass<256; pass++) {
byte[] target = tnums[pass];
int pos=0; // end in target;
if (target != null) {
pos = target.length;
} else {
target = new byte[4096];
}
// loop over documents, 0x00ppxxxx, 0x01ppxxxx, 0x02ppxxxx
// where pp is the pass (which array we are building), and xx is all values.
// each pass shares the same byte[] for termNumber lists.
for (int docbase = pass<<16; docbase<maxDoc; docbase+=(1<<24)) {
int lim = Math.min(docbase + (1<<16), maxDoc);
for (int doc=docbase; doc<lim; doc++) {
int val = index[doc];
if ((val&0xff) == 1) {
int len = val >>> 8;
index[doc] = (pos<<8)|1; // change index to point to start of array
if ((pos & 0xff000000) != 0) {
// we only have 24 bits for the array index
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Too many values for UnInvertedField faceting on field "+field);
}
byte[] arr = bytes[doc];
bytes[doc] = null; // IMPORTANT: allow GC to avoid OOM
if (target.length <= pos + len) {
int newlen = target.length;
/*** we don't have to worry about the array getting too large
* since the "pos" param will overflow first (only 24 bits available)
if ((newlen<<1) <= 0) {
// overflow...
newlen = Integer.MAX_VALUE;
if (newlen <= pos + len) {
throw new SolrException(400,"Too many terms to uninvert field!");
}
} else {
while (newlen <= pos + len) newlen<<=1; // doubling strategy
}
****/
while (newlen <= pos + len) newlen<<=1; // doubling strategy
byte[] newtarget = new byte[newlen];
System.arraycopy(target, 0, newtarget, 0, pos);
target = newtarget;
}
System.arraycopy(arr, 0, target, pos, len);
pos += len + 1; // skip single byte at end and leave it 0 for terminator
}
}
}
// shrink array
if (pos < target.length) {
byte[] newtarget = new byte[pos];
System.arraycopy(target, 0, newtarget, 0, pos);
target = newtarget;
if (target.length > (1<<24)*.9) {
SolrCore.log.warn("Approaching too many values for UnInvertedField faceting on field '"+field+"' : bucket size=" + target.length);
}
}
tnums[pass] = target;
if ((pass << 16) > maxDoc)
break;
}
}
long endTime = System.currentTimeMillis();
total_time = (int)(endTime-startTime);
phase1_time = (int)(midPoint-startTime);
SolrCore.log.info("UnInverted multi-valued field " + toString());
}
public NamedList getCounts(SolrIndexSearcher searcher, DocSet baseDocs, int offset, int limit, Integer mincount, boolean missing, String sort, String prefix) throws IOException {
use.incrementAndGet();
FieldType ft = searcher.getSchema().getFieldType(field);
NamedList res = new NamedList(); // order is important
DocSet docs = baseDocs;
int baseSize = docs.size();
int maxDoc = searcher.maxDoc();
if (baseSize >= mincount) {
final int[] index = this.index;
final int[] counts = new int[numTermsInField];
//
// If there is prefix, find it's start and end term numbers
//
int startTerm = 0;
int endTerm = numTermsInField; // one past the end
NumberedTermEnum te = ti.getEnumerator(searcher.getReader());
if (prefix != null && prefix.length() > 0) {
te.skipTo(prefix);
startTerm = te.getTermNumber();
te.skipTo(prefix + "\uffff\uffff\uffff\uffff");
endTerm = te.getTermNumber();
}
/***********
// Alternative 2: get the docSet of the prefix (could take a while) and
// then do the intersection with the baseDocSet first.
if (prefix != null && prefix.length() > 0) {
docs = searcher.getDocSet(new ConstantScorePrefixQuery(new Term(field, ft.toInternal(prefix))), docs);
// The issue with this method are problems of returning 0 counts for terms w/o
// the prefix. We can't just filter out those terms later because it may
// mean that we didn't collect enough terms in the queue (in the sorted case).
}
***********/
boolean doNegative = baseSize > maxDoc >> 1 && termInstances > 0
&& startTerm==0 && endTerm==numTermsInField
&& docs instanceof BitDocSet;
if (doNegative) {
OpenBitSet bs = (OpenBitSet)((BitDocSet)docs).getBits().clone();
bs.flip(0, maxDoc);
// TODO: when iterator across negative elements is available, use that
// instead of creating a new bitset and inverting.
docs = new BitDocSet(bs, maxDoc - baseSize);
// simply negating will mean that we have deleted docs in the set.
// that should be OK, as their entries in our table should be empty.
}
// For the biggest terms, do straight set intersections
for (TopTerm tt : bigTerms.values()) {
// TODO: counts could be deferred if sorted==false
if (tt.termNum >= startTerm && tt.termNum < endTerm) {
counts[tt.termNum] = searcher.numDocs(new TermQuery(tt.term), docs);
}
}
// TODO: we could short-circuit counting altogether for sorted faceting
// where we already have enough terms from the bigTerms
// TODO: we could shrink the size of the collection array, and
// additionally break when the termNumber got above endTerm, but
// it would require two extra conditionals in the inner loop (although
// they would be predictable for the non-prefix case).
// Perhaps a different copy of the code would be warranted.
if (termInstances > 0) {
DocIterator iter = docs.iterator();
while (iter.hasNext()) {
int doc = iter.nextDoc();
int code = index[doc];
if ((code & 0xff)==1) {
int pos = code>>>8;
int whichArray = (doc >>> 16) & 0xff;
byte[] arr = tnums[whichArray];
int tnum = 0;
for(;;) {
int delta = 0;
for(;;) {
byte b = arr[pos++];
delta = (delta << 7) | (b & 0x7f);
if ((b & 0x80) == 0) break;
}
if (delta == 0) break;
tnum += delta - TNUM_OFFSET;
counts[tnum]++;
}
} else {
int tnum = 0;
int delta = 0;
for (;;) {
delta = (delta << 7) | (code & 0x7f);
if ((code & 0x80)==0) {
if (delta==0) break;
tnum += delta - TNUM_OFFSET;
counts[tnum]++;
delta = 0;
}
code >>>= 8;
}
}
}
}
int off=offset;
int lim=limit>=0 ? limit : Integer.MAX_VALUE;
if (sort.equals(FacetParams.FACET_SORT_COUNT) || sort.equals(FacetParams.FACET_SORT_COUNT_LEGACY)) {
int maxsize = limit>0 ? offset+limit : Integer.MAX_VALUE-1;
maxsize = Math.min(maxsize, numTermsInField);
final BoundedTreeSet<Long> queue = new BoundedTreeSet<Long>(maxsize);
int min=mincount-1; // the smallest value in the top 'N' values
for (int i=startTerm; i<endTerm; i++) {
int c = doNegative ? maxTermCounts[i] - counts[i] : counts[i];
if (c>min) {
// NOTE: we use c>min rather than c>=min as an optimization because we are going in
// index order, so we already know that the keys are ordered. This can be very
// important if a lot of the counts are repeated (like zero counts would be).
// minimize object creation and speed comparison by creating a long that
// encompasses both count and term number.
// Since smaller values are kept in the TreeSet, make higher counts smaller.
//
// for equal counts, lower term numbers
// should come first and hence be "greater"
//long pair = (((long)c)<<32) | (0x7fffffff-i) ; // use if priority queue
long pair = (((long)-c)<<32) | i;
queue.add(new Long(pair));
if (queue.size()>=maxsize) min=-(int)(queue.last().longValue() >>> 32);
}
}
final int[] tnums = new int[Math.min(Math.max(0, queue.size()-off), lim)];
final int[] indirect = counts; // reuse the counts array for the index into the tnums array
assert indirect.length >= tnums.length;
int tnumCount = 0;
for (Long p : queue) {
if (--off>=0) continue;
if (--lim<0) break;
int c = -(int)(p.longValue() >>> 32);
//int tnum = 0x7fffffff - (int)p.longValue(); // use if priority queue
int tnum = (int)p.longValue();
indirect[tnumCount] = tnumCount;
tnums[tnumCount++] = tnum;
// String label = ft.indexedToReadable(getTermText(te, tnum));
// add a null label for now... we'll fill it in later.
res.add(null, c);
}
// now sort the indexes by the term numbers
PrimUtils.sort(0, tnumCount, indirect, new PrimUtils.IntComparator() {
@Override
public int compare(int a, int b) {
return tnums[a] - tnums[b];
}
});
// convert the term numbers to term values and set as the label
for (int i=0; i<tnumCount; i++) {
int idx = indirect[i];
int tnum = tnums[idx];
String label = ft.indexedToReadable(getTermText(te, tnum));
res.setName(idx, label);
}
} else {
// add results in index order
int i=startTerm;
if (mincount<=0) {
// if mincount<=0, then we won't discard any terms and we know exactly
// where to start.
i=startTerm+off;
off=0;
}
for (; i<endTerm; i++) {
int c = doNegative ? maxTermCounts[i] - counts[i] : counts[i];
if (c<mincount || --off>=0) continue;
if (--lim<0) break;
String label = ft.indexedToReadable(getTermText(te, i));
res.add(label, c);
}
}
te.close();
}
if (missing) {
// TODO: a faster solution for this?
res.add(null, SimpleFacets.getFieldMissingCount(searcher, baseDocs, field));
}
return res;
}
/**
* Collect statistics about the UninvertedField. Code is very similar to {@link #getCounts(org.apache.solr.search.SolrIndexSearcher, org.apache.solr.search.DocSet, int, int, Integer, boolean, String, String)}
* It can be used to calculate stats on multivalued fields.
* <p/>
* This method is mainly used by the {@link org.apache.solr.handler.component.StatsComponent}.
*
* @param searcher The Searcher to use to gather the statistics
* @param baseDocs The {@link org.apache.solr.search.DocSet} to gather the stats on
* @param facet One or more fields to facet on.
* @return The {@link org.apache.solr.handler.component.StatsValues} collected
* @throws IOException
*/
public StatsValues getStats(SolrIndexSearcher searcher, DocSet baseDocs, String[] facet) throws IOException {
//this function is ripped off nearly wholesale from the getCounts function to use
//for multiValued fields within the StatsComponent. may be useful to find common
//functionality between the two and refactor code somewhat
use.incrementAndGet();
FieldType ft = searcher.getSchema().getFieldType(field);
StatsValues allstats = StatsValuesFactory.createStatsValues(ft);
DocSet docs = baseDocs;
int baseSize = docs.size();
int maxDoc = searcher.maxDoc();
if (baseSize <= 0) return allstats;
DocSet missing = docs.andNot( searcher.getDocSet(new TermRangeQuery(field, null, null, false, false)) );
int i = 0;
final FieldFacetStats[] finfo = new FieldFacetStats[facet.length];
//Initialize facetstats, if facets have been passed in
FieldCache.StringIndex si;
for (String f : facet) {
FieldType facet_ft = searcher.getSchema().getFieldType(f);
try {
si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), f);
}
catch (IOException e) {
throw new RuntimeException("failed to open field cache for: " + f, e);
}
finfo[i] = new FieldFacetStats(f, si, facet_ft, numTermsInField, ft);
i++;
}
final int[] index = this.index;
final int[] counts = new int[numTermsInField];//keep track of the number of times we see each word in the field for all the documents in the docset
NumberedTermEnum te = ti.getEnumerator(searcher.getReader());
boolean doNegative = false;
if (finfo.length == 0) {
//if we're collecting statistics with a facet field, can't do inverted counting
doNegative = baseSize > maxDoc >> 1 && termInstances > 0
&& docs instanceof BitDocSet;
}
if (doNegative) {
OpenBitSet bs = (OpenBitSet) ((BitDocSet) docs).getBits().clone();
bs.flip(0, maxDoc);
// TODO: when iterator across negative elements is available, use that
// instead of creating a new bitset and inverting.
docs = new BitDocSet(bs, maxDoc - baseSize);
// simply negating will mean that we have deleted docs in the set.
// that should be OK, as their entries in our table should be empty.
}
// For the biggest terms, do straight set intersections
for (TopTerm tt : bigTerms.values()) {
// TODO: counts could be deferred if sorted==false
if (tt.termNum >= 0 && tt.termNum < numTermsInField) {
if (finfo.length == 0) {
counts[tt.termNum] = searcher.numDocs(new TermQuery(tt.term), docs);
} else {
//COULD BE VERY SLOW
//if we're collecting stats for facet fields, we need to iterate on all matching documents
DocSet bigTermDocSet = searcher.getDocSet(new TermQuery(tt.term)).intersection(docs);
DocIterator iter = bigTermDocSet.iterator();
while (iter.hasNext()) {
int doc = iter.nextDoc();
counts[tt.termNum]++;
for (FieldFacetStats f : finfo) {
f.facetTermNum(doc, tt.termNum);
}
}
}
}
}
if (termInstances > 0) {
DocIterator iter = docs.iterator();
while (iter.hasNext()) {
int doc = iter.nextDoc();
int code = index[doc];
if ((code & 0xff) == 1) {
int pos = code >>> 8;
int whichArray = (doc >>> 16) & 0xff;
byte[] arr = tnums[whichArray];
int tnum = 0;
for (; ;) {
int delta = 0;
for (; ;) {
byte b = arr[pos++];
delta = (delta << 7) | (b & 0x7f);
if ((b & 0x80) == 0) break;
}
if (delta == 0) break;
tnum += delta - TNUM_OFFSET;
counts[tnum]++;
for (FieldFacetStats f : finfo) {
f.facetTermNum(doc, tnum);
}
}
} else {
int tnum = 0;
int delta = 0;
for (; ;) {
delta = (delta << 7) | (code & 0x7f);
if ((code & 0x80) == 0) {
if (delta == 0) break;
tnum += delta - TNUM_OFFSET;
counts[tnum]++;
for (FieldFacetStats f : finfo) {
f.facetTermNum(doc, tnum);
}
delta = 0;
}
code >>>= 8;
}
}
}
}
// add results in index order
for (i = 0; i < numTermsInField; i++) {
int c = doNegative ? maxTermCounts[i] - counts[i] : counts[i];
if (c == 0) continue;
String value = ft.indexedToReadable(getTermText(te, i));
allstats.accumulate(value, c);
//as we've parsed the termnum into a value, lets also accumulate fieldfacet statistics
for (FieldFacetStats f : finfo) {
f.accumulateTermNum(i, value);
}
}
te.close();
int c = missing.size();
allstats.addMissing(c);
if (finfo.length > 0) {
for (FieldFacetStats f : finfo) {
Map<String, StatsValues> facetStatsValues = f.facetStatsValues;
FieldType facetType = searcher.getSchema().getFieldType(f.name);
for (Map.Entry<String,StatsValues> entry : facetStatsValues.entrySet()) {
String termLabel = entry.getKey();
int missingCount = searcher.numDocs(new TermQuery(new Term(f.name, facetType.toInternal(termLabel))), missing);
entry.getValue().addMissing(missingCount);
}
allstats.addFacet(f.name, facetStatsValues);
}
}
return allstats;
}
String getTermText(NumberedTermEnum te, int termNum) throws IOException {
if (bigTerms.size() > 0) {
// see if the term is one of our big terms.
TopTerm tt = bigTerms.get(termNum);
if (tt != null) {
return tt.term.text();
}
}
te.skipTo(termNum);
return te.term().text();
}
@Override
public String toString() {
return "{field=" + field
+ ",memSize="+memSize()
+ ",tindexSize="+ti.memSize()
+ ",time="+total_time
+ ",phase1="+phase1_time
+ ",nTerms="+numTermsInField
+ ",bigTerms="+bigTerms.size()
+ ",termInstances="+termInstances
+ ",uses="+use.get()
+ "}";
}
//////////////////////////////////////////////////////////////////
//////////////////////////// caching /////////////////////////////
//////////////////////////////////////////////////////////////////
public static UnInvertedField getUnInvertedField(String field, SolrIndexSearcher searcher) throws IOException {
SolrCache cache = searcher.getFieldValueCache();
if (cache == null) {
return new UnInvertedField(field, searcher);
}
UnInvertedField uif = (UnInvertedField)cache.get(field);
if (uif == null) {
synchronized (cache) {
uif = (UnInvertedField)cache.get(field);
if (uif == null) {
uif = new UnInvertedField(field, searcher);
cache.put(field, uif);
}
}
}
return uif;
}
}
// How to share TermDocs (int[] score[])???
// Hot to share TermPositions?
/***
class TermEnumListener {
void doTerm(Term t) {
}
void done() {
}
}
***/
class NumberedTermEnum extends TermEnum {
protected final IndexReader reader;
protected final TermIndex tindex;
protected TermEnum tenum;
protected int pos=-1;
protected Term t;
protected TermDocs termDocs;
NumberedTermEnum(IndexReader reader, TermIndex tindex) throws IOException {
this.reader = reader;
this.tindex = tindex;
}
NumberedTermEnum(IndexReader reader, TermIndex tindex, String termValue, int pos) throws IOException {
this.reader = reader;
this.tindex = tindex;
this.pos = pos;
tenum = reader.terms(tindex.createTerm(termValue));
setTerm();
}
public TermDocs getTermDocs() throws IOException {
if (termDocs==null) termDocs = reader.termDocs(t);
else termDocs.seek(t);
return termDocs;
}
protected boolean setTerm() {
t = tenum.term();
if (t==null
|| t.field() != tindex.fterm.field() // intern'd compare
|| (tindex.prefix != null && !t.text().startsWith(tindex.prefix,0)) )
{
t = null;
return false;
}
return true;
}
@Override
public boolean next() throws IOException {
pos++;
boolean b = tenum.next();
if (!b) {
t = null;
return false;
}
return setTerm(); // this is extra work if we know we are in bounds...
}
@Override
public Term term() {
return t;
}
@Override
public int docFreq() {
return tenum.docFreq();
}
@Override
public void close() throws IOException {
if (tenum!=null) tenum.close();
}
public boolean skipTo(String target) throws IOException {
return skipTo(tindex.fterm.createTerm(target));
}
public boolean skipTo(Term target) throws IOException {
// already here
if (t != null && t.equals(target)) return true;
int startIdx = Arrays.binarySearch(tindex.index,target.text());
if (startIdx >= 0) {
// we hit the term exactly... lucky us!
if (tenum != null) tenum.close();
tenum = reader.terms(target);
pos = startIdx << TermIndex.intervalBits;
return setTerm();
}
// we didn't hit the term exactly
startIdx=-startIdx-1;
if (startIdx == 0) {
// our target occurs *before* the first term
if (tenum != null) tenum.close();
tenum = reader.terms(target);
pos = 0;
return setTerm();
}
// back up to the start of the block
startIdx--;
if ((pos >> TermIndex.intervalBits) == startIdx && t != null && t.text().compareTo(target.text())<=0) {
// we are already in the right block and the current term is before the term we want,
// so we don't need to seek.
} else {
// seek to the right block
if (tenum != null) tenum.close();
tenum = reader.terms(target.createTerm(tindex.index[startIdx]));
pos = startIdx << TermIndex.intervalBits;
setTerm(); // should be true since it's in the index
}
while (t != null && t.text().compareTo(target.text()) < 0) {
next();
}
return t != null;
}
public boolean skipTo(int termNumber) throws IOException {
int delta = termNumber - pos;
if (delta < 0 || delta > TermIndex.interval || tenum==null) {
int idx = termNumber >>> TermIndex.intervalBits;
String base = tindex.index[idx];
pos = idx << TermIndex.intervalBits;
delta = termNumber - pos;
if (tenum != null) tenum.close();
tenum = reader.terms(tindex.createTerm(base));
}
while (--delta >= 0) {
boolean b = tenum.next();
if (b==false) {
t = null;
return false;
}
++pos;
}
return setTerm();
}
/** The current term number, starting at 0.
* Only valid if the previous call to next() or skipTo() returned true.
*/
public int getTermNumber() {
return pos;
}
}
/**
* Class to save memory by only storing every nth term (for random access), while
* numbering the terms, allowing them to be retrieved later by number.
* This is only valid when used with the IndexReader it was created with.
* The IndexReader is not actually stored to facilitate caching by using it as a key in
* a weak hash map.
*/
class TermIndex {
final static int intervalBits = 7; // decrease to a low number like 2 for testing
final static int intervalMask = 0xffffffff >>> (32-intervalBits);
final static int interval = 1 << intervalBits;
final Term fterm; // prototype to be used in term construction w/o String.intern overhead
final String prefix;
String[] index;
int nTerms;
long sizeOfStrings;
TermIndex(String field) {
this(field, null);
}
TermIndex(String field, String prefix) {
this.fterm = new Term(field, "");
this.prefix = prefix;
}
Term createTerm(String termVal) {
return fterm.createTerm(termVal);
}
NumberedTermEnum getEnumerator(IndexReader reader, int termNumber) throws IOException {
NumberedTermEnum te = new NumberedTermEnum(reader, this);
te.skipTo(termNumber);
return te;
}
/* The first time an enumerator is requested, it should be used
with next() to fully traverse all of the terms so the index
will be built.
*/
NumberedTermEnum getEnumerator(IndexReader reader) throws IOException {
if (index==null) return new NumberedTermEnum(reader,this, prefix==null?"":prefix, 0) {
ArrayList<String> lst;
@Override
protected boolean setTerm() {
boolean b = super.setTerm();
if (b && (pos & intervalMask)==0) {
String text = term().text();
sizeOfStrings += text.length() << 1;
if (lst==null) {
lst = new ArrayList<String>();
}
lst.add(text);
}
return b;
}
@Override
public boolean skipTo(Term target) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public boolean skipTo(int termNumber) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
nTerms=pos;
super.close();
index = lst!=null ? lst.toArray(new String[lst.size()]) : new String[0];
}
};
else return new NumberedTermEnum(reader,this,"",0);
}
/**
* Returns the approximate amount of memory taken by this TermIndex.
* This is only an approximation and doesn't take into account java object overhead.
*
* @return
* the approximate memory consumption in bytes
*/
public long memSize() {
// assume 8 byte references?
return 8+8+8+8+(index.length<<3)+sizeOfStrings;
}
}
| gpl-2.0 |
antoinebourget/INF5000-StaticProxy | src/share/classes/test/tools/proxies/RedefTest/Main.java | 716 | /*
* @test
* @summary redef
* @author Alexandre Terrasa
*
* @compile RealSubject/RunnableRealSubject.java Main.java
*/
package test.tools.proxies.RedefTest;
import java.io.Serializable;
import test.tools.proxies.RedefTest.RealSubject.RunnableRealSubject;
public class Main extends proxy<java.lang.Runnable> implements java.lang.Runnable {
public static void main(String[] args) {
Main prxy = new Main(new RunnableRealSubject("RedefTest"));
prxy.run();
prxy.addedMethod();
}
public Main(Runnable realSubject) {
super(realSubject);
}
public void run() {
super.run();
System.out.println("-> This is a redef <-");
}
public void addedMethod() {
System.out.println("added");
}
}
| gpl-2.0 |
alpapad/HotswapAgent | hotswap-agent-core/src/test/java/org/hotswap/agent/annotation/handler/OnClassLoadEventHandlerTest.java | 2240 | package org.hotswap.agent.annotation.handler;
import org.hotswap.agent.annotation.OnClassLoadEvent;
import org.hotswap.agent.config.PluginManager;
import org.hotswap.agent.config.PluginRegistry;
import org.hotswap.agent.testData.SimplePlugin;
import org.hotswap.agent.util.HotswapTransformer;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import java.lang.instrument.ClassFileTransformer;
import java.lang.reflect.Method;
import static org.junit.Assert.assertTrue;
/**
* @author Jiri Bubnik
*/
public class OnClassLoadEventHandlerTest {
Mockery context = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
PluginManager pluginManager = context.mock(PluginManager.class);
PluginRegistry pluginRegistry = context.mock(PluginRegistry.class);
HotswapTransformer hotswapTransformer = context.mock(HotswapTransformer.class);
@Test
public void testInitMethod() throws Exception {
final ClassLoader appClassLoader = getClass().getClassLoader();
context.checking(new Expectations() {{
allowing(pluginManager).getHotswapTransformer(); will(returnValue(hotswapTransformer));
allowing(pluginManager).getPluginRegistry(); will(returnValue(pluginRegistry));
allowing(pluginRegistry).getAppClassLoader(with(any(Object.class))); will(returnValue(appClassLoader));
oneOf(hotswapTransformer).registerTransformer(with(appClassLoader),
with("org.hotswap.example.type"), with(any(ClassFileTransformer.class)));
}});
OnClassLoadedHandler onClassLoadedHandler = new OnClassLoadedHandler(pluginManager);
SimplePlugin simplePlugin = new SimplePlugin();
Method method = SimplePlugin.class.getMethod("transform");
PluginAnnotation<OnClassLoadEvent> pluginAnnotation = new PluginAnnotation<OnClassLoadEvent>(SimplePlugin.class,
simplePlugin, method.getAnnotation(OnClassLoadEvent.class), method);
assertTrue("Init successful",
onClassLoadedHandler.initMethod(pluginAnnotation));
}
@Test
public void testTransform() throws Exception {
}
}
| gpl-2.0 |
lesavoie/nagiosservice | cassandra-client/CassandraClient.java | 2307 | import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class CassandraClient {
private Cluster cluster;
private Session session;
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack());
}
session = cluster.connect();
}
public String queryServerIp(String openid) {
ResultSet results = session.execute(
"SELECT * " +
"FROM nagioscontrol.monitor_servers " +
"WHERE openid = '" + openid +
"';");
Row result = results.one();
if (result.isNull(1)) {
return "";
}
else {
return result.getString(1);
}
}
public String queryUserToken(String openid) {
ResultSet results = session.execute(
"SELECT * " +
"FROM nagioscontrol.users " +
"WHERE openid = '" + openid +
"';");
Row result = results.one();
if (result.isNull(1)) {
return "";
}
else {
return result.getString(1);
}
}
public boolean insertUser(String openid, String openid_token) {
session.execute("INSERT INTO nagioscontrol.users " +
"(openid, openid_token)" +
"VALUES (" + openid + ", " + openid_token + ");");
return true;
}
public boolean insertMonitorServer(String openid, String ip_addr) {
// TODO check if user exists?
session.execute("INSERT INTO nagioscontrol.monitor_servers " +
"(openid, ip_addr) " +
"VALUES ('" + openid + "', '" + ip_addr + "');");
return true;
}
public void close() {
cluster.close();;
}
public static void main(String[] args) {
CassandraClient client = new CassandraClient();
client.connect("127.0.0.1");
//client.insertUser("admin", "1234567889");
client.insertMonitorServer("admin", "127.0.0.1");
System.out.println(client.queryUserToken("admin"));
System.out.println(client.queryServerIp("admin"));
client.close();
}
}
| gpl-2.0 |
we6jbo/FSL-CloudFileScanner | src/main/java/data/Data.java | 1827 | /*
* Copyright (C) 2014 Jeremiah ONeal <joneal@nuaitp.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package data;
/**
*
* @author Jeremiah ONeal <joneal@nuaitp.net>
*/
public class Data {
public static String name = "";
public static String[] compareLocal = new String[10];
public static int fileLines = 10;
public static String connectionport = "2481";
public Data(String platform)
{
for (int i = 0; i <= (data.Data.compareLocal.length - 1); i++)
{
compareLocal[i] = "";
}
}
public static int compareLocaltoRemote(String platform, int x, int y)
{
if (x<=0 || x >= data.Data.fileLines || y <= 0 || y >= data.Data.fileLines)
{
return 0;
}
try
{
if(compareLocal[x].equals(filemanager.Filemanager.fileArray[y]))
{
return 0;
}
}
catch(NullPointerException e)
{
say.Say.error("----", e.toString());
}
return 1;
}
public static void save()
{
filemanager.Filemanager.save();
}
}
| gpl-2.0 |
Romenig/iVProg_2 | src/usp/ime/line/ivprog/view/domaingui/workspace/codecomponents/BooleanOperationUI.java | 7868 | package usp.ime.line.ivprog.view.domaingui.workspace.codecomponents;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPopupMenu;
import usp.ime.line.ivprog.interpreter.execution.expressions.Expression;
import usp.ime.line.ivprog.interpreter.execution.expressions.Operation;
import usp.ime.line.ivprog.model.utils.Services;
import usp.ime.line.ivprog.view.utils.language.ResourceBundleIVP;
public class BooleanOperationUI extends OperationUI {
private JPopupMenu operationAndOrMenu;
private JPopupMenu operationComparisonMenu;
public BooleanOperationUI(String parent, String scope, String id) {
super(parent, scope, id);
}
public void initOperationSignMenu() {
operationComparisonMenu = new JPopupMenu();
operationAndOrMenu = new JPopupMenu();
Action changeToAND = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_AND, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToAND.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.AND.tip"));
changeToAND.putValue(Action.NAME, ResourceBundleIVP.getString("BooleanOperationUI.AND.text"));
Action changeToOR = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_OR, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToOR.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.OR.tip"));
changeToOR.putValue(Action.NAME, ResourceBundleIVP.getString("BooleanOperationUI.OR.text"));
Action changeToLEQ = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_LEQ, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToLEQ.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.LEQ.tip"));
changeToLEQ.putValue(Action.NAME, "\u2264");
Action changeToLES = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_LES, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToLES.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.LES.tip"));
changeToLES.putValue(Action.NAME, "\u003C");
Action changeToEQU = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_EQU, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToEQU.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.EQU.tip"));
changeToEQU.putValue(Action.NAME, "\u003D\u003D");
Action changeToNEQ = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_NEQ, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToNEQ.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.NEQ.tip"));
changeToNEQ.putValue(Action.NAME, "\u2260");
Action changeToGEQ = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_GEQ, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToGEQ.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.GEQ.tip"));
changeToGEQ.putValue(Action.NAME, "\u2265");
Action changeToGRE = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
Services.getService().getController().changeExpressionSign(currentModelID, Expression.OPERATION_GRE, context);
}
};
// setConstantAction.putValue(Action.SMALL_ICON, new
// ImageIcon(ExpressionBase.class.getResource("/usp/ime/line/resources/icons/varDelete2.png")));
changeToGRE.putValue(Action.SHORT_DESCRIPTION, ResourceBundleIVP.getString("BooleanOperationUI.GRE.tip"));
changeToGRE.putValue(Action.NAME, "\u003E");
operationComparisonMenu.add(changeToLEQ);
operationComparisonMenu.add(changeToLES);
operationComparisonMenu.add(changeToEQU);
operationComparisonMenu.add(changeToNEQ);
operationComparisonMenu.add(changeToGEQ);
operationComparisonMenu.add(changeToGRE);
operationAndOrMenu.add(changeToAND);
operationAndOrMenu.add(changeToOR);
operationSignMenu = operationComparisonMenu;
}
public void initSignal() {
String sign = "";
Operation op = (Operation) Services.getService().getModelMapping().get(currentModelID);
String type = op.getOperationType();
if (type.equals(Expression.OPERATION_AND)) {
sign = ResourceBundleIVP.getString("BooleanOperationUI.AND.text");
operationSignMenu = operationAndOrMenu;
enableComparison();
} else if (type.equals(Expression.OPERATION_OR)) {
sign = ResourceBundleIVP.getString("BooleanOperationUI.OR.text");
operationSignMenu = operationAndOrMenu;
enableComparison();
} else if (type.equals(Expression.OPERATION_LEQ)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u2264";
} else if (type.equals(Expression.OPERATION_LES)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u003C";
} else if (type.equals(Expression.OPERATION_EQU)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u003D\u003D";
} else if (type.equals(Expression.OPERATION_NEQ)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u2260";
} else if (type.equals(Expression.OPERATION_GEQ)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u2265";
} else if (type.equals(Expression.OPERATION_GRE)) {
disableComparison();
operationSignMenu = operationComparisonMenu;
sign = "\u003E";
}
expSign.setText(sign);
}
private void enableComparison() {
expressionBaseUI_1.enableComparison();
expressionBaseUI_2.enableComparison();
}
private void disableComparison() {
expressionBaseUI_1.disableComparison();
expressionBaseUI_2.disableComparison();
}
public void operationTypeChanged(String id, String context) {
if (currentModelID.equals(id) && this.context.equals(context)) {
setModelID(id);
}
}
public boolean isContentSet() {
boolean isCSet = true;
if (!expressionBaseUI_1.isCSet()) {
isCSet = false;
}
if (!expressionBaseUI_2.isCSet()) {
if (isCSet)
isCSet = false;
}
return isCSet;
}
public void lockDownCode() {
disableEdition();
}
}
| gpl-2.0 |
dpisarenko/pcc-scheduler | src/test/java/co/altruix/scheduler/model/MockInjectorAdapter.java | 2761 | /**
* This file is part of Project Control Center (PCC).
*
* PCC (Project Control Center) project is intellectual property of
* Dmitri Anatol'evich Pisarenko.
*
* Copyright 2010, 2011 Dmitri Anatol'evich Pisarenko
* All rights reserved
*
**/
package co.altruix.scheduler.model;
import java.util.List;
import java.util.Map;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.MembersInjector;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
/**
* @author DP118M
*
*/
public abstract class MockInjectorAdapter implements Injector {
@Override
public Injector createChildInjector(Iterable<? extends Module> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Injector createChildInjector(Module... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> List<Binding<T>> findBindingsByType(TypeLiteral<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Binding<T> getBinding(Key<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Binding<T> getBinding(Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<Key<?>, Binding<?>> getBindings() {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T getInstance(Key<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T getInstance(Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> MembersInjector<T> getMembersInjector(Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Injector getParent() {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Provider<T> getProvider(Key<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> Provider<T> getProvider(Class<T> arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void injectMembers(Object arg0) {
// TODO Auto-generated method stub
}
}
| gpl-2.0 |
dain/graal | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/UnaryNode.java | 1804 | /*
* Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.calc;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.nodes.*;
/**
* The {@code UnaryNode} class is the base of arithmetic and bit logic operations with exactly one
* input.
*/
public abstract class UnaryNode extends FloatingNode implements Canonicalizable.Unary<ValueNode> {
@Input private ValueNode value;
public ValueNode getValue() {
return value;
}
/**
* Creates a new UnaryNode instance.
*
* @param stamp the result type of this instruction
* @param value the input instruction
*/
public UnaryNode(Stamp stamp, ValueNode value) {
super(stamp);
this.value = value;
}
}
| gpl-2.0 |
BaudouinDrou/Stubi | src/game/ImageLoader.java | 596 | package game;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageLoader {
/**
* This class has been built in order to make easier the loading of images
*/
/**
* This method give a BufferedImage from a path to it
* @param path the path to the image (usually "img/XXX.png")
* @return a BufferedImage
* @throws IOException
*/
public BufferedImage load(String path) throws IOException {
BufferedImage img = ImageIO.read(getClass().getClassLoader().getResource(path));
return img;
}
}
| gpl-2.0 |
AcademicTorrents/AcademicTorrents-Downloader | frostwire-merge/org/minicastle/asn1/BERSequenceGenerator.java | 847 | package org.minicastle.asn1;
import java.io.IOException;
import java.io.OutputStream;
public class BERSequenceGenerator
extends BERGenerator
{
public BERSequenceGenerator(
OutputStream out)
throws IOException
{
super(out);
writeBERHeader(DERTags.CONSTRUCTED | DERTags.SEQUENCE);
}
public BERSequenceGenerator(
OutputStream out,
int tagNo,
boolean isExplicit)
throws IOException
{
super(out, tagNo, isExplicit);
writeBERHeader(DERTags.CONSTRUCTED | DERTags.SEQUENCE);
}
public void addObject(
DEREncodable object)
throws IOException
{
object.getDERObject().encode(new DEROutputStream(_out));
}
public void close()
throws IOException
{
writeBEREnd();
}
}
| gpl-2.0 |
krishna174/Java_C | AadharValidation-PFX/src/com/tin/aadhaar/uidai/authentication/uid_auth_request/_1/ObjectFactory.java | 3226 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.06 at 04:38:08 PM IST
//
package com.tin.aadhaar.uidai.authentication.uid_auth_request._1;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import com.tin.aadhaar.uidai.authentication.uid_auth_request._1.Auth;
import com.tin.aadhaar.uidai.authentication.uid_auth_request._1.Skey;
import com.tin.aadhaar.uidai.authentication.uid_auth_request._1.Tkn;
import com.tin.aadhaar.uidai.authentication.uid_auth_request._1.Uses;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the in.gov.uidai.authentication.uid_auth_request._1 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _Auth_QNAME = new QName("http://www.uidai.gov.in/authentication/uid-auth-request/2.0", "Auth");
// private final static QName _Auth_QNAME = new QName("http://www.uidai.gov.in/authentication/uid-auth-request/2.5", "Auth");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: in.gov.uidai.authentication.uid_auth_request._1
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Auth }
*
*/
public Auth createAuth() {
return new Auth();
}
/**
* Create an instance of {@link Tkn }
*
*/
public Tkn createTkn() {
return new Tkn();
}
/**
* Create an instance of {@link Auth.Data }
*
*/
public Auth.Data createAuthData() {
return new Auth.Data();
}
/**
* Create an instance of {@link Skey }
*
*/
public Skey createSkey() {
return new Skey();
}
/**
* Create an instance of {@link Uses }
*
*/
public Uses createUses() {
return new Uses();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Auth }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://www.uidai.gov.in/authentication/uid-auth-request/2.0", name = "Auth")
// @XmlElementDecl(namespace = "http://www.uidai.gov.in/authentication/uid-auth-request/2.5", name = "Auth")
public JAXBElement<Auth> createAuth(Auth value) {
return new JAXBElement<Auth>(_Auth_QNAME, Auth.class, null, value);
}
}
| gpl-2.0 |
markan82/diary | src/br/com/condesales/models/ScoreItem.java | 279 | package br.com.condesales.models;
public class ScoreItem {
private String message;
private String icon;
private int points;
public String getMessage() {
return message;
}
public String getIcon() {
return icon;
}
public int getPoints() {
return points;
}
}
| gpl-2.0 |
justinwm/astor | src/main/java/fr/inria/astor/core/validation/executors/JUnitExecutorProcessWait.java | 2593 | package fr.inria.astor.core.validation.executors;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import fr.inria.astor.core.setup.ConfigurationProperties;
import fr.inria.astor.core.validation.entity.TestResult;
import fr.inria.astor.junitexec.JUnitTestExecutor;
/**
* Process-based program variant validation, used for executing EvoSuite test cases
*
* @author Matias Martinez, matias.martinez@inria.fr
*
*/@Deprecated
public abstract class JUnitExecutorProcessWait extends JUnitExecutorProcess {
@Override
public TestResult execute(String jvmPath, String path, List<String> classesToExecute, int waitTime) {
Process p = null;
String javaPath = ConfigurationProperties.getProperty("jvm4evosuitetestexecution");
javaPath += File.separator + "java";
String systemcp = System.getProperty("java.class.path");
path = systemcp + File.pathSeparator + path;
List<String> cls = new ArrayList<>(classesToExecute);
try {
List<String> command = new ArrayList<String>();
command.add(javaPath);
command.add("-Xmx2048m");
command.add("-cp");
command.add(path);
command.add(JUnitTestExecutor.class.getName());
command.addAll(cls);
ProcessBuilder pb = new ProcessBuilder(command.toArray(new String[command.size()]));
pb.redirectOutput();
pb.redirectErrorStream(true);
pb.directory(new File((ConfigurationProperties.getProperty("location"))));
long t_start = System.currentTimeMillis();
p = pb.start();
String commandString = command.toString().replace("[", "").replace("]", "").replace(",", " ");
int trunk = ConfigurationProperties.getPropertyInt("commandTrunk");
String commandToPrint = (trunk != 0 && commandString.length() > trunk) ? (commandString.substring(0, trunk)
+ "..AND " + (commandString.length() - trunk) + " CHARS MORE...") : commandString;
log.debug("Executing process: \n" + commandToPrint);
// Here, we do not use the worker
// jdk 8 p.waitFor(waitTime,TimeUnit.MILLISECONDS);
// Exec: p.wait(waitTime);
WorkerThreadHelper worker = new WorkerThreadHelper(p);
worker.start();
worker.join(waitTime);
// ==
long t_end = System.currentTimeMillis();
TestResult tr = getTestResult(p);
p.destroy();
log.debug("Execution time " + ((t_end - t_start) / 1000) + " seconds");
return tr;
} catch (IOException | InterruptedException | IllegalThreadStateException ex) {
log.error("The Process that runs JUnit test cases had problems: " + ex.getMessage());
if (p != null)
p.destroy();
}
return null;
}
}
| gpl-2.0 |
FCC/mobile-mba-androidapp | libcore/src/com/samknows/measurement/environment/NetUsageCollector.java | 873 | package com.samknows.measurement.environment;
import com.samknows.measurement.CachingStorage;
import com.samknows.measurement.Storage;
import android.content.Context;
public class NetUsageCollector extends BaseDataCollector {
public static final String NETUSAGE_STORAGE = "netusage_storage";
public NetUsageCollector(Context context) {
super(context);
}
@Override
public DCSData collect() {
Storage storage = CachingStorage.getInstance();
TrafficData start = storage.loadNetUsage();
TrafficData now = TrafficStatsCollector.collectTraffic();
storage.saveNetUsage(now);
//if there is no data in cache return null
if(start == null){
return null;
}
return TrafficData.interval(start, now);
}
@Override
public void start() {
// TODO Auto-generated method stub
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
}
| gpl-2.0 |
mobile-event-processing/Asper | source/test/com/espertech/esper/regression/epl/TestCreateExpression.java | 12005 | /*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.regression.epl;
import com.espertech.esper.client.*;
import com.espertech.esper.client.scopetest.EPAssertionUtil;
import com.espertech.esper.client.scopetest.SupportUpdateListener;
import com.espertech.esper.client.soda.EPStatementObjectModel;
import com.espertech.esper.support.bean.SupportBean;
import com.espertech.esper.support.bean.SupportBean_S0;
import com.espertech.esper.support.bean.SupportCollection;
import com.espertech.esper.support.bean.lambda.LambdaAssertionUtil;
import com.espertech.esper.support.client.SupportConfigFactory;
import junit.framework.TestCase;
public class TestCreateExpression extends TestCase
{
private EPServiceProvider epService;
public void setUp()
{
Configuration config = SupportConfigFactory.getConfiguration();
config.addEventType(SupportBean.class);
config.addEventType(SupportBean_S0.class);
config.addEventType(SupportCollection.class);
epService = EPServiceProviderManager.getDefaultProvider(config);
epService.initialize();
}
public void testInvalid() {
epService.getEPAdministrator().createEPL("create expression E1 {''}");
tryInvalid("create expression E1 {''}",
"Error starting statement: Expression 'E1' has already been declared [create expression E1 {''}]");
epService.getEPAdministrator().createEPL("create expression int js:abc(p1, p2) [p1*p2]");
tryInvalid("create expression int js:abc(a, a) [p1*p2]",
"Error starting statement: Script 'abc' that takes the same number of parameters has already been declared [create expression int js:abc(a, a) [p1*p2]]");
}
public void testParseSpecialAndMixedExprAndScript() {
SupportUpdateListener listener = new SupportUpdateListener();
epService.getEPAdministrator().createEPL("create expression string js:myscript(p1) [\"--\"+p1+\"--\"]");
epService.getEPAdministrator().createEPL("create expression myexpr {sb => '--'||theString||'--'}");
// test mapped property syntax
String eplMapped = "select myscript('x') as c0, myexpr(sb) as c1 from SupportBean as sb";
EPStatement stmtMapped = epService.getEPAdministrator().createEPL(eplMapped);
stmtMapped.addListener(listener);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 1));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "c0,c1".split(","), new Object[]{"--x--", "--E1--"});
stmtMapped.destroy();
// test expression chained syntax
String eplExpr = "" +
"create expression scalarfilter {s => " +
" strvals.where(y => y != 'E1') " +
"}";
epService.getEPAdministrator().createEPL(eplExpr);
String eplSelect = "select scalarfilter(t).where(x => x != 'E2') as val1 from SupportCollection as t";
epService.getEPAdministrator().createEPL(eplSelect).addListener(listener);
epService.getEPRuntime().sendEvent(SupportCollection.makeString("E1,E2,E3,E4"));
LambdaAssertionUtil.assertValuesArrayScalar(listener, "val1", "E3", "E4");
epService.getEPAdministrator().destroyAllStatements();
listener.reset();
// test script chained synax
String eplScript = "create expression " + SupportBean.class.getName() + " js:callIt() [ new " + SupportBean.class.getName() + "('E1', 10); ]";
epService.getEPAdministrator().createEPL(eplScript);
epService.getEPAdministrator().createEPL("select callIt() as val0, callIt().getTheString() as val1 from SupportBean as sb").addListener(listener);
epService.getEPRuntime().sendEvent(new SupportBean());
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "val0.theString,val0.intPrimitive,val1".split(","), new Object[]{"E1", 10, "E1"});
}
public void testScriptUse() {
epService.getEPAdministrator().createEPL("create expression int js:abc(p1, p2) [p1*p2*10]");
epService.getEPAdministrator().createEPL("create expression int js:abc(p1) [p1*10]");
String epl = "select abc(intPrimitive, doublePrimitive) as c0, abc(intPrimitive) as c1 from SupportBean";
EPStatement stmt = epService.getEPAdministrator().createEPL(epl);
SupportUpdateListener listener = new SupportUpdateListener();
stmt.addListener(listener);
epService.getEPRuntime().sendEvent(makeBean("E1", 10, 3.5));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "c0,c1".split(","), new Object[]{350, 100});
stmt.destroy();
// test SODA
String eplExpr = "create expression somescript(i1) ['a']";
EPStatementObjectModel modelExpr = epService.getEPAdministrator().compileEPL(eplExpr);
assertEquals(eplExpr, modelExpr.toEPL());
EPStatement stmtSODAExpr = epService.getEPAdministrator().create(modelExpr);
assertEquals(eplExpr, stmtSODAExpr.getText());
String eplSelect = "select somescript(1) from SupportBean";
EPStatementObjectModel modelSelect = epService.getEPAdministrator().compileEPL(eplSelect);
assertEquals(eplSelect, modelSelect.toEPL());
EPStatement stmtSODASelect = epService.getEPAdministrator().create(modelSelect);
assertEquals(eplSelect, stmtSODASelect.getText());
}
public void testExpressionUse() {
SupportUpdateListener listener = new SupportUpdateListener();
epService.getEPAdministrator().createEPL("create expression TwoPi {Math.PI * 2}");
epService.getEPAdministrator().createEPL("create expression factorPi {sb => Math.PI * intPrimitive}");
String[] fields = "c0,c1,c2".split(",");
String epl = "select " +
"TwoPi() as c0," +
"(select TwoPi() from SupportBean_S0.std:lastevent()) as c1," +
"factorPi(sb) as c2 " +
"from SupportBean sb";
EPStatement stmtSelect = epService.getEPAdministrator().createEPL(epl);
stmtSelect.addListener(listener);
epService.getEPRuntime().sendEvent(new SupportBean_S0(10));
epService.getEPRuntime().sendEvent(new SupportBean("E1", 3)); // factor is 3
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields,
new Object[] {Math.PI*2, Math.PI*2, Math.PI*3});
stmtSelect.destroy();
// test local expression override
EPStatement stmtOverride = epService.getEPAdministrator().createEPL("expression TwoPi {Math.PI * 10} select TwoPi() as c0 from SupportBean");
stmtOverride.addListener(listener);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 0));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "c0".split(","), new Object[] {Math.PI*10});
// test SODA
String eplExpr = "create expression JoinMultiplication {(s1, s2) => s1.intPrimitive * s2.id}";
EPStatementObjectModel modelExpr = epService.getEPAdministrator().compileEPL(eplExpr);
assertEquals(eplExpr, modelExpr.toEPL());
EPStatement stmtSODAExpr = epService.getEPAdministrator().create(modelExpr);
assertEquals(eplExpr, stmtSODAExpr.getText());
// test SODA and join and 2-stream parameter
String eplJoin = "select JoinMultiplication(sb, s0) from SupportBean.std:lastevent() as sb, SupportBean_S0.std:lastevent() as s0";
EPStatementObjectModel modelJoin = epService.getEPAdministrator().compileEPL(eplJoin);
assertEquals(eplJoin, modelJoin.toEPL());
EPStatement stmtSODAJoin = epService.getEPAdministrator().create(modelJoin);
assertEquals(eplJoin, stmtSODAJoin.getText());
epService.getEPAdministrator().destroyAllStatements();
// test subquery defined in declared expression
epService.getEPAdministrator().createEPL("create expression myexpr {(select intPrimitive from ABCWindow)}");
epService.getEPAdministrator().createEPL("create window ABCWindow.win:keepall() as SupportBean");
epService.getEPAdministrator().createEPL("insert into ABCWindow select * from SupportBean");
epService.getEPAdministrator().createEPL("select myexpr() as c0 from SupportBean_S0").addListener(listener);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 100));
epService.getEPRuntime().sendEvent(new SupportBean_S0(1, "E1"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "c0".split(","), new Object[] {100});
}
public void testExprAndScriptLifecycleAndFilter() {
// expression assertion
runAssertionLifecycleAndFilter("create expression MyFilter {sb => intPrimitive = 1}",
"select * from SupportBean(MyFilter(sb)) as sb",
"create expression MyFilter {sb => intPrimitive = 2}");
// script assertion
runAssertionLifecycleAndFilter("create expression boolean js:MyFilter(intPrimitive) [intPrimitive==1]",
"select * from SupportBean(MyFilter(intPrimitive)) as sb",
"create expression boolean js:MyFilter(intPrimitive) [intPrimitive==2]");
}
private void runAssertionLifecycleAndFilter(String expressionBefore,
String selector,
String expressionAfter) {
SupportUpdateListener l1 = new SupportUpdateListener();
SupportUpdateListener l2 = new SupportUpdateListener();
EPStatement stmtExpression = epService.getEPAdministrator().createEPL(expressionBefore);
EPStatement stmtSelectOne = epService.getEPAdministrator().createEPL(selector);
stmtSelectOne.addListener(l1);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 0));
assertFalse(l1.getAndClearIsInvoked());
epService.getEPRuntime().sendEvent(new SupportBean("E2", 1));
assertTrue(l1.getAndClearIsInvoked());
stmtExpression.destroy();
epService.getEPAdministrator().createEPL(expressionAfter);
EPStatement stmtSelectTwo = epService.getEPAdministrator().createEPL(selector);
stmtSelectTwo.addListener(l2);
epService.getEPRuntime().sendEvent(new SupportBean("E3", 0));
assertFalse(l1.getAndClearIsInvoked() || l2.getAndClearIsInvoked());
epService.getEPRuntime().sendEvent(new SupportBean("E4", 1));
assertTrue(l1.getAndClearIsInvoked());
assertFalse(l2.getAndClearIsInvoked());
epService.getEPRuntime().sendEvent(new SupportBean("E4", 2));
assertFalse(l1.getAndClearIsInvoked());
assertTrue(l2.getAndClearIsInvoked());
epService.getEPAdministrator().destroyAllStatements();
}
private void tryInvalid(String epl, String message) {
try {
epService.getEPAdministrator().createEPL(epl);
fail();
}
catch (EPStatementException ex) {
assertEquals(message, ex.getMessage());
}
}
private SupportBean makeBean(String theString, int intPrimitive, double doublePrimitive) {
SupportBean sb = new SupportBean();
sb.setIntPrimitive(intPrimitive);
sb.setDoublePrimitive(doublePrimitive);
return sb;
}
}
| gpl-2.0 |
icelemon1314/mapleLemon | src/handling/login/handler/PacketErrorHandler.java | 1660 | package handling.login.handler;
import client.MapleClient;
import handling.SendPacketOpcode;
import tools.FileoutputUtil;
import static tools.FileoutputUtil.CurrentReadable_Time;
import tools.StringUtil;
import tools.data.input.SeekableLittleEndianAccessor;
public class PacketErrorHandler {
public static void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
if (slea.available() >= 6L) {
slea.skip(6);
short badPacketSize = slea.readShort();
slea.skip(4);
int pHeader = slea.readShort();
String pHeaderStr = Integer.toHexString(pHeader).toUpperCase();
pHeaderStr = StringUtil.getLeftPaddedStr(pHeaderStr, '0', 4);
String op = lookupRecv(pHeader);
String from = "\r\n------------------------ " + CurrentReadable_Time() + " ------------------------\r\n";
if (c.getPlayer() != null) {
from += "角色: " + c.getPlayer().getName() + " 等级(" + c.getPlayer().getLevel() + ") 职业: " + c.getPlayer().getJobName() + " (" + c.getPlayer().getJob() + ") 地图: " + c.getPlayer().getMapId() + " \r\n";
}
String Recv = "" + op + " [" + pHeaderStr + "] (" + (badPacketSize - 4) + ")" + slea.toString();
FileoutputUtil.packetLog(FileoutputUtil.Packet_Error, from + Recv);
}
}
private static String lookupRecv(int val) {
for (SendPacketOpcode op : SendPacketOpcode.values()) {
if (op.getValue(false) == val) {
return op.name();
}
}
return "UNKNOWN";
}
}
| gpl-2.0 |
fuuka1994/dss2016 | src/Main.java | 290 | import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import controller.ChatController;
import view.ChatWindow;
public class Main {
public static void main(String[] args) {
new ChatController();
}
}
| gpl-2.0 |
1995parham/OpenTrax | src/main/java/home/parham/trax/core/player/Player.java | 405 | /*
* In The Name Of God
* ======================================
* [] Project Name : OpenTrax
*
* [] Package Name : main.player
*
* [] Creation Date : 11-02-2015
*
* [] Created By : Parham Alvani (parham.alvani@gmail.com)
* =======================================
*/
package home.parham.trax.core.player;
public interface Player {
String move(String otherPlayerMove);
String getName();
}
| gpl-2.0 |
GoldBigDragon/GoldBigDragonRPG | [Spigot 1.8.8]/GoldBigDragonRPG_Source/GoldBigDragon_RPG/Monster/AI/AI_Elite_Hunter.java | 3102 | package GoldBigDragon_RPG.Monster.AI;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftSkeleton;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import GoldBigDragon_RPG.Util.YamlController;
import GoldBigDragon_RPG.Util.YamlManager;
import net.minecraft.server.v1_8_R3.EntityHuman;
import net.minecraft.server.v1_8_R3.EntityLiving;
import net.minecraft.server.v1_8_R3.EntitySkeleton;
import net.minecraft.server.v1_8_R3.World;
import net.minecraft.server.v1_8_R3.PathfinderGoalFloat;
import net.minecraft.server.v1_8_R3.PathfinderGoalHurtByTarget;
import net.minecraft.server.v1_8_R3.PathfinderGoalLookAtPlayer;
import net.minecraft.server.v1_8_R3.PathfinderGoalMoveThroughVillage;
import net.minecraft.server.v1_8_R3.PathfinderGoalMoveTowardsRestriction;
import net.minecraft.server.v1_8_R3.PathfinderGoalNearestAttackableTarget;
import net.minecraft.server.v1_8_R3.PathfinderGoalRandomLookaround;
import net.minecraft.server.v1_8_R3.PathfinderGoalRandomStroll;
public class AI_Elite_Hunter extends EntitySkeleton
{
public AI_Elite_Hunter(World world)
{
super(world);
if(GoldBigDragon_RPG.Main.ServerOption.SpawnMobName != null)
{
YamlController YC = new YamlController(GoldBigDragon_RPG.Main.Main.plugin);
YamlManager Monster = YC.getNewConfig("Monster/MonsterList.yml");
String AI = Monster.getString(GoldBigDragon_RPG.Main.ServerOption.SpawnMobName + ".AI");
this.goalSelector.a(0, new PathfinderGoalFloat(this));
this.goalSelector.a(5, new PathfinderGoalMoveTowardsRestriction(this, 1.0D));
this.goalSelector.a(6, new PathfinderGoalMoveThroughVillage(this, 1.0D, false));
this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D));
this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F));
this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this));
this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, true));
if(AI.equals("¼±°ø"))
this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget(this, EntityHuman.class, false, true));
GoldBigDragon_RPG.Main.ServerOption.SpawnMobName = null;
}
}
//È»ìÀÌ 5¹ß¾¿ ³ª°£´Ù.
@Override
public void a(EntityLiving entity, float f)
{
for(byte i=0;i<5;i++)
super.a(entity, f);
}
public static Skeleton spawn(Location location)
{
World mcWorld = (World) ((CraftWorld) location.getWorld()).getHandle();
final AI_Elite_Hunter customEntity = new AI_Elite_Hunter(mcWorld);
customEntity.setLocation(location.getX(), location.getY(),
location.getZ(), location.getYaw(), location.getPitch());
if(location.getWorld().getName().compareTo("Dungeon")==0)
((CraftLivingEntity) customEntity.getBukkitEntity()).setRemoveWhenFarAway(false);
mcWorld.addEntity(customEntity, SpawnReason.CUSTOM);
return (CraftSkeleton) customEntity.getBukkitEntity();
}
} | gpl-2.0 |
FlaPer87/meclipse | org.mongodb.meclipse/src/org/mongodb/meclipse/views/objects/properties/ConnectionPropertySource.java | 303 | package org.mongodb.meclipse.views.objects.properties;
import org.mongodb.meclipse.views.objects.Connection;
public class ConnectionPropertySource extends DBObjectPropertySource {
// private Connection conn;
public ConnectionPropertySource(Connection conn) {
super(conn.getServerStatus());
}
}
| gpl-2.0 |
crotwell/fissuresUtil | src/main/java/edu/sc/seis/fissuresUtil/xml/Writer.java | 13908 | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
//package dom;
package edu.sc.seis.fissuresUtil.xml;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* A sample DOM writer. This sample program illustrates how to
* traverse a DOM tree in order to print a document that is parsed.
*
* @author Andy Clark, IBM
*
* @version $Id: Writer.java 22072 2011-02-18 15:43:18Z crotwell $
*/
public class Writer {
//
// Constants
//
// feature ids
/** Namespaces feature id (http://xml.org/sax/features/namespaces). */
protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
/** Validation feature id (http://xml.org/sax/features/validation). */
protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
/** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
/** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
// property ids
/** Lexical handler property id (http://xml.org/sax/properties/lexical-handler). */
protected static final String LEXICAL_HANDLER_PROPERTY_ID = "http://xml.org/sax/properties/lexical-handler";
// default settings
/** Default parser name. */
protected static final String DEFAULT_PARSER_NAME = "dom.wrappers.Xerces";
/** Default namespaces support (true). */
protected static final boolean DEFAULT_NAMESPACES = true;
/** Default validation support (false). */
protected static final boolean DEFAULT_VALIDATION = false;
/** Default Schema validation support (false). */
protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;
/** Default Schema full checking support (false). */
protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
/** Default canonical output (false). */
protected static final boolean DEFAULT_CANONICAL = false;
//
// Data
//
/** Print writer. */
protected PrintWriter fOut;
/** Canonical output. */
protected boolean fCanonical;
/** Print newlines after end elements **/
protected boolean printNewlines;
//
// Constructors
//
/** Default constructor. */
public Writer() {
this(false);
} // <init>()
public Writer(boolean canonical) {
this(canonical, false);
} // <init>(boolean)
public Writer(boolean canonical, boolean printNewlines){
fCanonical = canonical;
this.printNewlines = printNewlines;
}
//
// Public methods
//
/** Sets whether output is canonical. */
public void setCanonical(boolean canonical) {
fCanonical = canonical;
} // setCanonical(boolean)
/** Sets the output stream for printing. */
public void setOutput(OutputStream stream, String encoding)
throws UnsupportedEncodingException {
if (encoding == null) {
encoding = "UTF8";
}
java.io.Writer writer = new OutputStreamWriter(stream, encoding);
fOut = new PrintWriter(writer);
} // setOutput(OutputStream,String)
/** Sets the output writer. */
public void setOutput(java.io.Writer writer) {
fOut = writer instanceof PrintWriter
? (PrintWriter)writer : new PrintWriter(writer);
} // setOutput(java.io.Writer)
/** Writes the specified node, recursively. */
public void write(Node node) {
// is there anything to do?
if (node == null) {
return;
}
short type = node.getNodeType();
switch (type) {
case Node.DOCUMENT_NODE: {
Document document = (Document)node;
if (!fCanonical) {
fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
fOut.flush();
write(document.getDoctype());
}
write(document.getDocumentElement());
break;
}
case Node.DOCUMENT_TYPE_NODE: {
DocumentType doctype = (DocumentType)node;
fOut.print("<!DOCTYPE ");
fOut.print(doctype.getName());
String publicId = doctype.getPublicId();
String systemId = doctype.getSystemId();
if (publicId != null) {
fOut.print(" PUBLIC '");
fOut.print(publicId);
fOut.print("' '");
fOut.print(systemId);
fOut.print('\'');
}
else {
fOut.print(" SYSTEM '");
fOut.print(systemId);
fOut.print('\'');
}
String internalSubset = doctype.getInternalSubset();
if (internalSubset != null) {
if (printNewlines){
fOut.println(" [");
} else{
fOut.print(" [");
}
fOut.print(internalSubset);
fOut.print(']');
}
fOut.println('>');
break;
}
case Node.ELEMENT_NODE: {
fOut.print('<');
fOut.print(node.getNodeName());
Attr attrs[] = sortAttributes(node.getAttributes());
for (int i = 0; i < attrs.length; i++) {
Attr attr = attrs[i];
fOut.print(' ');
fOut.print(attr.getNodeName());
fOut.print("=\"");
normalizeAndPrint(attr.getNodeValue());
fOut.print('"');
}
fOut.print('>');
fOut.flush();
Node child = node.getFirstChild();
while (child != null) {
write(child);
child = child.getNextSibling();
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
if (fCanonical) {
Node child = node.getFirstChild();
while (child != null) {
write(child);
child = child.getNextSibling();
}
}
else {
fOut.print('&');
fOut.print(node.getNodeName());
fOut.print(';');
fOut.flush();
}
break;
}
case Node.CDATA_SECTION_NODE: {
if (fCanonical) {
normalizeAndPrint(node.getNodeValue());
}
else {
fOut.print("<![CDATA[");
fOut.print(node.getNodeValue());
fOut.print("]]>");
}
fOut.flush();
break;
}
case Node.TEXT_NODE: {
normalizeAndPrint(node.getNodeValue());
fOut.flush();
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
fOut.print("<?");
fOut.print(node.getNodeName());
String data = node.getNodeValue();
if (data != null && data.length() > 0) {
fOut.print(' ');
fOut.print(data);
}
if (printNewlines){
fOut.println("?>");
} else {
fOut.print("?>");
}
fOut.flush();
break;
}
}
if (type == Node.ELEMENT_NODE) {
fOut.print("</");
fOut.print(node.getNodeName());
if (printNewlines){
fOut.println('>');
} else {
fOut.print('>');
}
fOut.flush();
}
} // write(Node)
/** Returns a sorted list of attributes. */
protected Attr[] sortAttributes(NamedNodeMap attrs) {
int len = (attrs != null) ? attrs.getLength() : 0;
Attr array[] = new Attr[len];
for (int i = 0; i < len; i++) {
array[i] = (Attr)attrs.item(i);
}
for (int i = 0; i < len - 1; i++) {
String name = array[i].getNodeName();
int index = i;
for (int j = i + 1; j < len; j++) {
String curName = array[j].getNodeName();
if (curName.compareTo(name) < 0) {
name = curName;
index = j;
}
}
if (index != i) {
Attr temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
return array;
} // sortAttributes(NamedNodeMap):Attr[]
//
// Protected methods
//
/** Normalizes and prints the given string. */
protected void normalizeAndPrint(String s) {
int len = (s != null) ? s.length() : 0;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
normalizeAndPrint(c);
}
} // normalizeAndPrint(String)
/** Normalizes and print the given character. */
protected void normalizeAndPrint(char c) {
switch (c) {
case '<': {
fOut.print("<");
break;
}
case '>': {
fOut.print(">");
break;
}
case '&': {
fOut.print("&");
break;
}
case '"': {
fOut.print(""");
break;
}
case '\r':
case '\n': {
if (fCanonical) {
fOut.print("&#");
fOut.print(Integer.toString(c));
fOut.print(';');
break;
}
// else, default print char
}
default: {
fOut.print(c);
}
}
} // normalizeAndPrint(char)
} // class Writer
| gpl-2.0 |
SOCVFinder/SOCVFinder | SOCVDBService/src/jdd/so/service/SOCVFinderServiceWrapper.java | 5398 | package jdd.so.service;
import java.io.FileInputStream;
import java.util.Properties;
import org.alicebot.ab.AIMLProcessor;
import org.alicebot.ab.MagicStrings;
import org.alicebot.ab.PCAIMLProcessorExtension;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.sobotics.redunda.PingService;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;
import jdd.so.CloseVoteFinder;
import jdd.so.bot.ChatBot;
public class SOCVFinderServiceWrapper implements WrapperListener {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(SOCVFinderServiceWrapper.class);
static {
PropertyConfigurator.configure("ini/log4j.properties");
}
private ChatBot cb;
/*---------------------------------------------------------------
* Constructors
*-------------------------------------------------------------*/
/**
* Creates an instance of a WrapperSimpleApp.
*
* @param The
* full list of arguments passed to the JVM.
*/
protected SOCVFinderServiceWrapper(String args[]) {
// Initialize the WrapperManager class on startup by referencing it.
@SuppressWarnings("unused")
Class<WrapperManager> wmClass = WrapperManager.class;
// Start the application. If the JVM was launched from the native
// Wrapper then the application will wait for the native Wrapper to
// call the application's start method. Otherwise the start method
// will be called immediately.
WrapperManager.start(this, args);
// This thread ends, the WrapperManager will start the application after
// the Wrapper has
// been properly initialized by calling the start method above.
}
public static void main(String[] args) {
new SOCVFinderServiceWrapper(args);
}
/*---------------------------------------------------------------
* WrapperListener Methods
*-------------------------------------------------------------*/
/**
* The start method is called when the WrapperManager is signalled by the
* native wrapper code that it can start its application. This method call
* is expected to return, so a new thread should be launched if necessary.
* If there are any problems, then an Integer should be returned, set to the
* desired exit code. If the application should continue, return null.
*/
@Override
public Integer start(String[] args) {
if (logger.isInfoEnabled()) {
logger.info("start(String[]) - start");
}
// Load AI interface
AIMLProcessor.extension = new PCAIMLProcessorExtension();
MagicStrings.root_path = System.getProperty("user.dir");
MagicStrings.default_bot_name = ChatBot.BOT_NAME;
// Load properties file an instance the CloseVoteFinder
// Start the bot
try {
Properties properties = new Properties();
properties.load(new FileInputStream("ini/SOCVService.properties"));
CloseVoteFinder.initInstance(properties);
//Redunda service
if (logger.isInfoEnabled()) {
logger.info("Starting redunda ping service");
}
PingService redunda = new PingService("b2f12d074632a1d9b2f55c3955326cf2c44b6d0f2210717bb467b18006161f91", CloseVoteFinder.VERSION);
redunda.start();
cb = new ChatBot(properties, null);
SOLoginThread login = new SOLoginThread(); // takes to much time
login.start();
if (logger.isDebugEnabled()) {
logger.debug("start(String[]) - Start completed");
}
} catch (Throwable e) {
logger.error("start service", e);
CloseVoteFinder.getInstance().shutDown();
cb.close();
return 1;
}
if (logger.isInfoEnabled()) {
logger.info("start(String[]) - end");
}
return null;
}
/**
* Called when the application is shutting down.
*/
@Override
public int stop(int exitCode) {
if (logger.isInfoEnabled()) {
logger.info("stop() - exitCode:" + exitCode);
}
try {
if (cb != null) {
cb.close();
}
CloseVoteFinder.getInstance().shutDown();
} catch (Throwable e) {
logger.error("stop(int)", e);
}
if (logger.isInfoEnabled()) {
logger.info("stop() end");
}
return exitCode;
}
/**
* Called whenever the native wrapper code traps a system control signal
* against the Java process. It is up to the callback to take any actions
* necessary. Possible values are: WrapperManager.WRAPPER_CTRL_C_EVENT,
* WRAPPER_CTRL_CLOSE_EVENT, WRAPPER_CTRL_LOGOFF_EVENT, or
* WRAPPER_CTRL_SHUTDOWN_EVENT
*/
@Override
public void controlEvent(int event) {
if ((event == WrapperManager.WRAPPER_CTRL_LOGOFF_EVENT) && WrapperManager.isLaunchedAsService()) {
// Ignore
if (logger.isInfoEnabled()) {
logger.info("ServiceWrapper: controlEvent(" + event + ") Ignored");
}
} else {
if (logger.isInfoEnabled()) {
logger.info("ServiceWrapper: controlEvent(" + event + ") Stopping");
}
WrapperManager.stop(0);
// Will not get here.
}
}
private class SOLoginThread extends Thread {
/**
* Logger for this class
*/
private final Logger logger = Logger.getLogger(SOLoginThread.class);
@Override
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("start(String[]) - Start login");
}
cb.loginIn();
logger.info("start(String[]) - Join rooms - START");
cb.joinRooms();
logger.info("start(String[]) - Join rooms - END");
cb.startDupeHunter();
logger.info("start(String[]) - dupe hunter - END");
}
}
}
| gpl-2.0 |
Jsawrus/Masters | src/com/ftbmasters/commands/TeleportCommands.java | 1772 | package com.ftbmasters.commands;
import com.ftbmasters.utils.commands.Command;
import com.ftbmasters.utils.commands.CommandArgumentException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class TeleportCommands {
@Command (
name = "teleport",
permission = "masters.teleport",
usage = "/teleport [from] <to> | <x> <y> <z>",
description = "Teleport you to someone or somewhere"
)
public void teleport(CommandSender sender, String[] args) {
throw new CommandArgumentException(ChatColor.RED + "This is the future!~");
}
@Command (
name = "invite",
permission = "masters.invite",
usage = "/invite <player>",
description = "Invite a Player to your location"
)
public void invite(CommandSender sender, String[] args) throws CommandArgumentException{
if (args.length != 1)
throw new CommandArgumentException(ChatColor.RED + "Correct usage: /invite <player>");
Player player2 = Bukkit.getPlayer(args[0]);
if (player2 == null)
throw new CommandArgumentException(ChatColor.RED + "The player " + args[0] + " doesn't exist.");
Player player = ((Player) sender).getPlayer();
Location location = player.getLocation();
double x = Math.round(location.getBlockX() + 0.5D);
double y = Math.round(location.getBlockY() + 0.5D);
double z = Math.round(location.getBlockZ() + 0.5D);
player2.sendMessage(ChatColor.GREEN + player.getDisplayName() + ChatColor.GREEN + " invites you to " + ChatColor.RED + "(" + ChatColor.GOLD + x + ", " + y + ", " + z + ChatColor.RED + ")");
sender.sendMessage(ChatColor.GREEN + "You have invited " + player2.getDisplayName() + ChatColor.GREEN + " to your location");
}
}
| gpl-2.0 |
easyxu/toolkit-sandbox | toolkit-sandbox-common/src/main/java/com/phoenix/common/lang/MathUtil.java | 35448 | package com.phoenix.common.lang;
import java.math.BigInteger;
/**
* 包装<code>java.lang.Math</code>的工具类。
*
* @author Michael Zhou
* @version $Id: MathUtil.java 1163 2004-08-20 02:56:58Z baobao $
*/
public class MathUtil {
/**
* The <code>double</code> value that is closer than any other to <i>e</i>, the base of the
* natural logarithms.
*/
public static double getE() {
return Math.E;
}
/**
* The <code>double</code> value that is closer than any other to <i>pi</i>, the ratio of the
* circumference of a circle to its diameter.
*/
public static double getPI() {
return Math.PI;
}
/**
* Returns the trigonometric sine of an angle. Special cases:
*
* <ul>
* <li>
* If the argument is NaN or an infinity, then the result is NaN.
* </li>
* <li>
* If the argument is zero, then the result is a zero with the same sign as the argument.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a an angle, in radians.
*
* @return the sine of the argument.
*/
public static double sin(double a) {
return Math.sin(a);
}
/**
* Returns the trigonometric cosine of an angle. Special cases:
*
* <ul>
* <li>
* If the argument is NaN or an infinity, then the result is NaN.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a an angle, in radians.
*
* @return the cosine of the argument.
*/
public static double cos(double a) {
return Math.cos(a);
}
/**
* Returns the trigonometric tangent of an angle. Special cases:
*
* <ul>
* <li>
* If the argument is NaN or an infinity, then the result is NaN.
* </li>
* <li>
* If the argument is zero, then the result is a zero with the same sign as the argument.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a an angle, in radians.
*
* @return the tangent of the argument.
*/
public static double tan(double a) {
return Math.tan(a);
}
/**
* Returns the arc sine of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2. Special
* cases:
*
* <ul>
* <li>
* If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
* </li>
* <li>
* If the argument is zero, then the result is a zero with the same sign as the argument.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a the value whose arc sine is to be returned.
*
* @return the arc sine of the argument.
*/
public static double asin(double a) {
return Math.asin(a);
}
/**
* Returns the arc cosine of an angle, in the range of 0.0 through <i>pi</i>. Special case:
*
* <ul>
* <li>
* If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a the value whose arc cosine is to be returned.
*
* @return the arc cosine of the argument.
*/
public static double acos(double a) {
return Math.acos(a);
}
/**
* Returns the arc tangent of an angle, in the range of -<i>pi</i>/2 through <i>pi</i>/2.
* Special cases:
*
* <ul>
* <li>
* If the argument is NaN, then the result is NaN.
* </li>
* <li>
* If the argument is zero, then the result is a zero with the same sign as the argument.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a the value whose arc tangent is to be returned.
*
* @return the arc tangent of the argument.
*/
public static double atan(double a) {
return Math.atan(a);
}
/**
* Converts an angle measured in degrees to an approximately equivalent angle measured in
* radians. The conversion from degrees to radians is generally inexact.
*
* @param angdeg an angle, in degrees
*
* @return the measurement of the angle <code>angdeg</code> in radians.
*
* @since 1.2
*/
public static double toRadians(double angdeg) {
return Math.toRadians(angdeg);
}
/**
* Converts an angle measured in radians to an approximately equivalent angle measured in
* degrees. The conversion from radians to degrees is generally inexact; users should
* <i>not</i> expect <code>cos(toRadians(90.0))</code> to exactly equal <code>0.0</code>.
*
* @param angrad an angle, in radians
*
* @return the measurement of the angle <code>angrad</code> in degrees.
*
* @since 1.2
*/
public static double toDegrees(double angrad) {
return Math.toDegrees(angrad);
}
/**
* Returns Euler's number <i>e</i> raised to the power of a <code>double</code> value. Special
* cases:
*
* <ul>
* <li>
* If the argument is NaN, the result is NaN.
* </li>
* <li>
* If the argument is positive infinity, then the result is positive infinity.
* </li>
* <li>
* If the argument is negative infinity, then the result is positive zero.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a the exponent to raise <i>e</i> to.
*
* @return the value <i>e</i><sup><code>a</code></sup>, where <i>e</i> is the base of the
* natural logarithms.
*/
public static double exp(double a) {
return Math.exp(a);
}
/**
* Returns the natural logarithm (base <i>e</i>) of a <code>double</code> value. Special
* cases:
*
* <ul>
* <li>
* If the argument is NaN or less than zero, then the result is NaN.
* </li>
* <li>
* If the argument is positive infinity, then the result is positive infinity.
* </li>
* <li>
* If the argument is positive zero or negative zero, then the result is negative infinity.
* </li>
* </ul>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a a number greater than <code>0.0</code>.
*
* @return the value ln <code>a</code>, the natural logarithm of <code>a</code>.
*/
public static double log(double a) {
return Math.log(a);
}
/**
* Returns the correctly rounded positive square root of a <code>double</code> value. Special
* cases:
*
* <ul>
* <li>
* If the argument is NaN or less than zero, then the result is NaN.
* </li>
* <li>
* If the argument is positive infinity, then the result is positive infinity.
* </li>
* <li>
* If the argument is positive zero or negative zero, then the result is the same as the
* argument.
* </li>
* </ul>
*
* Otherwise, the result is the <code>double</code> value closest to the true mathematical
* square root of the argument value.
*
* @param a a value. <!--@return the value of √ <code>a</code>.-->
*
* @return the positive square root of <code>a</code>. If the argument is NaN or less than
* zero, the result is NaN.
*/
public static double sqrt(double a) {
return Math.sqrt(a);
}
/**
* Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.
* The remainder value is mathematically equal to
* <code>f1 - f2</code> × <i>n</i>, where <i>n</i> is the
* mathematical integer closest to the exact mathematical value of the quotient
* <code>f1/f2</code>, and if two mathematical integers are equally close to
* <code>f1/f2</code>, then <i>n</i> is the integer that is even. If the remainder is zero,
* its sign is the same as the sign of the first argument. Special cases:
*
* <ul>
* <li>
* If either argument is NaN, or the first argument is infinite, or the second argument is
* positive zero or negative zero, then the result is NaN.
* </li>
* <li>
* If the first argument is finite and the second argument is infinite, then the result is the
* same as the first argument.
* </li>
* </ul>
*
*
* @param f1 the dividend.
* @param f2 the divisor.
*
* @return the remainder when <code>f1</code> is divided by <code>f2</code>.
*/
public static double IEEEremainder(double f1, double f2) {
return Math.IEEEremainder(f1, f2);
}
/**
* Returns the smallest (closest to negative infinity) <code>double</code> value that is not
* less than the argument and is equal to a mathematical integer. Special cases:
*
* <ul>
* <li>
* If the argument value is already equal to a mathematical integer, then the result is the
* same as the argument.
* </li>
* <li>
* If the argument is NaN or an infinity or positive zero or negative zero, then the result is
* the same as the argument.
* </li>
* <li>
* If the argument value is less than zero but greater than -1.0, then the result is negative
* zero.
* </li>
* </ul>
*
* Note that the value of <code>Math.ceil(x)</code> is exactly the value of
* <code>-Math.floor(-x)</code>.
*
* @param a a value. <!--@return the value ⌈ <code>a</code> ⌉.-->
*
* @return the smallest (closest to negative infinity) floating-point value that is not less
* than the argument and is equal to a mathematical integer.
*/
public static double ceil(double a) {
return Math.ceil(a);
}
/**
* Returns the largest (closest to positive infinity) <code>double</code> value that is not
* greater than the argument and is equal to a mathematical integer. Special cases:
*
* <ul>
* <li>
* If the argument value is already equal to a mathematical integer, then the result is the
* same as the argument.
* </li>
* <li>
* If the argument is NaN or an infinity or positive zero or negative zero, then the result is
* the same as the argument.
* </li>
* </ul>
*
*
* @param a a value. <!--@return the value ⌊ <code>a</code> ⌋.-->
*
* @return the largest (closest to positive infinity) floating-point value that is not greater
* than the argument and is equal to a mathematical integer.
*/
public static double floor(double a) {
return Math.floor(a);
}
/**
* Returns the <code>double</code> value that is closest in value to the argument and is equal
* to a mathematical integer. If two <code>double</code> values that are mathematical integers
* are equally close, the result is the integer value that is even. Special cases:
*
* <ul>
* <li>
* If the argument value is already equal to a mathematical integer, then the result is the
* same as the argument.
* </li>
* <li>
* If the argument is NaN or an infinity or positive zero or negative zero, then the result is
* the same as the argument.
* </li>
* </ul>
*
*
* @param a a <code>double</code> value.
*
* @return the closest floating-point value to <code>a</code> that is equal to a mathematical
* integer.
*/
public static double rint(double a) {
return Math.rint(a);
}
/**
* Converts rectangular coordinates (<code>x</code>, <code>y</code>) to polar
* (r, <i>theta</i>). This method computes the phase <i>theta</i> by computing an arc
* tangent of <code>y/x</code> in the range of -<i>pi</i> to <i>pi</i>. Special cases:
*
* <ul>
* <li>
* If either argument is NaN, then the result is NaN.
* </li>
* <li>
* If the first argument is positive zero and the second argument is positive, or the first
* argument is positive and finite and the second argument is positive infinity, then the
* result is positive zero.
* </li>
* <li>
* If the first argument is negative zero and the second argument is positive, or the first
* argument is negative and finite and the second argument is positive infinity, then the
* result is negative zero.
* </li>
* <li>
* If the first argument is positive zero and the second argument is negative, or the first
* argument is positive and finite and the second argument is negative infinity, then the
* result is the <code>double</code> value closest to <i>pi</i>.
* </li>
* <li>
* If the first argument is negative zero and the second argument is negative, or the first
* argument is negative and finite and the second argument is negative infinity, then the
* result is the <code>double</code> value closest to -<i>pi</i>.
* </li>
* <li>
* If the first argument is positive and the second argument is positive zero or negative
* zero, or the first argument is positive infinity and the second argument is finite, then
* the result is the <code>double</code> value closest to <i>pi</i>/2.
* </li>
* <li>
* If the first argument is negative and the second argument is positive zero or negative
* zero, or the first argument is negative infinity and the second argument is finite, then
* the result is the <code>double</code> value closest to -<i>pi</i>/2.
* </li>
* <li>
* If both arguments are positive infinity, then the result is the <code>double</code> value
* closest to <i>pi</i>/4.
* </li>
* <li>
* If the first argument is positive infinity and the second argument is negative infinity,
* then the result is the <code>double</code> value closest to 3<i>pi</i>/4.
* </li>
* <li>
* If the first argument is negative infinity and the second argument is positive infinity,
* then the result is the <code>double</code> value closest to -<i>pi</i>/4.
* </li>
* <li>
* If both arguments are negative infinity, then the result is the <code>double</code> value
* closest to -3<i>pi</i>/4.
* </li>
* </ul>
*
* <p>
* A result must be within 2 ulps of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param y the ordinate coordinate
* @param x the abscissa coordinate
*
* @return the <i>theta</i> component of the point (<i>r</i>, <i>theta</i>) in polar
* coordinates that corresponds to the point (<i>x</i>, <i>y</i>) in Cartesian
* coordinates.
*/
public static double atan2(double y, double x) {
return Math.atan2(y, x);
}
/**
* Returns the value of the first argument raised to the power of the second argument. Special
* cases:
*
* <ul>
* <li>
* If the second argument is positive or negative zero, then the result is 1.0.
* </li>
* <li>
* If the second argument is 1.0, then the result is the same as the first argument.
* </li>
* <li>
* If the second argument is NaN, then the result is NaN.
* </li>
* <li>
* If the first argument is NaN and the second argument is nonzero, then the result is NaN.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the absolute value of the first argument is greater than 1 and the second argument is
* positive infinity, or
* </li>
* <li>
* the absolute value of the first argument is less than 1 and the second argument is negative
* infinity,
* </li>
* </ul>
*
* then the result is positive infinity.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the absolute value of the first argument is greater than 1 and the second argument is
* negative infinity, or
* </li>
* <li>
* the absolute value of the first argument is less than 1 and the second argument is positive
* infinity,
* </li>
* </ul>
*
* then the result is positive zero.
* </li>
* <li>
* If the absolute value of the first argument equals 1 and the second argument is infinite,
* then the result is NaN.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is positive zero and the second argument is greater than zero, or
* </li>
* <li>
* the first argument is positive infinity and the second argument is less than zero,
* </li>
* </ul>
*
* then the result is positive zero.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is positive zero and the second argument is less than zero, or
* </li>
* <li>
* the first argument is positive infinity and the second argument is greater than zero,
* </li>
* </ul>
*
* then the result is positive infinity.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is negative zero and the second argument is greater than zero but not a
* finite odd integer, or
* </li>
* <li>
* the first argument is negative infinity and the second argument is less than zero but not a
* finite odd integer,
* </li>
* </ul>
*
* then the result is positive zero.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is negative zero and the second argument is a positive finite odd
* integer, or
* </li>
* <li>
* the first argument is negative infinity and the second argument is a negative finite odd
* integer,
* </li>
* </ul>
*
* then the result is negative zero.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is negative zero and the second argument is less than zero but not a
* finite odd integer, or
* </li>
* <li>
* the first argument is negative infinity and the second argument is greater than zero but not
* a finite odd integer,
* </li>
* </ul>
*
* then the result is positive infinity.
* </li>
* <li>
* If
*
* <ul>
* <li>
* the first argument is negative zero and the second argument is a negative finite odd
* integer, or
* </li>
* <li>
* the first argument is negative infinity and the second argument is a positive finite odd
* integer,
* </li>
* </ul>
*
* then the result is negative infinity.
* </li>
* <li>
* If the first argument is finite and less than zero
*
* <ul>
* <li>
* if the second argument is a finite even integer, the result is equal to the result of
* raising the absolute value of the first argument to the power of the second argument
* </li>
* <li>
* if the second argument is a finite odd integer, the result is equal to the negative of the
* result of raising the absolute value of the first argument to the power of the second
* argument
* </li>
* <li>
* if the second argument is finite and not an integer, then the result is NaN.
* </li>
* </ul>
*
* </li>
* <li>
* If both arguments are integers, then the result is exactly equal to the mathematical result
* of raising the first argument to the power of the second argument if that result can in
* fact be represented exactly as a <code>double</code> value.
* </li>
* </ul>
*
* <p>
* (In the foregoing descriptions, a floating-point value is considered to be an integer if and
* only if it is finite and a fixed point of the method {@link #ceil <tt>ceil</tt>} or,
* equivalently, a fixed point of the method {@link #floor <tt>floor</tt>}. A value is a fixed
* point of a one-argument method if and only if the result of applying the method to the
* value is equal to the value.)
* </p>
*
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results must be
* semi-monotonic.
* </p>
*
* @param a the base.
* @param b the exponent.
*
* @return the value <code>a<sup>b</sup></code>.
*/
public static double pow(double a, double b) {
return Math.pow(a, b);
}
/**
* Returns the closest <code>int</code> to the argument. The result is rounded to an integer
* by adding 1/2, taking the floor of the result, and casting the result to type
* <code>int</code>. In other words, the result is equal to the value of the expression:
*
* <p>
* <pre>(int)Math.floor(a + 0.5f)</pre>
* </p>
*
* <p>
* Special cases:
*
* <ul>
* <li>
* If the argument is NaN, the result is 0.
* </li>
* <li>
* If the argument is negative infinity or any value less than or equal to the value of
* <code>Integer.MIN_VALUE</code>, the result is equal to the value of
* <code>Integer.MIN_VALUE</code>.
* </li>
* <li>
* If the argument is positive infinity or any value greater than or equal to the value of
* <code>Integer.MAX_VALUE</code>, the result is equal to the value of
* <code>Integer.MAX_VALUE</code>.
* </li>
* </ul>
* </p>
*
* @param a a floating-point value to be rounded to an integer.
*
* @return the value of the argument rounded to the nearest <code>int</code> value.
*
* @see Integer#MAX_VALUE
* @see Integer#MIN_VALUE
*/
public static int round(float a) {
return Math.round(a);
}
/**
* Returns the closest <code>long</code> to the argument. The result is rounded to an integer
* by adding 1/2, taking the floor of the result, and casting the result to type
* <code>long</code>. In other words, the result is equal to the value of the expression:
*
* <p>
* <pre>(long)Math.floor(a + 0.5d)</pre>
* </p>
*
* <p>
* Special cases:
*
* <ul>
* <li>
* If the argument is NaN, the result is 0.
* </li>
* <li>
* If the argument is negative infinity or any value less than or equal to the value of
* <code>Long.MIN_VALUE</code>, the result is equal to the value of
* <code>Long.MIN_VALUE</code>.
* </li>
* <li>
* If the argument is positive infinity or any value greater than or equal to the value of
* <code>Long.MAX_VALUE</code>, the result is equal to the value of
* <code>Long.MAX_VALUE</code>.
* </li>
* </ul>
* </p>
*
* @param a a floating-point value to be rounded to a <code>long</code>.
*
* @return the value of the argument rounded to the nearest <code>long</code> value.
*
* @see Long#MAX_VALUE
* @see Long#MIN_VALUE
*/
public static long round(double a) {
return Math.round(a);
}
/**
* Returns a <code>double</code> value with a positive sign, greater than or equal to
* <code>0.0</code> and less than <code>1.0</code>. Returned values are chosen pseudorandomly
* with (approximately) uniform distribution from that range.
*
* <p>
* When this method is first called, it creates a single new pseudorandom-number generator,
* exactly as if by the expression
* <blockquote>
* <pre>new java.util.Random</pre>
* </blockquote>
* This new pseudorandom-number generator is used thereafter for all calls to this method and
* is used nowhere else.
* </p>
*
* <p>
* This method is properly synchronized to allow correct use by more than one thread. However,
* if many threads need to generate pseudorandom numbers at a great rate, it may reduce
* contention for each thread to have its own pseudorandom-number generator.
* </p>
*
* @return a pseudorandom <code>double</code> greater than or equal to <code>0.0</code> and
* less than <code>1.0</code>.
*
* @see java.util.Random#nextDouble()
*/
public static double random() {
return Math.random();
}
/**
* Returns the absolute value of an <code>int</code> value. If the argument is not negative,
* the argument is returned. If the argument is negative, the negation of the argument is
* returned.
*
* <p>
* Note that if the argument is equal to the value of <code>Integer.MIN_VALUE</code>, the most
* negative representable <code>int</code> value, the result is that same value, which is
* negative.
* </p>
*
* @param a the argument whose absolute value is to be determined
*
* @return the absolute value of the argument.
*
* @see Integer#MIN_VALUE
*/
public static int abs(int a) {
return Math.abs(a);
}
/**
* Returns the absolute value of a <code>long</code> value. If the argument is not negative,
* the argument is returned. If the argument is negative, the negation of the argument is
* returned.
*
* <p>
* Note that if the argument is equal to the value of <code>Long.MIN_VALUE</code>, the most
* negative representable <code>long</code> value, the result is that same value, which is
* negative.
* </p>
*
* @param a the argument whose absolute value is to be determined
*
* @return the absolute value of the argument.
*
* @see Long#MIN_VALUE
*/
public static long abs(long a) {
return Math.abs(a);
}
/**
* Returns the absolute value of a <code>float</code> value. If the argument is not negative,
* the argument is returned. If the argument is negative, the negation of the argument is
* returned. Special cases:
*
* <ul>
* <li>
* If the argument is positive zero or negative zero, the result is positive zero.
* </li>
* <li>
* If the argument is infinite, the result is positive infinity.
* </li>
* <li>
* If the argument is NaN, the result is NaN.
* </li>
* </ul>
*
* In other words, the result is the same as the value of the expression:
*
* <p>
* <pre>Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))</pre>
* </p>
*
* @param a the argument whose absolute value is to be determined
*
* @return the absolute value of the argument.
*/
public static float abs(float a) {
return Math.abs(a);
}
/**
* Returns the absolute value of a <code>double</code> value. If the argument is not negative,
* the argument is returned. If the argument is negative, the negation of the argument is
* returned. Special cases:
*
* <ul>
* <li>
* If the argument is positive zero or negative zero, the result is positive zero.
* </li>
* <li>
* If the argument is infinite, the result is positive infinity.
* </li>
* <li>
* If the argument is NaN, the result is NaN.
* </li>
* </ul>
*
* In other words, the result is the same as the value of the expression:
*
* <p>
* <code>Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)</code>
* </p>
*
* @param a the argument whose absolute value is to be determined
*
* @return the absolute value of the argument.
*/
public static double abs(double a) {
return Math.abs(a);
}
/**
* Returns the greater of two <code>int</code> values. That is, the result is the argument
* closer to the value of <code>Integer.MAX_VALUE</code>. If the arguments have the same
* value, the result is that same value.
*
* @param a an argument.
* @param b another argument.
*
* @return the larger of <code>a</code> and <code>b</code>.
*
* @see Long#MAX_VALUE
*/
public static int max(int a, int b) {
return Math.max(a, b);
}
/**
* Returns the greater of two <code>long</code> values. That is, the result is the argument
* closer to the value of <code>Long.MAX_VALUE</code>. If the arguments have the same value,
* the result is that same value.
*
* @param a an argument.
* @param b another argument.
*
* @return the larger of <code>a</code> and <code>b</code>.
*
* @see Long#MAX_VALUE
*/
public static long max(long a, long b) {
return Math.max(a, b);
}
/**
* Returns the greater of two <code>float</code> values. That is, the result is the argument
* closer to positive infinity. If the arguments have the same value, the result is that same
* value. If either value is NaN, then the result is NaN. Unlike the the numerical comparison
* operators, this method considers negative zero to be strictly smaller than positive zero.
* If one argument is positive zero and the other negative zero, the result is positive zero.
*
* @param a an argument.
* @param b another argument.
*
* @return the larger of <code>a</code> and <code>b</code>.
*/
public static float max(float a, float b) {
return Math.max(a, b);
}
/**
* Returns the greater of two <code>double</code> values. That is, the result is the argument
* closer to positive infinity. If the arguments have the same value, the result is that same
* value. If either value is NaN, then the result is NaN. Unlike the the numerical comparison
* operators, this method considers negative zero to be strictly smaller than positive zero.
* If one argument is positive zero and the other negative zero, the result is positive zero.
*
* @param a an argument.
* @param b another argument.
*
* @return the larger of <code>a</code> and <code>b</code>.
*/
public static double max(double a, double b) {
return Math.max(a, b);
}
/**
* Returns the smaller of two <code>int</code> values. That is, the result the argument closer
* to the value of <code>Integer.MIN_VALUE</code>. If the arguments have the same value, the
* result is that same value.
*
* @param a an argument.
* @param b another argument.
*
* @return the smaller of <code>a</code> and <code>b</code>.
*
* @see Long#MIN_VALUE
*/
public static int min(int a, int b) {
return Math.min(a, b);
}
/**
* Returns the smaller of two <code>long</code> values. That is, the result is the argument
* closer to the value of <code>Long.MIN_VALUE</code>. If the arguments have the same value,
* the result is that same value.
*
* @param a an argument.
* @param b another argument.
*
* @return the smaller of <code>a</code> and <code>b</code>.
*
* @see Long#MIN_VALUE
*/
public static long min(long a, long b) {
return Math.min(a, b);
}
/**
* Returns the smaller of two <code>float</code> values. That is, the result is the value
* closer to negative infinity. If the arguments have the same value, the result is that same
* value. If either value is NaN, then the result is NaN. Unlike the the numerical comparison
* operators, this method considers negative zero to be strictly smaller than positive zero.
* If one argument is positive zero and the other is negative zero, the result is negative
* zero.
*
* @param a an argument.
* @param b another argument.
*
* @return the smaller of <code>a</code> and <code>b.</code>
*/
public static float min(float a, float b) {
return Math.min(a, b);
}
/**
* Returns the smaller of two <code>double</code> values. That is, the result is the value
* closer to negative infinity. If the arguments have the same value, the result is that same
* value. If either value is NaN, then the result is NaN. Unlike the the numerical comparison
* operators, this method considers negative zero to be strictly smaller than positive zero.
* If one argument is positive zero and the other is negative zero, the result is negative
* zero.
*
* @param a an argument.
* @param b another argument.
*
* @return the smaller of <code>a</code> and <code>b</code>.
*/
public static double min(double a, double b) {
return Math.min(a, b);
}
public static boolean isPowerOfTwo(int intValue) {
if (intValue == 0) {
return false;
}
while ((intValue & 1) == 0) {
intValue = intValue >>> 1;
}
return intValue == 1;
}
public static boolean isPowerOfTwo(long longValue) {
if (longValue == 0L) {
return false;
}
while ((longValue & 1L) == 0L) {
longValue = longValue >>> 1;
}
return longValue == 1L;
}
public static boolean isPowerOfTwo(BigInteger bintValue) {
int bitIndex = bintValue.getLowestSetBit();
if (bitIndex < 0) {
return false;
}
return bintValue.clearBit(bitIndex).equals(BigInteger.ZERO);
}
}
| gpl-2.0 |
martinggww/Programming | XBRL/xbrl-api/module-api/src/main/java/org/xbrlapi/grabber/Grabber.java | 304 | package org.xbrlapi.grabber;
import java.net.URI;
import java.util.List;
/**
* Defines an XBRL grabber
* @author Geoff Shuetrim (geoff@galexy.net)
*/
public interface Grabber {
/**
* @return a list of URIs of XBRL resources provided
* by the source.
*/
public List<URI> getResources();
}
| gpl-2.0 |
BunnyWei/truffle-llvmir | graal/com.oracle.truffle.sl/src_gen/com/oracle/truffle/sl/builtins/SLNanoTimeBuiltinFactory.java | 3963 | /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// CheckStyle: start generated
package com.oracle.truffle.sl.builtins;
import com.oracle.truffle.api.dsl.GeneratedBy;
import com.oracle.truffle.api.dsl.NodeFactory;
import com.oracle.truffle.api.dsl.UnsupportedSpecializationException;
import com.oracle.truffle.api.dsl.internal.DSLMetadata;
import com.oracle.truffle.api.dsl.internal.NodeFactoryBase;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeCost;
import com.oracle.truffle.sl.nodes.SLExpressionNode;
import com.oracle.truffle.sl.runtime.SLContext;
@GeneratedBy(SLNanoTimeBuiltin.class)
public final class SLNanoTimeBuiltinFactory extends NodeFactoryBase<SLNanoTimeBuiltin> {
private static SLNanoTimeBuiltinFactory instance;
private SLNanoTimeBuiltinFactory() {
super(SLNanoTimeBuiltin.class, DSLMetadata.EMPTY_CLASS_ARRAY, new Class<?>[][] {new Class<?>[] {SLExpressionNode[].class, SLContext.class}});
}
@Override
public SLNanoTimeBuiltin createNode(Object... arguments) {
if (arguments.length == 2 && (arguments[0] == null || arguments[0] instanceof SLExpressionNode[]) && (arguments[1] == null || arguments[1] instanceof SLContext)) {
return create((SLExpressionNode[]) arguments[0], (SLContext) arguments[1]);
} else {
throw new IllegalArgumentException("Invalid create signature.");
}
}
public static NodeFactory<SLNanoTimeBuiltin> getInstance() {
if (instance == null) {
instance = new SLNanoTimeBuiltinFactory();
}
return instance;
}
public static SLNanoTimeBuiltin create(SLExpressionNode[] arguments, SLContext context) {
return new SLNanoTimeBuiltinNodeGen(arguments, context);
}
@GeneratedBy(SLNanoTimeBuiltin.class)
public static final class SLNanoTimeBuiltinNodeGen extends SLNanoTimeBuiltin {
private final SLContext context;
@SuppressWarnings("unused")
private SLNanoTimeBuiltinNodeGen(SLExpressionNode[] arguments, SLContext context) {
this.context = context;
}
@Override
public SLContext getContext() {
return this.context;
}
@Override
public Object executeGeneric(VirtualFrame frameValue) {
return executeLong(frameValue);
}
@Override
public long executeLong(VirtualFrame frameValue) {
return this.nanoTime();
}
@Override
public void executeVoid(VirtualFrame frameValue) {
executeLong(frameValue);
return;
}
@Override
public NodeCost getCost() {
return NodeCost.MONOMORPHIC;
}
protected UnsupportedSpecializationException unsupported() {
return new UnsupportedSpecializationException(this, new Node[] {});
}
}
}
| gpl-2.0 |
underplex/tickay | src/main/java/com/underplex/tickay/jaxb/StationChoiceEntry.java | 6131 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.01.21 at 12:18:56 PM EST
//
package com.underplex.tickay.jaxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import com.underplex.infowrap.InfoSource;
import com.underplex.tickay.jaxbinfo.StationChoiceEntryInfo;
/**
* <p>Java class for StationChoiceEntry complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="StationChoiceEntry">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="player" type="{}PlayerType"/>
* <element name="stationCity" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="noAvailableRoutes" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="availableRoutes" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="chosenRoute" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="error" type="{}StrategyErrorEntry" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "StationChoiceEntry", propOrder = {
"player",
"stationCity",
"noAvailableRoutes",
"availableRoutes",
"chosenRoute",
"error"
})
public class StationChoiceEntry implements InfoSource<StationChoiceEntryInfo>{
@XmlElement(required = true)
protected PlayerType player;
@XmlElement(required = true)
protected String stationCity;
protected Boolean noAvailableRoutes;
protected List<String> availableRoutes;
protected String chosenRoute;
protected StrategyErrorEntry error;
@XmlTransient
private StationChoiceEntryInfo info;
public StationChoiceEntry(){
this.info = new StationChoiceEntryInfo(this);
}
public StationChoiceEntryInfo info() {
return this.info;
}
/**
* Gets the value of the player property.
*
* @return
* possible object is
* {@link PlayerType }
*
*/
public PlayerType getPlayer() {
return player;
}
/**
* Sets the value of the player property.
*
* @param value
* allowed object is
* {@link PlayerType }
*
*/
public void setPlayer(PlayerType value) {
this.player = value;
}
/**
* Gets the value of the stationCity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStationCity() {
return stationCity;
}
/**
* Sets the value of the stationCity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStationCity(String value) {
this.stationCity = value;
}
/**
* Gets the value of the noAvailableRoutes property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNoAvailableRoutes() {
return noAvailableRoutes;
}
/**
* Sets the value of the noAvailableRoutes property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNoAvailableRoutes(Boolean value) {
this.noAvailableRoutes = value;
}
/**
* Gets the value of the availableRoutes property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the availableRoutes property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvailableRoutes().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAvailableRoutes() {
if (availableRoutes == null) {
availableRoutes = new ArrayList<String>();
}
return this.availableRoutes;
}
/**
* Gets the value of the chosenRoute property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChosenRoute() {
return chosenRoute;
}
/**
* Sets the value of the chosenRoute property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChosenRoute(String value) {
this.chosenRoute = value;
}
/**
* Gets the value of the error property.
*
* @return
* possible object is
* {@link StrategyErrorEntry }
*
*/
public StrategyErrorEntry getError() {
return error;
}
/**
* Sets the value of the error property.
*
* @param value
* allowed object is
* {@link StrategyErrorEntry }
*
*/
public void setError(StrategyErrorEntry value) {
this.error = value;
}
}
| gpl-2.0 |
niloc132/mauve-gwt | src/main/java/gnu/testlet/java/lang/ArrayIndexOutOfBoundsException/classInfo/getInterfaces.java | 1813 | // Test for method java.lang.ArrayIndexOutOfBoundsException.getClass().getInterfaces()
// Copyright (C) 2012, 2013 Pavel Tisnovsky <ptisnovs@redhat.com>
// This file is part of Mauve.
// Mauve is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
// Mauve is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street,
// Fifth Floor, Boston, MA 02110-1301 USA.
// Tags: JDK1.5
package gnu.testlet.java.lang.ArrayIndexOutOfBoundsException.classInfo;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.lang.ArrayIndexOutOfBoundsException;
import java.util.List;
import java.util.Arrays;
/**
* Test for method java.lang.ArrayIndexOutOfBoundsException.getClass().getInterfaces()
*/
public class getInterfaces implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
// create instance of a class ArrayIndexOutOfBoundsException
final Object o = new ArrayIndexOutOfBoundsException("java.lang.ArrayIndexOutOfBoundsException");
// get a runtime class of an object "o"
final Class c = o.getClass();
List interfaces = Arrays.asList(c.getInterfaces());
}
}
| gpl-2.0 |
danbornman/geospatial-iot | nationwide-geospatial-app/src/main/java/com/nationwide/listener/PropertiesListener.java | 2268 | package com.nationwide.listener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.nationwide.service.GeoServiceConnectionMngr;
public class PropertiesListener implements ServletContextListener {
private static Logger logger = Logger.getLogger(PropertiesListener.class.getName());
public static Map<String,String> applicationProperties = new HashMap<String,String>();
InputStream inputStream;
public void contextInitialized(ServletContextEvent servletContextListener){
// execute on Start up
logger.info("Application started!!!");
applicationProperties = loadProperties();
getGeoServiceCredentials();
}
public void getGeoServiceCredentials(){
GeoServiceConnectionMngr.initGeoService();
}
public Map<String,String> loadProperties(){
// access properties data and create a map object
Map<String, String> propertiesMap = new HashMap<String,String>();
try{
Properties props = new Properties();
String propFilename = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFilename);
if (inputStream != null){
props.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFilename + "' not found in the classpath");
}
Enumeration<?> e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = props.getProperty(key);
logger.info("Key : " + key + ", Value : " + value);
propertiesMap.put(key, value);
}
}
catch(IOException ex){
System.out.println("Properties file not found" + ex.getMessage());
}
return propertiesMap;
}
public void contextDestroyed(ServletContextEvent servletContextListener){
// execute on Shut down
}
/*
* Add this class to the web.xml
* <listener>
* <listener-class>
* com.nationwide.listener.PropertiesListener
* </listener-class>
* </listener>
*/
}
| gpl-2.0 |
smarr/GraalCompiler | graal/com.oracle.graal.loop/src/com/oracle/graal/loop/InductionVariable.java | 3711 | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.loop;
import jdk.internal.jvmci.common.JVMCIError;
import com.oracle.graal.compiler.common.type.Stamp;
import com.oracle.graal.nodes.StructuredGraph;
import com.oracle.graal.nodes.ValueNode;
/**
* This class describes a value node that is an induction variable in a counted loop.
*/
public abstract class InductionVariable {
public enum Direction {
Up,
Down;
public Direction opposite() {
switch (this) {
case Up:
return Down;
case Down:
return Up;
default:
throw JVMCIError.shouldNotReachHere();
}
}
}
public abstract StructuredGraph graph();
protected final LoopEx loop;
public InductionVariable(LoopEx loop) {
this.loop = loop;
}
public LoopEx getLoop() {
return loop;
}
public abstract Direction direction();
/**
* Returns the value node that is described by this induction variable.
*/
public abstract ValueNode valueNode();
/**
* Returns the node that gives the initial value of this induction variable.
*/
public abstract ValueNode initNode();
/**
* Returns the stride of the induction variable. The stride is the value that is added to the
* induction variable at each iteration.
*/
public abstract ValueNode strideNode();
public abstract boolean isConstantInit();
public abstract boolean isConstantStride();
public abstract long constantInit();
public abstract long constantStride();
/**
* Returns the extremum value of the induction variable. The extremum value is the value of the
* induction variable in the loop body of the last iteration, only taking into account the main
* loop limit test. It's possible for the loop to exit before this value if
* {@link CountedLoopInfo#isExactTripCount()} returns false for the containing loop.
*/
public ValueNode extremumNode() {
return extremumNode(false, valueNode().stamp());
}
public abstract ValueNode extremumNode(boolean assumePositiveTripCount, Stamp stamp);
public abstract boolean isConstantExtremum();
public abstract long constantExtremum();
/**
* Returns the exit value of the induction variable. The exit value is the value of the
* induction variable at the loop exit.
*/
public abstract ValueNode exitValueNode();
/**
* Deletes any nodes created within the scope of this object that have no usages.
*/
public abstract void deleteUnusedNodes();
}
| gpl-2.0 |
arronvera/MyBlog | app/src/main/java/code/vera/myblog/bean/CollectionBean.java | 1270 | package code.vera.myblog.bean;
import com.alibaba.fastjson.JSON;
import java.util.List;
/**
* Created by vera on 2017/4/12 0012.
*/
public class CollectionBean {
private String status;
private String tags;
private String favorited_time;
private StatusesBean statusesBean;
private List<CollectionTagBean> tagBeanList;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getFavorited_time() {
return favorited_time;
}
public void setFavorited_time(String favorited_time) {
this.favorited_time = favorited_time;
}
public StatusesBean getStatusesBean() {
return JSON.parseObject(status,StatusesBean.class);
}
public void setStatusesBean(StatusesBean statusesBean) {
this.statusesBean = statusesBean;
}
public List<CollectionTagBean> getTagBeanList() {
return JSON.parseArray(tags,CollectionTagBean.class);
}
public void setTagBeanList(List<CollectionTagBean> tagBeanList) {
this.tagBeanList = tagBeanList;
}
}
| gpl-2.0 |
PersonalBigDataAnalyticsTeam/myPersonalBusiness | src/org/solinari/server/driver/sina/SinaHistoryServer.java | 3635 | /**
*
*/
package org.solinari.server.driver.sina;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author solinari
* 从sina获取原始历史数据网页
*/
public class SinaHistoryServer {
private static final Log LOG = LogFactory.getLog(SinaHistoryServer.class);
private final static String SINA_HISTORY_URL = "http://biz.finance.sina.com.cn/stock/flash_hq/kline_data.php?&symbol=";
// final String sinaHistoryUrl = "http://biz.finance.sina.com.cn/stock/flash_hq/kline_data.php?&rand=random(10000)&symbol=";
// /*+ "sz002241&" + "end_date=20130806&begin_date=20130101&type=plain";*/
/*
* 根据stock的代码和启示抓取日期,生成HTTP访问的URL,抓取的时间是从begindate到当前为止
* code stock代码
* begindate时间类型,抓取的起始日期,截止日期为now
*/
private String setHttpUrl(String code, Date begindate){
Date date=new Date(); //取时间
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
//calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
date=calendar.getTime(); //这个时间就是日期往后推一天的结果
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String dateString = formatter.format(date);
String url = SINA_HISTORY_URL + code + "&end_date=" + dateString +
"&begin_date=" + formatter.format(begindate) + "&type=plain";
return url;
}
/*
* 抓取对应stock的历史数据信息
* code stock的代码
* begindate 抓取的起始时间,抓取时间阶段为begindate到now
*/
public String getStockHistoryInfo(String code, Date begindate) {
String result = null;
try {
URL url = new URL(setHttpUrl(code, begindate));
byte[] buffer = new byte[256];
InputStream inputstream = null;
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
try {
inputstream = url.openStream();
int i;
while ((i = inputstream.read(buffer)) != -1) {
outputstream.write(buffer, 0, i);
}
result = outputstream.toString();
outputstream.reset();
inputstream.close();
LOG.debug("catch sina history stock info success code: " + code);
}
catch (Exception e) {
LOG.error("catch sina history stock info failed error: " + e.getMessage());
inputstream.close();
}
finally {
if (inputstream != null) {
inputstream.close();
}
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
return result;
}
/*
public void getStockHistoryInfo() {
try{
URL url=new URL(add);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();//建立连接
int code=connection.getResponseCode();
if(code!=HttpURLConnection.HTTP_OK){
log.error("连接资源错误!");
}
else{
DataInputStream in=new DataInputStream(connection.getInputStream());//获得输入流
File file=new File(path);
RandomAccessFile rafile=new RandomAccessFile(file,"rw");//建立随机读写文件
byte[] buf=new byte[1024];
int num=in.read(buf);
while(num!=-1){
rafile.write(buf,0,buf.length);
rafile.skipBytes(num);
num=in.read(buf);
System.out.println(buf.toString());
}
log.error("Complete!");
}
}
catch(Exception e){
log.error("Http error!!");
}
}*/
}
| gpl-2.0 |
LususAnimat/tiled | util/java/libtiled-java/src/tiled/io/TMXMapReader.java | 35901 | /*
* Copyright 2004-2010, Thorbjørn Lindeijer <thorbjorn@lindeijer.nl>
* Copyright 2004-2006, Adam Turk <aturk@biggeruniverse.com>
*
* This file is part of libtiled-java.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tiled.io;
import java.awt.Color;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.geom.Ellipse2D;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import tiled.core.AnimatedTile;
import tiled.core.Map;
import tiled.core.MapLayer;
import tiled.core.MapObject;
import tiled.core.ObjectGroup;
import tiled.core.Tile;
import tiled.core.TileLayer;
import tiled.core.TileSet;
import tiled.util.Base64;
import tiled.util.BasicTileCutter;
import tiled.util.ImageHelper;
/**
* The standard map reader for TMX files. Supports reading .tmx, .tmx.gz and *.tsx files.
*/
public class TMXMapReader
{
private Map map;
private String xmlPath;
private String error;
private final EntityResolver entityResolver = new MapEntityResolver();
private TreeMap<Integer, TileSet> tilesetPerFirstGid;
public final TMXMapReaderSettings settings = new TMXMapReaderSettings();
private final HashMap<String, TileSet> cachedTilesets = new HashMap<String, TileSet>();
public static final class TMXMapReaderSettings {
public boolean reuseCachedTilesets = false;
}
public TMXMapReader() {
}
String getError() {
return error;
}
private static String makeUrl(String filename) throws MalformedURLException {
final String url;
if (filename.indexOf("://") > 0 || filename.startsWith("file:")) {
url = filename;
} else {
url = new File(filename).toURI().toString();
}
return url;
}
private static int reflectFindMethodByName(Class c, String methodName) {
Method[] methods = c.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equalsIgnoreCase(methodName)) {
return i;
}
}
return -1;
}
private void reflectInvokeMethod(Object invokeVictim, Method method,
String[] args) throws Exception
{
Class[] parameterTypes = method.getParameterTypes();
Object[] conformingArguments = new Object[parameterTypes.length];
if (args.length < parameterTypes.length) {
throw new Exception("Insufficient arguments were supplied");
}
for (int i = 0; i < parameterTypes.length; i++) {
if ("int".equalsIgnoreCase(parameterTypes[i].getName())) {
conformingArguments[i] = new Integer(args[i]);
} else if ("float".equalsIgnoreCase(parameterTypes[i].getName())) {
conformingArguments[i] = new Float(args[i]);
} else if (parameterTypes[i].getName().endsWith("String")) {
conformingArguments[i] = args[i];
} else if ("boolean".equalsIgnoreCase(parameterTypes[i].getName())) {
conformingArguments[i] = Boolean.valueOf(args[i]);
} else {
// Unsupported argument type, defaulting to String
conformingArguments[i] = args[i];
}
}
method.invoke(invokeVictim,conformingArguments);
}
private void setOrientation(String o) {
if ("isometric".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_ISOMETRIC);
} else if ("orthogonal".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_ORTHOGONAL);
} else if ("hexagonal".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_HEXAGONAL);
} else if ("shifted".equalsIgnoreCase(o)) {
map.setOrientation(Map.ORIENTATION_SHIFTED);
} else {
System.out.println("Unknown orientation '" + o + "'");
}
}
private static String getAttributeValue(Node node, String attribname) {
final NamedNodeMap attributes = node.getAttributes();
String value = null;
if (attributes != null) {
Node attribute = attributes.getNamedItem(attribname);
if (attribute != null) {
value = attribute.getNodeValue();
}
}
return value;
}
private static int getAttribute(Node node, String attribname, int def) {
final String attr = getAttributeValue(node, attribname);
if (attr != null) {
return Integer.parseInt(attr);
} else {
return def;
}
}
private Object unmarshalClass(Class reflector, Node node)
throws InstantiationException, IllegalAccessException,
InvocationTargetException {
Constructor cons = null;
try {
cons = reflector.getConstructor((Class[]) null);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
return null;
}
Object o = cons.newInstance((Object[]) null);
Node n;
Method[] methods = reflector.getMethods();
NamedNodeMap nnm = node.getAttributes();
if (nnm != null) {
for (int i = 0; i < nnm.getLength(); i++) {
n = nnm.item(i);
try {
int j = reflectFindMethodByName(reflector,
"set" + n.getNodeName());
if (j >= 0) {
reflectInvokeMethod(o,methods[j],
new String [] {n.getNodeValue()});
} else {
System.out.println("Unsupported attribute '" +
n.getNodeName() + "' on <" +
node.getNodeName() + "> tag");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return o;
}
private Image unmarshalImage(Node t, String baseDir) throws IOException
{
Image img = null;
String source = getAttributeValue(t, "source");
if (source != null) {
if (checkRoot(source)) {
source = makeUrl(source);
} else {
source = makeUrl(baseDir + source);
}
img = ImageIO.read(new URL(source));
} else {
NodeList nl = t.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if ("data".equals(node.getNodeName())) {
Node cdata = node.getFirstChild();
if (cdata != null) {
String sdata = cdata.getNodeValue();
char[] charArray = sdata.trim().toCharArray();
byte[] imageData = Base64.decode(charArray);
img = ImageHelper.bytesToImage(imageData);
// Deriving a scaled instance, even if it has the same
// size, somehow makes drawing of the tiles a lot
// faster on various systems (seen on Linux, Windows
// and MacOS X).
img = img.getScaledInstance(
img.getWidth(null), img.getHeight(null),
Image.SCALE_FAST);
}
break;
}
}
}
return img;
}
private TileSet unmarshalTilesetFile(InputStream in, String filename)
throws Exception
{
TileSet set = null;
Node tsNode;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
//builder.setErrorHandler(new XMLErrorHandler());
Document tsDoc = builder.parse(in, ".");
String xmlPathSave = xmlPath;
if (filename.indexOf(File.separatorChar) >= 0) {
xmlPath = filename.substring(0,
filename.lastIndexOf(File.separatorChar) + 1);
}
NodeList tsNodeList = tsDoc.getElementsByTagName("tileset");
// There can be only one tileset in a .tsx file.
tsNode = tsNodeList.item(0);
if (tsNode != null) {
set = unmarshalTileset(tsNode);
if (set.getSource() != null) {
System.out.println("Recursive external tilesets are not supported.");
}
set.setSource(filename);
}
xmlPath = xmlPathSave;
} catch (SAXException e) {
error = "Failed while loading " + filename + ": " +
e.getLocalizedMessage();
}
return set;
}
private TileSet unmarshalTileset(Node t) throws Exception {
String source = getAttributeValue(t, "source");
String basedir = getAttributeValue(t, "basedir");
int firstGid = getAttribute(t, "firstgid", 1);
String tilesetBaseDir = xmlPath;
if (basedir != null) {
tilesetBaseDir = basedir; //makeUrl(basedir);
}
if (source != null) {
String filename = tilesetBaseDir + source;
//if (checkRoot(source)) {
// filename = makeUrl(source);
//}
TileSet ext = null;
try {
InputStream in = new URL(makeUrl(filename)).openStream();
ext = unmarshalTilesetFile(in, filename);
setFirstGidForTileset(ext, firstGid);
} catch (FileNotFoundException fnf) {
error = "Could not find external tileset file " + filename;
}
if (ext == null) {
error = "Tileset " + source + " was not loaded correctly!";
}
return ext;
}
else {
final int tileWidth = getAttribute(t, "tilewidth", map != null ? map.getTileWidth() : 0);
final int tileHeight = getAttribute(t, "tileheight", map != null ? map.getTileHeight() : 0);
final int tileSpacing = getAttribute(t, "spacing", 0);
final int tileMargin = getAttribute(t, "margin", 0);
final String name = getAttributeValue(t, "name");
TileSet set;
if (settings.reuseCachedTilesets) {
set = cachedTilesets.get(name);
if (set != null) {
setFirstGidForTileset(set, firstGid);
return set;
}
set = new TileSet();
cachedTilesets.put(name, set);
} else {
set = new TileSet();
}
set.setName(name);
set.setBaseDir(basedir);
setFirstGidForTileset(set, firstGid);
boolean hasTilesetImage = false;
NodeList children = t.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeName().equalsIgnoreCase("image")) {
if (hasTilesetImage) {
System.out.println("Ignoring illegal image element after tileset image.");
continue;
}
String imgSource = getAttributeValue(child, "source");
String transStr = getAttributeValue(child, "trans");
if (imgSource != null) {
// Not a shared image, but an entire set in one image
// file. There should be only one image element in this
// case.
hasTilesetImage = true;
// FIXME: importTileBitmap does not fully support URLs
String sourcePath = imgSource;
if (! new File(imgSource).isAbsolute()) {
sourcePath = tilesetBaseDir + imgSource;
}
if (transStr != null) {
if (transStr.startsWith("#"))
transStr = transStr.substring(1);
int colorInt = Integer.parseInt(transStr, 16);
Color color = new Color(colorInt);
set.setTransparentColor(color);
}
set.importTileBitmap(sourcePath, new BasicTileCutter(
tileWidth, tileHeight, tileSpacing, tileMargin));
}
}
else if (child.getNodeName().equalsIgnoreCase("tile")) {
Tile tile = unmarshalTile(set, child, tilesetBaseDir);
if (!hasTilesetImage || tile.getId() > set.getMaxTileId()) {
set.addTile(tile);
} else {
Tile myTile = set.getTile(tile.getId());
myTile.setProperties(tile.getProperties());
//TODO: there is the possibility here of overlaying images,
// which some people may want
}
}
}
return set;
}
}
private MapObject readMapObject(Node t) throws Exception {
final String name = getAttributeValue(t, "name");
final String type = getAttributeValue(t, "type");
final String gid = getAttributeValue(t, "gid");
final int x = getAttribute(t, "x", 0);
final int y = getAttribute(t, "y", 0);
final int width = getAttribute(t, "width", 0);
final int height = getAttribute(t, "height", 0);
MapObject obj = new MapObject(x, y, width, height);
obj.setShape(obj.getBounds());
if (name != null)
obj.setName(name);
if (type != null)
obj.setType(type);
if (gid != null){
Tile tile = getTileForTileGID(Integer.parseInt(gid));
obj.setTile(tile);
}
NodeList children = t.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("image".equalsIgnoreCase(child.getNodeName())) {
String source = getAttributeValue(child, "source");
if (source != null) {
if (! new File(source).isAbsolute()) {
source = xmlPath + source;
}
obj.setImageSource(source);
}
break;
} else if ("ellipse".equalsIgnoreCase(child.getNodeName())) {
obj.setShape(new Ellipse2D.Double(x, y, width, height));
} else if ("polygon".equalsIgnoreCase(child.getNodeName()) || "polyline".equalsIgnoreCase(child.getNodeName())) {
Polygon shape = new Polygon();
final String pointsAttribute = getAttributeValue(child, "points");
StringTokenizer st = new StringTokenizer(pointsAttribute, ", ");
while (st.hasMoreElements()) {
shape.addPoint(x + Integer.parseInt(st.nextToken()), y + Integer.parseInt(st.nextToken()));
}
obj.setShape(shape);
obj.setBounds(shape.getBounds());
}
}
Properties props = new Properties();
readProperties(children, props);
obj.setProperties(props);
return obj;
}
/**
* Reads properties from amongst the given children. When a "properties"
* element is encountered, it recursively calls itself with the children
* of this node. This function ensures backward compatibility with tmx
* version 0.99a.
*
* Support for reading property values stored as character data was added
* in Tiled 0.7.0 (tmx version 0.99c).
*
* @param children the children amongst which to find properties
* @param props the properties object to set the properties of
*/
private static void readProperties(NodeList children, Properties props) {
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("property".equalsIgnoreCase(child.getNodeName())) {
final String key = getAttributeValue(child, "name");
String value = getAttributeValue(child, "value");
if (value == null) {
Node grandChild = child.getFirstChild();
if (grandChild != null) {
value = grandChild.getNodeValue();
if (value != null)
value = value.trim();
}
}
if (value != null)
props.setProperty(key, value);
}
else if ("properties".equals(child.getNodeName())) {
readProperties(child.getChildNodes(), props);
}
}
}
private Tile unmarshalTile(TileSet set, Node t, String baseDir)
throws Exception
{
Tile tile = null;
NodeList children = t.getChildNodes();
boolean isAnimated = false;
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("animation".equalsIgnoreCase(child.getNodeName())) {
isAnimated = true;
break;
}
}
try {
if (isAnimated) {
tile = (Tile) unmarshalClass(AnimatedTile.class, t);
} else {
tile = (Tile) unmarshalClass(Tile.class, t);
}
} catch (Exception e) {
error = "Failed creating tile: " + e.getLocalizedMessage();
return tile;
}
tile.setTileSet(set);
readProperties(children, tile.getProperties());
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("image".equalsIgnoreCase(child.getNodeName())) {
Image img = unmarshalImage(child, baseDir);
tile.setImage(img);
} else if ("animation".equalsIgnoreCase(child.getNodeName())) {
// TODO: fill this in once TMXMapWriter is complete
}
}
return tile;
}
private MapLayer unmarshalObjectGroup(Node t) throws Exception {
ObjectGroup og = null;
try {
og = (ObjectGroup)unmarshalClass(ObjectGroup.class, t);
} catch (Exception e) {
e.printStackTrace();
return og;
}
final int offsetX = getAttribute(t, "x", 0);
final int offsetY = getAttribute(t, "y", 0);
og.setOffset(offsetX, offsetY);
// Add all objects from the objects group
NodeList children = t.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("object".equalsIgnoreCase(child.getNodeName())) {
og.addObject(readMapObject(child));
}
}
Properties props = new Properties();
readProperties(children, props);
og.setProperties(props);
return og;
}
/**
* Loads a map layer from a layer node.
* @param t the node representing the "layer" element
* @return the loaded map layer
* @throws Exception
*/
private MapLayer readLayer(Node t) throws Exception {
final int layerWidth = getAttribute(t, "width", map.getWidth());
final int layerHeight = getAttribute(t, "height", map.getHeight());
TileLayer ml = new TileLayer(layerWidth, layerHeight);
final int offsetX = getAttribute(t, "x", 0);
final int offsetY = getAttribute(t, "y", 0);
final int visible = getAttribute(t, "visible", 1);
String opacity = getAttributeValue(t, "opacity");
ml.setName(getAttributeValue(t, "name"));
if (opacity != null) {
ml.setOpacity(Float.parseFloat(opacity));
}
readProperties(t.getChildNodes(), ml.getProperties());
for (Node child = t.getFirstChild(); child != null;
child = child.getNextSibling())
{
String nodeName = child.getNodeName();
if ("data".equalsIgnoreCase(nodeName)) {
String encoding = getAttributeValue(child, "encoding");
String comp = getAttributeValue(child, "compression");
if ("base64".equalsIgnoreCase(encoding)) {
Node cdata = child.getFirstChild();
if (cdata != null) {
char[] enc = cdata.getNodeValue().trim().toCharArray();
byte[] dec = Base64.decode(enc);
ByteArrayInputStream bais = new ByteArrayInputStream(dec);
InputStream is;
if ("gzip".equalsIgnoreCase(comp)) {
final int len = layerWidth * layerHeight * 4;
is = new GZIPInputStream(bais, len);
} else if ("zlib".equalsIgnoreCase(comp)) {
is = new InflaterInputStream(bais);
} else if (comp != null && !comp.isEmpty()) {
throw new IOException("Unrecognized compression method \"" + comp + "\" for map layer " + ml.getName());
} else {
is = bais;
}
for (int y = 0; y < ml.getHeight(); y++) {
for (int x = 0; x < ml.getWidth(); x++) {
int tileId = 0;
tileId |= is.read();
tileId |= is.read() << 8;
tileId |= is.read() << 16;
tileId |= is.read() << 24;
setTileAtFromTileId(ml, y, x, tileId);
}
}
}
} else if ("csv".equalsIgnoreCase(encoding)) {
String csvText = child.getTextContent();
if (comp != null && !comp.isEmpty()) {
throw new IOException("Unrecognized compression method \"" + comp + "\" for map layer " + ml.getName() + " and encoding " + encoding);
}
String[] csvTileIds = csvText
.trim() // trim 'space', 'tab', 'newline'. pay attention to additional unicode chars like \u2028, \u2029, \u0085 if necessary
.split("[\\s]*,[\\s]*");
if (csvTileIds.length != ml.getHeight() * ml.getWidth()) {
throw new IOException("Number of tiles does not match the layer's width and height");
}
for (int y = 0; y < ml.getHeight(); y++) {
for (int x = 0; x < ml.getWidth(); x++) {
String sTileId = csvTileIds[x + y * ml.getHeight()];
int tileId = Integer.parseInt(sTileId);
setTileAtFromTileId(ml, y, x, tileId);
}
}
} else {
int x = 0, y = 0;
for (Node dataChild = child.getFirstChild();
dataChild != null;
dataChild = dataChild.getNextSibling())
{
if ("tile".equalsIgnoreCase(dataChild.getNodeName())) {
int tileId = getAttribute(dataChild, "gid", -1);
setTileAtFromTileId(ml, y, x, tileId);
x++;
if (x == ml.getWidth()) {
x = 0; y++;
}
if (y == ml.getHeight()) { break; }
}
}
}
} else if ("tileproperties".equalsIgnoreCase(nodeName)) {
for (Node tpn = child.getFirstChild();
tpn != null;
tpn = tpn.getNextSibling())
{
if ("tile".equalsIgnoreCase(tpn.getNodeName())) {
int x = getAttribute(tpn, "x", -1);
int y = getAttribute(tpn, "y", -1);
Properties tip = new Properties();
readProperties(tpn.getChildNodes(), tip);
ml.setTileInstancePropertiesAt(x, y, tip);
}
}
}
}
// This is done at the end, otherwise the offset is applied during
// the loading of the tiles.
ml.setOffset(offsetX, offsetY);
// Invisible layers are automatically locked, so it is important to
// set the layer to potentially invisible _after_ the layer data is
// loaded.
// todo: Shouldn't this be just a user interface feature, rather than
// todo: something to keep in mind at this level?
ml.setVisible(visible == 1);
return ml;
}
/**
* Helper method to set the tile based on its global id.
* @param ml tile layer
* @param y y-coordinate
* @param x x-coordinate
* @param tileId global id of the tile as read from the file
*/
private void setTileAtFromTileId(TileLayer ml, int y, int x, int tileId) {
ml.setTileAt(x, y, getTileForTileGID(tileId));
}
/**
* Helper method to get the tile based on its global id
* @param tileId global id of the tile
* @return <ul><li>{@link Tile} object corresponding to the global id, if found</li><li><code>null</code>, otherwise</li></ul>
*/
private Tile getTileForTileGID(int tileId) {
Tile tile = null;
java.util.Map.Entry<Integer, TileSet> ts = findTileSetForTileGID(tileId);
if (ts != null) {
tile = ts.getValue().getTile(tileId - ts.getKey());
}
return tile;
}
private void buildMap(Document doc) throws Exception {
Node item, mapNode;
mapNode = doc.getDocumentElement();
if (!"map".equals(mapNode.getNodeName())) {
throw new Exception("Not a valid tmx map file.");
}
// Get the map dimensions and create the map
int mapWidth = getAttribute(mapNode, "width", 0);
int mapHeight = getAttribute(mapNode, "height", 0);
if (mapWidth > 0 && mapHeight > 0) {
map = new Map(mapWidth, mapHeight);
} else {
// Maybe this map is still using the dimensions element
NodeList l = doc.getElementsByTagName("dimensions");
for (int i = 0; (item = l.item(i)) != null; i++) {
if (item.getParentNode() == mapNode) {
mapWidth = getAttribute(item, "width", 0);
mapHeight = getAttribute(item, "height", 0);
if (mapWidth > 0 && mapHeight > 0) {
map = new Map(mapWidth, mapHeight);
}
}
}
}
if (map == null) {
throw new Exception("Couldn't locate map dimensions.");
}
// Load other map attributes
String orientation = getAttributeValue(mapNode, "orientation");
int tileWidth = getAttribute(mapNode, "tilewidth", 0);
int tileHeight = getAttribute(mapNode, "tileheight", 0);
if (tileWidth > 0) {
map.setTileWidth(tileWidth);
}
if (tileHeight > 0) {
map.setTileHeight(tileHeight);
}
if (orientation != null) {
setOrientation(orientation);
} else {
setOrientation("orthogonal");
}
// Load properties
readProperties(mapNode.getChildNodes(), map.getProperties());
// Load tilesets first, in case order is munged
tilesetPerFirstGid = new TreeMap<Integer, TileSet>();
NodeList l = doc.getElementsByTagName("tileset");
for (int i = 0; (item = l.item(i)) != null; i++) {
map.addTileset(unmarshalTileset(item));
}
// Load the layers and objectgroups
for (Node sibs = mapNode.getFirstChild(); sibs != null;
sibs = sibs.getNextSibling())
{
if ("layer".equals(sibs.getNodeName())) {
MapLayer layer = readLayer(sibs);
if (layer != null) {
map.addLayer(layer);
}
}
else if ("objectgroup".equals(sibs.getNodeName())) {
MapLayer layer = unmarshalObjectGroup(sibs);
if (layer != null) {
map.addLayer(layer);
}
}
}
tilesetPerFirstGid = null;
}
private Map unmarshal(InputStream in) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc;
try {
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(entityResolver);
InputSource insrc = new InputSource(in);
insrc.setSystemId(xmlPath);
insrc.setEncoding("UTF-8");
doc = builder.parse(insrc);
} catch (SAXException e) {
e.printStackTrace();
throw new Exception("Error while parsing map file: " +
e.toString());
}
buildMap(doc);
return map;
}
public Map readMap(String filename) throws Exception {
xmlPath = filename.substring(0,
filename.lastIndexOf(File.separatorChar) + 1);
String xmlFile = makeUrl(filename);
//xmlPath = makeUrl(xmlPath);
URL url = new URL(xmlFile);
InputStream is = url.openStream();
// Wrap with GZIP decoder for .tmx.gz files
if (filename.endsWith(".gz")) {
is = new GZIPInputStream(is);
}
Map unmarshalledMap = unmarshal(is);
unmarshalledMap.setFilename(filename);
map = null;
return unmarshalledMap;
}
public Map readMap(InputStream in) throws Exception {
xmlPath = makeUrl(".");
Map unmarshalledMap = unmarshal(in);
//unmarshalledMap.setFilename(xmlFile)
//
return unmarshalledMap;
}
public TileSet readTileset(String filename) throws Exception {
String xmlFile = filename;
xmlPath = filename.substring(0,
filename.lastIndexOf(File.separatorChar) + 1);
xmlFile = makeUrl(xmlFile);
xmlPath = makeUrl(xmlPath);
URL url = new URL(xmlFile);
return unmarshalTilesetFile(url.openStream(), filename);
}
public TileSet readTileset(InputStream in) throws Exception {
return unmarshalTilesetFile(in, ".");
}
public boolean accept(File pathName) {
try {
String path = pathName.getCanonicalPath();
if (path.endsWith(".tmx") || path.endsWith(".tsx") ||
path.endsWith(".tmx.gz")) {
return true;
}
} catch (IOException e) {}
return false;
}
private class MapEntityResolver implements EntityResolver
{
public InputSource resolveEntity(String publicId, String systemId) {
if (systemId.equals("http://mapeditor.org/dtd/1.0/map.dtd")) {
return new InputSource(TMXMapReader.class.getResourceAsStream(
"resources/map.dtd"));
}
return null;
}
}
/**
* This utility function will check the specified string to see if it
* starts with one of the OS root designations. (Ex.: '/' on Unix, 'C:' on
* Windows)
*
* @param filename a filename to check for absolute or relative path
* @return <code>true</code> if the specified filename starts with a
* filesystem root, <code>false</code> otherwise.
*/
public static boolean checkRoot(String filename) {
File[] roots = File.listRoots();
for (File root : roots) {
try {
String canonicalRoot = root.getCanonicalPath().toLowerCase();
if (filename.toLowerCase().startsWith(canonicalRoot)) {
return true;
}
} catch (IOException e) {
// Do we care?
}
}
return false;
}
/**
* Get the tile set and its corresponding firstgid that matches the given
* global tile id.
*
*
* @param gid a global tile id
* @return the tileset containing the tile with the given global tile id,
* or <code>null</code> when no such tileset exists
*/
private java.util.Map.Entry<Integer, TileSet> findTileSetForTileGID(int gid) {
return tilesetPerFirstGid.floorEntry(gid);
}
private void setFirstGidForTileset(TileSet tileset, int firstGid) {
tilesetPerFirstGid.put(firstGid, tileset);
}
}
| gpl-2.0 |
joshmoore/zeroc-ice | java/demo/book/map_filesystem/Client.java | 1237 | // **********************************************************************
//
// Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
import Filesystem.*;
public class Client extends Ice.Application
{
public int
run(String[] args)
{
//
// Terminate cleanly on receipt of a signal.
//
shutdownOnInterrupt();
//
// Create a proxy for the root directory
//
DirectoryPrx rootDir = DirectoryPrxHelper.checkedCast(communicator().propertyToProxy("RootDir.Proxy"));
if(rootDir == null)
{
throw new Error("Client: invalid proxy");
}
Parser p = new Parser(rootDir);
return p.parse();
}
static public void
main(String[] args)
{
Client app = new Client();
app.main("demo.book.map_filesystem.Client", args, "config.client");
}
static private class Error extends RuntimeException
{
public Error(String msg)
{
super(msg);
}
}
}
| gpl-2.0 |
Milton89/androidsipservice | comp-sipstack/src/main/java/com/colibria/android/sipservice/sip/tx/TransactionCondition.java | 7754 | /*
*
* Copyright (C) 2010 Colibria AS
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.colibria.android.sipservice.sip.tx;
import com.colibria.android.sipservice.fsm.Condition;
import com.colibria.android.sipservice.sip.messages.Ack;
import com.colibria.android.sipservice.sip.messages.Invite;
/**
*/
public class TransactionCondition extends Condition<Signal, TransactionBase> {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return false;
}
static final TransactionCondition C_REQUEST = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.request;
}
};
static final TransactionCondition C_INVITE = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.request &&
Invite.NAME.equals(signal.getMethod().toString());
}
};
static final TransactionCondition C_NON_INVITE_REQUEST = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.request &&
!Invite.NAME.equals(signal.getMethod().toString());
}
};
static final TransactionCondition C_ACK = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.request &&
Ack.NAME.equals(signal.getMethod().toString());
}
};
static final TransactionCondition C_ACK_KILL = new TransactionCondition() {
@Override
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.ackKill;
}
};
static final TransactionCondition C_XXX_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response;
}
};
static final TransactionCondition C_2XX_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response &&
(signal.getStatusCode() >= 200 && signal.getStatusCode() < 300);
}
};
static final TransactionCondition C_PROV_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response &&
(signal.getStatusCode() >= 100 && signal.getStatusCode() < 200);
}
};
static final TransactionCondition C_101_199_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response &&
(signal.getStatusCode() >= 101 && signal.getStatusCode() < 200);
}
};
static final TransactionCondition C_200_699_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response &&
(signal.getStatusCode() >= 200 && signal.getStatusCode() < 700);
}
};
static final TransactionCondition C_300_699_RESP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.response &&
(signal.getStatusCode() >= 300 && signal.getStatusCode() < 700);
}
};
static final TransactionCondition C_TIMER_A_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.A;
}
};
static final TransactionCondition C_TIMER_B_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.B;
}
};
static final TransactionCondition C_TIMER_D_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.D;
}
};
static final TransactionCondition C_TIMER_E_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.E;
}
};
static final TransactionCondition C_TIMER_F_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.F;
}
};
static final TransactionCondition C_TIMER_G_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.G;
}
};
static final TransactionCondition C_TIMER_H_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.H;
}
};
static final TransactionCondition C_TIMER_I_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.I;
}
};
static final TransactionCondition C_TIMER_J_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.J;
}
};
static final TransactionCondition C_TIMER_K_EXP = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return signal.getType() == Signal.Type.timeout &&
signal.getTimer() == TimerID.K;
}
};
static final TransactionCondition C_ANY = new TransactionCondition() {
public boolean satisfiedBy(Signal signal, TransactionBase transactionBase) {
return true;
}
};
}
| gpl-2.0 |
hhannu/FXAddressBook | src/fxaddressbook/UserData.java | 1794 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fxaddressbook;
import java.io.Serializable;
/**
*
* @author hth
*/
public class UserData implements Serializable, Comparable {
private String firstName, lastName, address, phone, email;
public UserData(String fname, String lname, String address, String phone, String email) {
this.address = address;
this.firstName = fname;
this.lastName = lname;
this.phone = phone;
this.email = email;
}
public String getName() {
String name = firstName + " " + lastName;
return name.trim();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
this.firstName = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String name) {
this.lastName = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/**
* Compares the names of userdata objects.
* This allows to sort a list of userdatas by name.
* @param o
* @return
*/
@Override
public int compareTo(Object o) {
UserData ud = (UserData)o;
return this.getName().compareTo(ud.getName());
}
}
| gpl-2.0 |
Knux14/SnapDesk | src/main/java/com/habosa/javasnap/Message.java | 6100 | package com.habosa.javasnap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by James on 2014-06-17.
*/
public class Message implements JSONBinder<Message> {
/**
* Types of Message.
*/
private final static String TYPE_MEDIA = "media";
private final static String TYPE_TEXT = "text";
/**
* Paths for various inner json objects.
*/
private final static String HEADER_KEY = "header";
private final static String BODY_KEY = "body";
private final static String MEDIA_KEY = "media"; //Only exist for media
/**
* Various key to get specific informations
*/
private final static String CHAT_MESSAGE_ID = "chat_message_id"; //Same as media_id
private final static String ID_KEY = "id";
private final static String FROM_KEY = "from";
private final static String TO_KEY = "to";
private final static String WIDTH_KEY = "width"; //Only exist for media
private final static String HEIGHT_KEY = "height"; //Only exist for media
private final static String IV_KEY = "iv"; //Only exist for media
private final static String KEY_KEY = "key"; //Only exist for media
private final static String MEDIA_ID_KEY = "media_id"; //Only exist for media. Same as chat_message_id
private final static String TEXT_KEY = "text";
private final static String TYPE_KEY = "type";
private final static String TIMESTAMP_KEY = "timestamp";
/**
* Local variables
*/
private String sender;
private List<String> recipients;
private String chat_message_id;
private String id;
private String media_id;
private int width;
private int height;
private String key;
private String iv;
private String type;
private long sent_time;
private String text;
@Override
public Message bind(JSONObject obj) {
try{
//Inner json objects
JSONObject header = obj.getJSONObject(HEADER_KEY);
JSONObject body = obj.getJSONObject(BODY_KEY);
//Root
this.chat_message_id = obj.getString(CHAT_MESSAGE_ID);
this.id = obj.getString(ID_KEY);
this.sent_time = obj.getLong(TIMESTAMP_KEY);
//Header
this.sender = header.getString(FROM_KEY);
this.recipients = new ArrayList<String>();
JSONArray jsonRecipients = header.getJSONArray(TO_KEY);
for(int i = 0; i < jsonRecipients.length(); i++){
this.recipients.add(jsonRecipients.getString(i));
}
//Body
this.type = body.getString(TYPE_KEY);
if(this.type.equalsIgnoreCase(TYPE_MEDIA)){
JSONObject media = body.getJSONObject(MEDIA_KEY);
this.width = media.getInt(WIDTH_KEY);
this.height = media.getInt(HEIGHT_KEY);
this.media_id = media.getString(MEDIA_ID_KEY);
this.key = media.getString(KEY_KEY);
this.iv = media.getString(IV_KEY);
}else if(this.type.equalsIgnoreCase(TYPE_TEXT)){
this.text = body.getString(TEXT_KEY);
}
}catch(JSONException e){
e.printStackTrace();
return this;
}
return this;
}
/**
* Get sender username.
*
* @return sender username.
*/
public String getSender(){
return this.sender;
}
/**
* Get all recipients.
*
* @return recipients.
*/
public List<String> getRecipients(){
return this.recipients;
}
/**
* Get the text of this message.
*
* @return the text.
*/
public String getText(){
return this.text;
}
/**
* Get the date of when this message was sent.
*
* @return unix timestamp of when this message was sent.
*/
public long getSentTime(){
return this.sent_time;
}
/**
* Check if this message was an image.
*
* @return true if it is an image, otherwise false.
*/
public boolean isMedia(){
return this.type.equalsIgnoreCase(TYPE_MEDIA);
}
/**
* Check if this message is a text message.
*
* @return true if it is a text message, otherwise false.
*/
public boolean isTextMessage(){
return this.type.equalsIgnoreCase(TYPE_TEXT);
}
/**
* Get the width of this media.
*
* @return the width of this media. If this is not a media, returns -1.
*/
public int getWidth(){
if(!this.isMedia()){
return -1;
}
return this.width;
}
/**
* Get the height of this media.
*
* @return the height of this media. -1 if this is not a media.
*/
public int getHeight(){
if(!this.isMedia()){
return -1;
}
return this.height;
}
/**
* Get the key of this media. Used for decryption.
*
* @return the key of this media. Null if this is not a media.
*/
public String getKey(){
if(!this.isMedia()){
return null;
}
return this.key;
}
/**
* Get the iv key of this media. Used for decryption.
*
* @return the iv key of this media. Null if this is not a media.
*/
public String getIVKey(){
if(!this.isMedia()){
return null;
}
return this.iv;
}
/**
* Get the ID.
*
* @return the id.
*/
public String getID(){
return this.id;
}
/**
* Get the Chat Message ID.
*
* @return the chat message id.
*/
public String getChatMessageID(){
return this.chat_message_id;
}
/**
* Get the media id. Basically same has Message#getChatMessageID
*
* @return the media id. Null if not a media.
*/
public String getMediaID(){
if(!this.isMedia()){
return null;
}
return this.media_id;
}
}
| gpl-2.0 |
Hertuno/the-erder | The_Erder_Dedicated/src/ru/alastar/world/ServerWorld.java | 3871 | package ru.alastar.world;
import java.util.ArrayList;
import java.util.HashMap;
import com.alastar.game.Tile;
import com.alastar.game.enums.ModeType;
import com.alastar.game.enums.TileType;
import com.badlogic.gdx.math.Vector3;
import ru.alastar.entities.Entity;
import ru.alastar.main.Server;
import ru.alastar.main.net.ConnectedClient;
import ru.alastar.main.net.PacketGenerator;
import ru.alastar.main.net.responses.AddEntityResponse;
import ru.alastar.main.net.responses.AddTileResponse;
import ru.alastar.main.net.responses.RemoveEntityResponse;
import ru.alastar.main.net.responses.RemoveTileResponse;
public class ServerWorld {
public int id = 0;
public String name = "GenericWorld";
public HashMap<Vector3, Tile> tiles = new HashMap<Vector3, Tile>();
public ArrayList<Entity> entities = new ArrayList<Entity>();
public int version = 0;
public int zMin = -1;
public int zMax = 10;
public ServerWorld(int i, String n) {
this.id = i;
this.name = n;
tiles = new HashMap<Vector3, Tile>();
entities = new ArrayList<Entity>();
}
public void CreateTile(int x, int y, int z, TileType type, boolean p) {
AddTile(new Tile(new Vector3(x, y, z), type, p));
}
public void AddTile(Tile t) {
AddTileResponse r;
tiles.put(t.position, t);
for (int i = 0; i < entities.size(); ++i) {
if (Server.getClient(entities.get(i).id) != null) {
r = new AddTileResponse();
r.x = (int) t.position.x;
r.y = (int) t.position.y;
r.z = (int) t.position.z;
r.ordinalType = t.type.ordinal();
r.modeOrdinal = ModeType.World.ordinal();
PacketGenerator.generatePacketTo(Server.getClient(entities.get(i).id).connection, r);
}
}
}
public void AddEntity(Entity e) {
Entity ent;
AddEntityResponse r;
for (int i = 0; i < entities.size(); ++i) {
ent = entities.get(i);
r = new AddEntityResponse();
r.caption = e.caption;
r.id = e.id;
r.x = (int) e.position.x;
r.y = (int) e.position.y;
r.z = (int) e.position.z;
r.typeOrdinal = e.type.ordinal();
PacketGenerator.generatePacketTo(Server.getClient(ent.id).connection, r);
}
entities.add(e);
}
public void RemoveEntity(Entity entity) {
RemoveEntityResponse r;
entities.remove(entity);
for (int i = 0; i < entities.size(); ++i) {
if (Server.getClient(entities.get(i).id) != null) {
r = new RemoveEntityResponse();
r.id = entity.id;
r.modeOrdinal = ModeType.World.ordinal();
PacketGenerator.generatePacketTo(Server.getClient(entities.get(i).id).connection, r);
}
}
}
public void RemoveTile(Tile t) {
RemoveTileResponse r;
for (int i = 0; i < entities.size(); ++i) {
if (Server.getClient(entities.get(i).id) != null) {
r = new RemoveTileResponse();
r.x = (int) t.position.x;
r.y = (int) t.position.y;
r.z = (int) t.position.z;
r.modeOrdinal = ModeType.World.ordinal();
PacketGenerator.generatePacketTo(Server.getClient(entities.get(i).id).connection, r);
}
}
try {
tiles.remove(t.position);
} finally {
}
}
public Tile GetTile(int x, int y, int z) {
return tiles.get(new Vector3(x, y, z));
}
public Tile GetTile(Vector3 xyz) {
return tiles.get(xyz);
}
public void SendTiles(ConnectedClient c) {
}
public void SendEntities(ConnectedClient c) {
Entity e;
AddEntityResponse r;
for (int i = 0; i < entities.size(); ++i) {
e = entities.get(i);
r = new AddEntityResponse();
r.caption = e.caption;
r.id = e.id;
r.x = (int) e.position.x;
r.y = (int) e.position.y;
r.z = (int) e.position.z;
r.typeOrdinal = e.type.ordinal();
Server.Log("Send entity id: " + e.id + " caption: " + e.caption
+ " pos: " + e.position.toString());
PacketGenerator.generatePacketTo(c.connection, r);
}
}
}
| gpl-2.0 |
StarMade/Fake-Player-Count | src/org/schema/schine/network/RegisteredClientOnServer.java | 5027 | package org.schema.schine.network;
import java.io.PrintStream;
import java.net.InetAddress;
import java.util.ArrayList;
import org.schema.schine.network.commands.MessageTo;
import org.schema.schine.network.server.ServerMessage;
import org.schema.schine.network.server.ServerProcessor;
import org.schema.schine.network.server.ServerStateInterface;
public class RegisteredClientOnServer
implements Identifiable, Recipient, RegisteredClientInterface
{
protected NetworkStateContainer localAndRemoteContainer;
protected SynchronizationContainerController synchController;
protected ArrayList wispers = new ArrayList();
public boolean wasFullSynched;
protected int id;
protected String playerName;
protected ServerProcessor serverProcessor;
protected boolean connected;
protected short needsSynch = Short.MIN_VALUE;
protected Object player;
protected String starmadeName;
protected boolean upgradedAccount;
public RegisteredClientOnServer(int paramInt, String paramString)
{
this.id = paramInt;
this.playerName = paramString;
this.connected = true;
}
public RegisteredClientOnServer(int paramInt, String paramString, ServerStateInterface paramServerStateInterface)
{
this.id = paramInt;
this.playerName = paramString;
this.connected = true;
this.localAndRemoteContainer = new NetworkStateContainer(true, paramServerStateInterface);
this.synchController = new SynchronizationContainerController(this.localAndRemoteContainer, paramServerStateInterface, true);
}
public boolean checkConnection()
{
if (!this.connected) {
return false;
}
if (!getProcessor().isConnectionAlive()) {
return false;
}
return true;
}
public void executedAdminCommand() {}
public int getId()
{
return this.id;
}
public String getPlayerName()
{
return this.playerName;
}
public void serverMessage(String paramString)
{
System.err.println("[SEND][SERVERMESSAGE] " + paramString + " to " + this);
sendCommand(getId(), IdGen.getNewPacketId(), MessageTo.class, new Object[] { "SERVER", paramString, Integer.valueOf(0) });
}
public void setPlayerName(String paramString)
{
this.playerName = paramString;
}
public void setId(int paramInt)
{
this.id = paramInt;
}
public void flagSynch(short paramShort)
{
this.needsSynch = paramShort;
}
public String getIp()
{
try
{
return getProcessor().getClientIp().toString().replace("/", "");
}
catch (Exception localException)
{
localException.printStackTrace();;
}
return "0.0.0.0";
}
public NetworkStateContainer getLocalAndRemoteObjectContainer()
{
return this.localAndRemoteContainer;
}
public Object getPlayerObject()
{
return this.player;
}
public void setPlayerObject(Object paramObject)
{
this.player = paramObject;
}
public ServerProcessor getProcessor()
{
return this.serverProcessor;
}
public void setProcessor(ServerProcessor paramServerProcessor)
{
this.serverProcessor = paramServerProcessor;
}
public SynchronizationContainerController getSynchController()
{
return this.synchController;
}
public short getSynchPacketId()
{
return this.needsSynch;
}
public ArrayList getWispers()
{
return this.wispers;
}
public boolean isConnected()
{
return this.connected;
}
public void setConnected(boolean paramBoolean)
{
this.connected = false;
}
public boolean needsSynch()
{
return this.needsSynch > Short.MIN_VALUE;
}
public void sendCommand(int paramInt, short paramShort, Class paramClass, Object... paramVarArgs)
{
NetUtil.commands.getByClass(paramClass).writeAndCommitParametriziedCommand(paramVarArgs, getId(), paramInt, paramShort, this.serverProcessor);
}
public Object[] sendReturnedCommand(int paramInt, short paramShort, Class paramClass, Object... paramVarArgs)
{
throw new IllegalArgumentException("this moethod is only used: client to server for client requests");
}
public void method7017serverMessage(ServerMessage paramServerMessage)
{
System.err.println("[SEND][SERVERMESSAGE] " + paramServerMessage + " to " + this);
sendCommand(getId(), IdGen.getNewPacketId(), MessageTo.class, new Object[] { "SERVER", paramServerMessage.message, Integer.valueOf(paramServerMessage.type) });
}
public String toString()
{
return "RegisteredClient: " + getPlayerName() + " (" + this.id + ") " + (this.starmadeName != null ? "[" + this.starmadeName + "]" : "") + "connected: " + this.connected;
}
public String getStarmadeName()
{
return this.starmadeName;
}
public void setStarmadeName(String paramString)
{
this.starmadeName = paramString;
}
public boolean isUpgradedAccount()
{
return this.upgradedAccount;
}
public void setUpgradedAccount(boolean paramBoolean)
{
this.upgradedAccount = paramBoolean;
}
}
| gpl-2.0 |
cesaralmeciga/Estructura.1 | Problema3/src/problema3/punto4.java | 1104 | import java.io.*;
/**
* @date 01-11-17
* @author CesarAlmeciga
* Punto 1 del parcial
*/
public class punto4 {
static BufferedReader br = new BufferedReader ( new InputStreamReader (System.in));
static BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter (System.out));
public static void main(String[] args) throws IOException {
int [] dias = new int [7];
bw.write (" ingrese los precios por día");
bw.flush();
int i;
for (i = 0; i < dias.length; i++) {
int valor = Integer.parseInt(br.readLine() );
dias[i] = valor;
}
int Menor = dias[0];
int Mayor = dias[0];
int diferencia=0;
for (int j = 0; j < dias.length; j++) {
if(dias[j] < Menor){
Menor = dias[j];
}
}
System.out.println(Menor);
for (int x = 0; x < dias.length; x++) {
if(dias[x] > Mayor){
Mayor = dias[x];
}
}
System.out.println(Mayor);
diferencia = Mayor - Menor;
System.out.println("La ganancia es de " + diferencia);
}
} | gpl-2.0 |
bdaum/zoraPD | com.bdaum.zoom.ui/src/com/bdaum/zoom/ui/internal/audio/Messages.java | 1386 | /*
* This file is part of the ZoRa project: http://www.photozora.org.
*
* ZoRa is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* ZoRa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ZoRa; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* (c) 2009 Berthold Daum
*/
package com.bdaum.zoom.ui.internal.audio;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "com.bdaum.zoom.ui.internal.audio.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);
private Messages() {
}
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| gpl-2.0 |
fozziethebeat/C-Cat | wordnet/src/main/java/gov/llnl/ontology/wordnet/feature/SnowEtAlFeatureMaker.java | 7935 | /*
* Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
* the Lawrence Livermore National Laboratory. Written by Keith Stevens,
* kstevens@cs.ucla.edu OCEC-10-073 All rights reserved.
*
* This file is part of the C-Cat package and is covered under the terms and
* conditions therein.
*
* The C-Cat package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gov.llnl.ontology.wordnet.feature;
import gov.llnl.ontology.wordnet.Lemma;
import gov.llnl.ontology.wordnet.OntologyReader;
import gov.llnl.ontology.wordnet.SynsetSimilarity;
import gov.llnl.ontology.wordnet.Synset;
import gov.llnl.ontology.wordnet.Synset.PartsOfSpeech;
import gov.llnl.ontology.wordnet.SynsetRelations;
import gov.llnl.ontology.wordnet.sim.HirstStOngeSimilarity;
import gov.llnl.ontology.wordnet.sim.LeacockChodorowScaledSimilarity;
import gov.llnl.ontology.wordnet.sim.PathSimilarity;
import gov.llnl.ontology.wordnet.sim.WuPalmerSimilarity;
import edu.ucla.sspace.vector.DenseVector;
import edu.ucla.sspace.vector.DoubleVector;
import edu.ucla.sspace.vector.VectorIO;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOError;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This {@link SynsetPairFeatureMaker} creates a subset of the features used by
* the following paper:
*
* </p style="font-family:Garamond, Georgia, serif">Rion Snow; Sushant
* Prakash; Daniel Jurafsky; Andrew Y. Ng. "Learning to merge word senses," in
* <i> Proceedings of the 2007 Joint Conference on Empirical Methods in
* Natural Language Processing and Computational Natural Language Learning</i>
*
* </p>
*
* This class uses only features that are based on the path's linking two {@link
* Synset}s. This is done because {@link Synset}s that are automatically added
* to WordNet are likely to be missing information content, glosses, and links
* besides Hypernymy and Hyponymy.
*
* </p>
*
* The feature vectors generated by this class can be used to train a
* classifier, if a predetermined clustering for all {@link Sysnet}s can be
* provided. When creating a set of test feature vectors, this set of
* assignments does not need to be provided.
*
* </p>
*
* Classes which want to use a superset of these features can extends this class
* and implement three helper methods.
*
* @author Keith Stevens
*/
public class SnowEtAlFeatureMaker implements SynsetPairFeatureMaker {
/**
* A link to the word net hierarchy being used.
*/
private final OntologyReader wordnet;
/**
* A mapping from a {@link Synset}'s sense key to it's cluster of {@link
* Synset}s. This may be null.
*/
private final Map<String, Set<String>> mergedSenseInfo;
/**
* Creates a new {@link SnowEtAlFeatureMaker}. No sense clustering is used.
*/
public SnowEtAlFeatureMaker(OntologyReader wordnet) {
this(wordnet, null);
}
/**
* Creates a new {@link SnowEtAlFeatureMaker}. If {@link mergedInfoFilename}
* is not null, the cluster assignments are used as class labels.
*/
public SnowEtAlFeatureMaker(OntologyReader wordnet,
String mergedInfoFilename) {
this.wordnet = wordnet;
// Create the mapping for known sense clusterings if a file is provided.
if (mergedInfoFilename != null) {
mergedSenseInfo = new HashMap<String, Set<String>>();
try {
BufferedReader br = new BufferedReader(new FileReader(
mergedInfoFilename));
for (String line = null; (line = br.readLine()) != null; ) {
Set<String> keys = new HashSet<String>();
keys.addAll(Arrays.asList(line.split("\\s+")));
for (String key : keys)
mergedSenseInfo.put(key, keys);
}
} catch (IOException ioe) {
throw new IOError(ioe);
}
} else
mergedSenseInfo = null;
}
/**
* Returns the number of extra features.
*/
protected int numExtraFeatures() {
return 0;
}
/**
* Appends extra attribute labels.
*/
protected void addExtraAttributes(List<String> attributeList) {
}
/**
* Adds extra feature values to {@code featureVector}. {@code index} is the
* first index at which a feature can be stored.
*/
protected void addExtraFeatures(Synset sense1, Synset sense2,
DoubleVector featureVector, int index) {
}
/**
* {@inheritDoc}
*/
public List<String> makeAttributeList() {
List<String> attributeList = new ArrayList<String>();
attributeList.add("HSO");
attributeList.add("LCH");
attributeList.add("WUP");
attributeList.add("PATH");
attributeList.add("MN");
attributeList.add("MAXMN");
attributeList.add("SENSECOUNT");
addExtraAttributes(attributeList);
attributeList.add("class");
return attributeList;
}
/**
* {@inheritDoc}
*/
public DoubleVector makeFeatureVector(Synset sense1, Synset sense2) {
PartsOfSpeech pos = sense1.getPartOfSpeech();
DoubleVector values = new DenseVector(8 + numExtraFeatures());
// Add the class label. 1 for merged according to some known scheme
// or 0 otherwise.
values.set(values.length() - 1, 0);
if (mergedSenseInfo != null) {
Set<String> senseKeys = mergedSenseInfo.get(sense1.getName());
// If we have a data point that lacks sense clustering info when it is
// required, drop the data point.
if (senseKeys == null)
return null;
if (senseKeys.contains(sense2.getName()))
values.set(values.length() - 1, 1);
}
SynsetSimilarity[] simFunctions = new SynsetSimilarity[] {
new HirstStOngeSimilarity(),
new LeacockChodorowScaledSimilarity(wordnet),
new WuPalmerSimilarity(),
new PathSimilarity()
};
// Set the pure path based similarity features.
for (int i = 0; i < simFunctions.length; ++i)
values.set(i, simFunctions[i].similarity(sense1, sense2));
// Set the MN and MAXMN features.
Synset lowestCH = SynsetRelations.lowestCommonHypernym(
sense1, sense2);
if (lowestCH != null) {
values.set(4, Math.min(
SynsetRelations.shortestPathDistance(sense1, lowestCH),
SynsetRelations.shortestPathDistance(sense2, lowestCH)));
values.set(5, Math.min(
SynsetRelations.longestPathDistance(sense1, lowestCH),
SynsetRelations.longestPathDistance(sense2, lowestCH)));
}
// Add the SENSECOUNT feature.
Set<Lemma> sharedLemmas = new HashSet<Lemma>();
sharedLemmas.addAll(sense1.getLemmas());
int maxSenseForLemma = 0;
for (Lemma sharedLemma : sense2.getLemmas())
if (sharedLemmas.contains(sharedLemma))
maxSenseForLemma = Math.max(
maxSenseForLemma,
wordnet.getSynsets(sharedLemma.getLemmaName(), pos).length);
values.set(6, maxSenseForLemma);
// Add any extra feautres.
addExtraFeatures(sense1, sense2, values, 7);
return values;
}
public String toString() {
return "SnowEtAlFeatureMaker";
}
}
| gpl-2.0 |
mobile-event-processing/Asper | source/src/com/asper/sources/sun/naming/internal/VersionHelper12.java | 8599 | /*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.asper.sources.sun.naming.internal;
import java.io.InputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Properties;
import com.asper.sources.javax.naming.*;
/**
* VersionHelper was used by JNDI to accommodate differences between
* JDK 1.1.x and the Java 2 platform. As this is no longer necessary
* since JNDI's inclusion in the platform, this class currently
* serves as a set of utilities for performing system-level things,
* such as class-loading and reading system properties.
*
* @author Rosanna Lee
* @author Scott Seligman
*/
final class VersionHelper12 extends VersionHelper {
private boolean getSystemPropsFailed = false;
VersionHelper12() {} // Disallow external from creating one of these.
public Class loadClass(String className) throws ClassNotFoundException {
ClassLoader cl = getContextClassLoader();
return Class.forName(className, true, cl);
}
/**
* Package private.
*/
Class loadClass(String className, ClassLoader cl)
throws ClassNotFoundException {
return Class.forName(className, true, cl);
}
/**
* @param className A non-null fully qualified class name.
* @param codebase A non-null, space-separated list of URL strings.
*/
public Class loadClass(String className, String codebase)
throws ClassNotFoundException, MalformedURLException {
ClassLoader cl;
ClassLoader parent = getContextClassLoader();
cl = URLClassLoader.newInstance(getUrlArray(codebase), parent);
return Class.forName(className, true, cl);
}
String getJndiProperty(final int i) {
return (String) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
try {
return System.getProperty(PROPS[i]);
} catch (SecurityException e) {
return null;
}
}
}
);
}
String[] getJndiProperties() {
if (getSystemPropsFailed) {
return null; // after one failure, don't bother trying again
}
Properties sysProps = (Properties) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
try {
return System.getProperties();
} catch (SecurityException e) {
getSystemPropsFailed = true;
return null;
}
}
}
);
if (sysProps == null) {
return null;
}
String[] jProps = new String[PROPS.length];
for (int i = 0; i < PROPS.length; i++) {
jProps[i] = sysProps.getProperty(PROPS[i]);
}
return jProps;
}
InputStream getResourceAsStream(final Class c, final String name) {
return (InputStream) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return c.getResourceAsStream(name);
}
}
);
}
InputStream getJavaHomeLibStream(final String filename) {
return (InputStream) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
try {
String javahome = System.getProperty("java.home");
if (javahome == null) {
return null;
}
String pathname = javahome + java.io.File.separator +
"lib" + java.io.File.separator + filename;
return new java.io.FileInputStream(pathname);
} catch (Exception e) {
return null;
}
}
}
);
}
NamingEnumeration getResources(final ClassLoader cl, final String name)
throws IOException
{
Enumeration urls;
try {
urls = (Enumeration) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws IOException {
return (cl == null)
? ClassLoader.getSystemResources(name)
: cl.getResources(name);
}
}
);
} catch (PrivilegedActionException e) {
throw (IOException)e.getException();
}
return new InputStreamEnumeration(urls);
}
ClassLoader getContextClassLoader() {
return (ClassLoader) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
}
);
}
/**
* Given an enumeration of URLs, an instance of this class represents
* an enumeration of their InputStreams. Each operation on the URL
* enumeration is performed within a doPrivileged block.
* This is used to enumerate the resources under a foreign codebase.
* This class is not MT-safe.
*/
class InputStreamEnumeration implements NamingEnumeration {
private final Enumeration urls;
private Object nextElement = null;
InputStreamEnumeration(Enumeration urls) {
this.urls = urls;
}
/*
* Returns the next InputStream, or null if there are no more.
* An InputStream that cannot be opened is skipped.
*/
private Object getNextElement() {
return AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
while (urls.hasMoreElements()) {
try {
return ((URL)urls.nextElement()).openStream();
} catch (IOException e) {
// skip this URL
}
}
return null;
}
}
);
}
public boolean hasMore() {
if (nextElement != null) {
return true;
}
nextElement = getNextElement();
return (nextElement != null);
}
public boolean hasMoreElements() {
return hasMore();
}
public Object next() {
if (hasMore()) {
Object res = nextElement;
nextElement = null;
return res;
} else {
throw new NoSuchElementException();
}
}
public Object nextElement() {
return next();
}
public void close() {
}
}
}
| gpl-2.0 |
shahora/kurdishgram1 | TMeesagesProj/src/main/java/org/vidogram/messenger/exoplayer2/extractor/mp4/AtomParsers.java | 52440 | package org.vidogram.messenger.exoplayer2.extractor.mp4;
import android.util.Log;
import android.util.Pair;
import android.util.Pair<Ljava.lang.Integer;Lorg.vidogram.messenger.exoplayer2.extractor.mp4.TrackEncryptionBox;>;
import android.util.Pair<Ljava.lang.String;[B>;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.vidogram.messenger.exoplayer2.Format;
import org.vidogram.messenger.exoplayer2.ParserException;
import org.vidogram.messenger.exoplayer2.audio.Ac3Util;
import org.vidogram.messenger.exoplayer2.drm.DrmInitData;
import org.vidogram.messenger.exoplayer2.extractor.GaplessInfoHolder;
import org.vidogram.messenger.exoplayer2.metadata.Metadata;
import org.vidogram.messenger.exoplayer2.metadata.Metadata.Entry;
import org.vidogram.messenger.exoplayer2.util.Assertions;
import org.vidogram.messenger.exoplayer2.util.CodecSpecificDataUtil;
import org.vidogram.messenger.exoplayer2.util.ParsableByteArray;
import org.vidogram.messenger.exoplayer2.util.Util;
import org.vidogram.messenger.exoplayer2.video.AvcConfig;
import org.vidogram.messenger.exoplayer2.video.HevcConfig;
final class AtomParsers
{
private static final String TAG = "AtomParsers";
private static final int TYPE_cenc;
private static final int TYPE_clcp;
private static final int TYPE_meta;
private static final int TYPE_sbtl;
private static final int TYPE_soun;
private static final int TYPE_subt;
private static final int TYPE_text;
private static final int TYPE_vide = Util.getIntegerCodeForString("vide");
static
{
TYPE_soun = Util.getIntegerCodeForString("soun");
TYPE_text = Util.getIntegerCodeForString("text");
TYPE_sbtl = Util.getIntegerCodeForString("sbtl");
TYPE_subt = Util.getIntegerCodeForString("subt");
TYPE_clcp = Util.getIntegerCodeForString("clcp");
TYPE_cenc = Util.getIntegerCodeForString("cenc");
TYPE_meta = Util.getIntegerCodeForString("meta");
}
private static int findEsdsPosition(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2)
{
int i = paramParsableByteArray.getPosition();
while (i - paramInt1 < paramInt2)
{
paramParsableByteArray.setPosition(i);
int j = paramParsableByteArray.readInt();
if (j > 0);
for (boolean bool = true; ; bool = false)
{
Assertions.checkArgument(bool, "childAtomSize should be positive");
if (paramParsableByteArray.readInt() != Atom.TYPE_esds)
break;
return i;
}
i += j;
}
return -1;
}
private static void parseAudioSampleEntry(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2, int paramInt3, int paramInt4, String paramString, boolean paramBoolean, DrmInitData paramDrmInitData, StsdData paramStsdData, int paramInt5)
{
paramParsableByteArray.setPosition(paramInt2 + 8);
int k;
int m;
int n;
int i;
int j;
label88: Object localObject1;
label137: Object localObject2;
label151: boolean bool;
label179: label225: Object localObject3;
Object localObject4;
if (paramBoolean)
{
paramParsableByteArray.skipBytes(8);
k = paramParsableByteArray.readUnsignedShort();
paramParsableByteArray.skipBytes(6);
if ((k != 0) && (k != 1))
break label369;
m = paramParsableByteArray.readUnsignedShort();
paramParsableByteArray.skipBytes(6);
n = paramParsableByteArray.readUnsignedFixedPoint1616();
i = n;
j = m;
if (k == 1)
{
paramParsableByteArray.skipBytes(16);
j = m;
i = n;
}
m = paramParsableByteArray.getPosition();
k = paramInt1;
if (paramInt1 == Atom.TYPE_enca)
{
k = parseSampleEntryEncryptionData(paramParsableByteArray, paramInt2, paramInt3, paramStsdData, paramInt5);
paramParsableByteArray.setPosition(m);
}
localObject1 = null;
if (k != Atom.TYPE_ac_3)
break label406;
localObject1 = "audio/ac3";
localObject2 = null;
paramInt1 = i;
i = j;
paramInt5 = m;
if (paramInt5 - paramInt2 >= paramInt3)
break label735;
paramParsableByteArray.setPosition(paramInt5);
m = paramParsableByteArray.readInt();
if (m <= 0)
break label542;
bool = true;
Assertions.checkArgument(bool, "childAtomSize should be positive");
n = paramParsableByteArray.readInt();
if ((n != Atom.TYPE_esds) && ((!paramBoolean) || (n != Atom.TYPE_wave)))
break label561;
if (n != Atom.TYPE_esds)
break label548;
j = paramInt5;
if (j == -1)
break label814;
localObject1 = parseEsdsFromParent(paramParsableByteArray, j);
localObject3 = (String)((Pair)localObject1).first;
localObject4 = (byte[])((Pair)localObject1).second;
localObject1 = localObject3;
localObject2 = localObject4;
if ("audio/mp4a-latm".equals(localObject3))
{
localObject1 = CodecSpecificDataUtil.parseAacAudioSpecificConfig(localObject4);
paramInt1 = ((Integer)((Pair)localObject1).first).intValue();
i = ((Integer)((Pair)localObject1).second).intValue();
localObject2 = localObject4;
localObject1 = localObject3;
}
}
label406: label542: label548: label805: label814:
while (true)
{
localObject3 = localObject2;
j = paramInt1;
k = i;
localObject4 = localObject1;
while (true)
{
paramInt5 += m;
localObject1 = localObject4;
i = k;
paramInt1 = j;
localObject2 = localObject3;
break label151;
paramParsableByteArray.skipBytes(16);
k = 0;
break;
label369: if (k != 2)
break label799;
paramParsableByteArray.skipBytes(16);
i = (int)Math.round(paramParsableByteArray.readDouble());
j = paramParsableByteArray.readUnsignedIntToInt();
paramParsableByteArray.skipBytes(20);
break label88;
if (k == Atom.TYPE_ec_3)
{
localObject1 = "audio/eac3";
break label137;
}
if (k == Atom.TYPE_dtsc)
{
localObject1 = "audio/vnd.dts";
break label137;
}
if ((k == Atom.TYPE_dtsh) || (k == Atom.TYPE_dtsl))
{
localObject1 = "audio/vnd.dts.hd";
break label137;
}
if (k == Atom.TYPE_dtse)
{
localObject1 = "audio/vnd.dts.hd;profile=lbr";
break label137;
}
if (k == Atom.TYPE_samr)
{
localObject1 = "audio/3gpp";
break label137;
}
if (k == Atom.TYPE_sawb)
{
localObject1 = "audio/amr-wb";
break label137;
}
if ((k == Atom.TYPE_lpcm) || (k == Atom.TYPE_sowt))
{
localObject1 = "audio/raw";
break label137;
}
if (k != Atom.TYPE__mp3)
break label137;
localObject1 = "audio/mpeg";
break label137;
bool = false;
break label179;
j = findEsdsPosition(paramParsableByteArray, paramInt5, m);
break label225;
label561: if (n == Atom.TYPE_dac3)
{
paramParsableByteArray.setPosition(paramInt5 + 8);
paramStsdData.format = Ac3Util.parseAc3AnnexFFormat(paramParsableByteArray, Integer.toString(paramInt4), paramString, paramDrmInitData);
localObject4 = localObject1;
k = i;
j = paramInt1;
localObject3 = localObject2;
continue;
}
if (n == Atom.TYPE_dec3)
{
paramParsableByteArray.setPosition(paramInt5 + 8);
paramStsdData.format = Ac3Util.parseEAc3AnnexFFormat(paramParsableByteArray, Integer.toString(paramInt4), paramString, paramDrmInitData);
localObject4 = localObject1;
k = i;
j = paramInt1;
localObject3 = localObject2;
continue;
}
localObject4 = localObject1;
k = i;
j = paramInt1;
localObject3 = localObject2;
if (n != Atom.TYPE_ddts)
continue;
paramStsdData.format = Format.createAudioSampleFormat(Integer.toString(paramInt4), (String)localObject1, null, -1, -1, i, paramInt1, null, paramDrmInitData, 0, paramString);
localObject4 = localObject1;
k = i;
j = paramInt1;
localObject3 = localObject2;
}
label735: if ((paramStsdData.format == null) && (localObject1 != null))
{
if (!"audio/raw".equals(localObject1))
break label800;
paramInt2 = 2;
localObject3 = Integer.toString(paramInt4);
if (localObject2 != null)
break label805;
}
for (paramParsableByteArray = null; ; paramParsableByteArray = Collections.singletonList(localObject2))
{
paramStsdData.format = Format.createAudioSampleFormat((String)localObject3, (String)localObject1, null, -1, -1, i, paramInt1, paramInt2, paramParsableByteArray, paramDrmInitData, 0, paramString);
return;
paramInt2 = -1;
break;
}
}
}
private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom paramContainerAtom)
{
if (paramContainerAtom != null)
{
paramContainerAtom = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_elst);
if (paramContainerAtom != null);
}
else
{
return Pair.create(null, null);
}
paramContainerAtom = paramContainerAtom.data;
paramContainerAtom.setPosition(8);
int j = Atom.parseFullAtomVersion(paramContainerAtom.readInt());
int k = paramContainerAtom.readUnsignedIntToInt();
long[] arrayOfLong1 = new long[k];
long[] arrayOfLong2 = new long[k];
int i = 0;
while (i < k)
{
long l;
if (j == 1)
{
l = paramContainerAtom.readUnsignedLongToLong();
arrayOfLong1[i] = l;
if (j != 1)
break label125;
l = paramContainerAtom.readLong();
}
while (true)
{
arrayOfLong2[i] = l;
if (paramContainerAtom.readShort() == 1)
break label135;
throw new IllegalArgumentException("Unsupported media rate.");
l = paramContainerAtom.readUnsignedInt();
break;
label125: l = paramContainerAtom.readInt();
}
label135: paramContainerAtom.skipBytes(2);
i += 1;
}
return Pair.create(arrayOfLong1, arrayOfLong2);
}
private static Pair<String, byte[]> parseEsdsFromParent(ParsableByteArray paramParsableByteArray, int paramInt)
{
Object localObject = null;
paramParsableByteArray.setPosition(paramInt + 8 + 4);
paramParsableByteArray.skipBytes(1);
parseExpandableClassSize(paramParsableByteArray);
paramParsableByteArray.skipBytes(2);
paramInt = paramParsableByteArray.readUnsignedByte();
if ((paramInt & 0x80) != 0)
paramParsableByteArray.skipBytes(2);
if ((paramInt & 0x40) != 0)
paramParsableByteArray.skipBytes(paramParsableByteArray.readUnsignedShort());
if ((paramInt & 0x20) != 0)
paramParsableByteArray.skipBytes(2);
paramParsableByteArray.skipBytes(1);
parseExpandableClassSize(paramParsableByteArray);
switch (paramParsableByteArray.readUnsignedByte())
{
default:
case 107:
case 32:
case 33:
case 35:
case 64:
case 102:
case 103:
case 104:
case 165:
case 166:
while (true)
{
paramParsableByteArray.skipBytes(12);
paramParsableByteArray.skipBytes(1);
paramInt = parseExpandableClassSize(paramParsableByteArray);
byte[] arrayOfByte = new byte[paramInt];
paramParsableByteArray.readBytes(arrayOfByte, 0, paramInt);
return Pair.create(localObject, arrayOfByte);
return Pair.create("audio/mpeg", null);
localObject = "video/mp4v-es";
continue;
localObject = "video/avc";
continue;
localObject = "video/hevc";
continue;
localObject = "audio/mp4a-latm";
continue;
localObject = "audio/ac3";
continue;
localObject = "audio/eac3";
}
case 169:
case 172:
return Pair.create("audio/vnd.dts", null);
case 170:
case 171:
}
return (Pair<String, byte[]>)Pair.create("audio/vnd.dts.hd", null);
}
private static int parseExpandableClassSize(ParsableByteArray paramParsableByteArray)
{
int j = paramParsableByteArray.readUnsignedByte();
for (int i = j & 0x7F; (j & 0x80) == 128; i = i << 7 | j & 0x7F)
j = paramParsableByteArray.readUnsignedByte();
return i;
}
private static int parseHdlr(ParsableByteArray paramParsableByteArray)
{
paramParsableByteArray.setPosition(16);
int i = paramParsableByteArray.readInt();
if (i == TYPE_soun)
return 1;
if (i == TYPE_vide)
return 2;
if ((i == TYPE_text) || (i == TYPE_sbtl) || (i == TYPE_subt) || (i == TYPE_clcp))
return 3;
if (i == TYPE_meta)
return 4;
return -1;
}
private static Metadata parseIlst(ParsableByteArray paramParsableByteArray, int paramInt)
{
paramParsableByteArray.skipBytes(8);
ArrayList localArrayList = new ArrayList();
while (paramParsableByteArray.getPosition() < paramInt)
{
Metadata.Entry localEntry = MetadataUtil.parseIlstElement(paramParsableByteArray);
if (localEntry == null)
continue;
localArrayList.add(localEntry);
}
if (localArrayList.isEmpty())
return null;
return new Metadata(localArrayList);
}
private static Pair<Long, String> parseMdhd(ParsableByteArray paramParsableByteArray)
{
int j = 8;
paramParsableByteArray.setPosition(8);
int k = Atom.parseFullAtomVersion(paramParsableByteArray.readInt());
if (k == 0);
for (int i = 8; ; i = 16)
{
paramParsableByteArray.skipBytes(i);
long l = paramParsableByteArray.readUnsignedInt();
i = j;
if (k == 0)
i = 4;
paramParsableByteArray.skipBytes(i);
i = paramParsableByteArray.readUnsignedShort();
return Pair.create(Long.valueOf(l), "" + (char)((i >> 10 & 0x1F) + 96) + (char)((i >> 5 & 0x1F) + 96) + (char)((i & 0x1F) + 96));
}
}
private static Metadata parseMetaAtom(ParsableByteArray paramParsableByteArray, int paramInt)
{
paramParsableByteArray.skipBytes(12);
while (paramParsableByteArray.getPosition() < paramInt)
{
int i = paramParsableByteArray.getPosition();
int j = paramParsableByteArray.readInt();
if (paramParsableByteArray.readInt() == Atom.TYPE_ilst)
{
paramParsableByteArray.setPosition(i);
return parseIlst(paramParsableByteArray, i + j);
}
paramParsableByteArray.skipBytes(j - 8);
}
return null;
}
private static long parseMvhd(ParsableByteArray paramParsableByteArray)
{
int i = 8;
paramParsableByteArray.setPosition(8);
if (Atom.parseFullAtomVersion(paramParsableByteArray.readInt()) == 0);
while (true)
{
paramParsableByteArray.skipBytes(i);
return paramParsableByteArray.readUnsignedInt();
i = 16;
}
}
private static float parsePaspFromParent(ParsableByteArray paramParsableByteArray, int paramInt)
{
paramParsableByteArray.setPosition(paramInt + 8);
paramInt = paramParsableByteArray.readUnsignedIntToInt();
int i = paramParsableByteArray.readUnsignedIntToInt();
return paramInt / i;
}
private static byte[] parseProjFromParent(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2)
{
int i = paramInt1 + 8;
while (i - paramInt1 < paramInt2)
{
paramParsableByteArray.setPosition(i);
int j = paramParsableByteArray.readInt();
if (paramParsableByteArray.readInt() == Atom.TYPE_proj)
return Arrays.copyOfRange(paramParsableByteArray.data, i, j + i);
i += j;
}
return null;
}
private static int parseSampleEntryEncryptionData(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2, StsdData paramStsdData, int paramInt3)
{
int k = 0;
int i = paramParsableByteArray.getPosition();
while (true)
{
int j = k;
if (i - paramInt1 < paramInt2)
{
paramParsableByteArray.setPosition(i);
j = paramParsableByteArray.readInt();
if (j <= 0)
break label104;
}
label104: for (boolean bool = true; ; bool = false)
{
Assertions.checkArgument(bool, "childAtomSize should be positive");
if (paramParsableByteArray.readInt() != Atom.TYPE_sinf)
break;
Pair localPair = parseSinfFromParent(paramParsableByteArray, i, j);
if (localPair == null)
break;
paramStsdData.trackEncryptionBoxes[paramInt3] = ((TrackEncryptionBox)localPair.second);
j = ((Integer)localPair.first).intValue();
return j;
}
i += j;
}
}
private static TrackEncryptionBox parseSchiFromParent(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2)
{
boolean bool = true;
int i = paramInt1 + 8;
while (i - paramInt1 < paramInt2)
{
paramParsableByteArray.setPosition(i);
int j = paramParsableByteArray.readInt();
if (paramParsableByteArray.readInt() == Atom.TYPE_tenc)
{
paramParsableByteArray.skipBytes(6);
if (paramParsableByteArray.readUnsignedByte() == 1);
while (true)
{
paramInt1 = paramParsableByteArray.readUnsignedByte();
byte[] arrayOfByte = new byte[16];
paramParsableByteArray.readBytes(arrayOfByte, 0, arrayOfByte.length);
return new TrackEncryptionBox(bool, paramInt1, arrayOfByte);
bool = false;
}
}
i += j;
}
return null;
}
private static Pair<Integer, TrackEncryptionBox> parseSinfFromParent(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2)
{
boolean bool2 = true;
TrackEncryptionBox localTrackEncryptionBox = null;
int k = 0;
int j = paramInt1 + 8;
Object localObject1 = null;
if (j - paramInt1 < paramInt2)
{
paramParsableByteArray.setPosition(j);
int m = paramParsableByteArray.readInt();
int n = paramParsableByteArray.readInt();
Object localObject2;
int i;
if (n == Atom.TYPE_frma)
{
localObject2 = Integer.valueOf(paramParsableByteArray.readInt());
i = k;
}
while (true)
{
j += m;
localObject1 = localObject2;
k = i;
break;
if (n == Atom.TYPE_schm)
{
paramParsableByteArray.skipBytes(4);
if (paramParsableByteArray.readInt() == TYPE_cenc)
{
i = 1;
localObject2 = localObject1;
continue;
}
i = 0;
localObject2 = localObject1;
continue;
}
localObject2 = localObject1;
i = k;
if (n != Atom.TYPE_schi)
continue;
localTrackEncryptionBox = parseSchiFromParent(paramParsableByteArray, j, m);
localObject2 = localObject1;
i = k;
}
}
if (k != 0)
{
if (localObject1 != null)
{
bool1 = true;
Assertions.checkArgument(bool1, "frma atom is mandatory");
if (localTrackEncryptionBox == null)
break label209;
}
label209: for (boolean bool1 = bool2; ; bool1 = false)
{
Assertions.checkArgument(bool1, "schi->tenc atom is mandatory");
return Pair.create(localObject1, localTrackEncryptionBox);
bool1 = false;
break;
}
}
return (Pair<Integer, TrackEncryptionBox>)null;
}
public static TrackSampleTable parseStbl(Track paramTrack, Atom.ContainerAtom paramContainerAtom, GaplessInfoHolder paramGaplessInfoHolder)
{
Object localObject1 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stsz);
if (localObject1 != null);
int i14;
for (Object localObject2 = new StszSampleSizeBox((Atom.LeafAtom)localObject1); ; localObject2 = new Stz2SampleSizeBox((Atom.LeafAtom)localObject1))
{
i14 = ((SampleSizeBox)localObject2).getSampleCount();
if (i14 != 0)
break;
return new TrackSampleTable(new long[0], new int[0], 0, new long[0], new int[0]);
localObject1 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stz2);
if (localObject1 != null)
continue;
throw new ParserException("Track has no sample table size information");
}
boolean bool = false;
Object localObject3 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stco);
localObject1 = localObject3;
if (localObject3 == null)
{
bool = true;
localObject1 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_co64);
}
Object localObject4 = ((Atom.LeafAtom)localObject1).data;
Object localObject5 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stsc).data;
ParsableByteArray localParsableByteArray = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stts).data;
localObject1 = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_stss);
label202: ChunkIterator localChunkIterator;
int i5;
int i6;
int n;
int k;
int i;
int m;
int j;
if (localObject1 != null)
{
localObject1 = ((Atom.LeafAtom)localObject1).data;
paramContainerAtom = paramContainerAtom.getLeafAtomOfType(Atom.TYPE_ctts);
if (paramContainerAtom == null)
break label475;
localObject3 = paramContainerAtom.data;
localChunkIterator = new ChunkIterator((ParsableByteArray)localObject5, (ParsableByteArray)localObject4, bool);
localParsableByteArray.setPosition(12);
i5 = localParsableByteArray.readUnsignedIntToInt() - 1;
i6 = localParsableByteArray.readUnsignedIntToInt();
n = localParsableByteArray.readUnsignedIntToInt();
k = 0;
if (localObject3 != null)
{
((ParsableByteArray)localObject3).setPosition(12);
k = ((ParsableByteArray)localObject3).readUnsignedIntToInt();
}
if (localObject1 == null)
break label1996;
((ParsableByteArray)localObject1).setPosition(12);
i = ((ParsableByteArray)localObject1).readUnsignedIntToInt();
if (i <= 0)
break label481;
m = ((ParsableByteArray)localObject1).readUnsignedIntToInt() - 1;
paramContainerAtom = (Atom.ContainerAtom)localObject1;
j = i;
i = m;
}
while (true)
{
label309: if ((((SampleSizeBox)localObject2).isFixedSampleSize()) && ("audio/raw".equals(paramTrack.format.sampleMimeType)) && (i5 == 0) && (k == 0) && (j == 0));
Object localObject6;
long l2;
int i4;
int i2;
long l1;
int i3;
int i7;
int i8;
for (m = 1; ; m = 0)
{
if (m != 0)
break label983;
localObject4 = new long[i14];
localObject1 = new int[i14];
localObject5 = new long[i14];
localObject6 = new int[i14];
l2 = 0L;
i4 = 0;
i2 = 0;
i9 = 0;
m = k;
l1 = 0L;
i10 = 0;
i3 = 0;
k = n;
i7 = i;
i8 = j;
j = k;
k = i10;
i = m;
n = i9;
if (i4 >= i14)
break label776;
while (i3 == 0)
{
Assertions.checkState(localChunkIterator.moveNext());
l2 = localChunkIterator.offset;
i3 = localChunkIterator.numSamples;
}
localObject1 = null;
break;
label475: localObject3 = null;
break label202;
label481: m = -1;
paramContainerAtom = null;
j = i;
i = m;
break label309;
}
int i11 = n;
int i10 = i;
int i9 = i2;
if (localObject3 != null)
{
while ((i2 == 0) && (i > 0))
{
i2 = ((ParsableByteArray)localObject3).readUnsignedIntToInt();
n = ((ParsableByteArray)localObject3).readInt();
i -= 1;
}
i9 = i2 - 1;
i10 = i;
i11 = n;
}
localObject4[i4] = l2;
localObject1[i4] = ((SampleSizeBox)localObject2).readNextSampleSize();
int i12 = k;
if (localObject1[i4] > k)
i12 = localObject1[i4];
localObject5[i4] = (i11 + l1);
label617: int i13;
if (paramContainerAtom == null)
{
i = 1;
localObject6[i4] = i;
m = i8;
i13 = i7;
if (i4 == i7)
{
localObject6[i4] = 1;
i = i8 - 1;
if (i <= 0)
break label1986;
i13 = paramContainerAtom.readUnsignedIntToInt() - 1;
m = i;
}
}
while (true)
{
long l3 = j;
k = i6 - 1;
if ((k == 0) && (i5 > 0))
{
j = localParsableByteArray.readUnsignedIntToInt();
i = localParsableByteArray.readUnsignedIntToInt();
i5 -= 1;
}
while (true)
{
long l4 = localObject1[i4];
i4 += 1;
l2 += l4;
i6 = j;
j = i;
i3 -= 1;
l1 = l3 + l1;
n = i11;
i = i10;
i2 = i9;
k = i12;
i8 = m;
i7 = i13;
break;
i = 0;
break label617;
label776: if (i2 == 0)
{
bool = true;
Assertions.checkArgument(bool);
label789: if (i <= 0)
break label834;
if (((ParsableByteArray)localObject3).readUnsignedIntToInt() != 0)
break label828;
}
label828: for (bool = true; ; bool = false)
{
Assertions.checkArgument(bool);
((ParsableByteArray)localObject3).readInt();
i -= 1;
break label789;
bool = false;
break;
}
label834: if ((i8 != 0) || (i6 != 0) || (i3 != 0) || (i5 != 0))
Log.w("AtomParsers", "Inconsistent stbl box for track " + paramTrack.id + ": remainingSynchronizationSamples " + i8 + ", remainingSamplesAtTimestampDelta " + i6 + ", remainingSamplesInChunk " + i3 + ", remainingTimestampDeltaChanges " + i5);
localObject2 = localObject6;
localObject3 = localObject5;
i = k;
paramContainerAtom = (Atom.ContainerAtom)localObject4;
while ((paramTrack.editListDurations == null) || (paramGaplessInfoHolder.hasGaplessInfo()))
{
Util.scaleLargeTimestampsInPlace(localObject3, 1000000L, paramTrack.timescale);
return new TrackSampleTable(paramContainerAtom, localObject1, i, localObject3, localObject2);
label983: paramContainerAtom = new long[localChunkIterator.length];
localObject1 = new int[localChunkIterator.length];
while (localChunkIterator.moveNext())
{
paramContainerAtom[localChunkIterator.index] = localChunkIterator.offset;
localObject1[localChunkIterator.index] = localChunkIterator.numSamples;
}
localObject2 = FixedSampleSizeRechunker.rechunk(((SampleSizeBox)localObject2).readNextSampleSize(), paramContainerAtom, localObject1, n);
paramContainerAtom = ((FixedSampleSizeRechunker.Results)localObject2).offsets;
localObject1 = ((FixedSampleSizeRechunker.Results)localObject2).sizes;
i = ((FixedSampleSizeRechunker.Results)localObject2).maximumSize;
localObject3 = ((FixedSampleSizeRechunker.Results)localObject2).timestamps;
localObject2 = ((FixedSampleSizeRechunker.Results)localObject2).flags;
l1 = 0L;
}
if ((paramTrack.editListDurations.length == 1) && (paramTrack.type == 1) && (localObject3.length >= 2))
{
l3 = paramTrack.editListMediaTimes[0];
l2 = Util.scaleLargeTimestamp(paramTrack.editListDurations[0], paramTrack.timescale, paramTrack.movieTimescale) + l3;
if ((localObject3[0] <= l3) && (l3 < localObject3[1]) && (localObject3[(localObject3.length - 1)] < l2) && (l2 <= l1))
{
l3 = Util.scaleLargeTimestamp(l3 - localObject3[0], paramTrack.format.sampleRate, paramTrack.timescale);
l1 = Util.scaleLargeTimestamp(l1 - l2, paramTrack.format.sampleRate, paramTrack.timescale);
if (((l3 != 0L) || (l1 != 0L)) && (l3 <= 2147483647L) && (l1 <= 2147483647L))
{
paramGaplessInfoHolder.encoderDelay = (int)l3;
paramGaplessInfoHolder.encoderPadding = (int)l1;
Util.scaleLargeTimestampsInPlace(localObject3, 1000000L, paramTrack.timescale);
return new TrackSampleTable(paramContainerAtom, localObject1, i, localObject3, localObject2);
}
}
}
if ((paramTrack.editListDurations.length == 1) && (paramTrack.editListDurations[0] == 0L))
{
j = 0;
while (j < localObject3.length)
{
localObject3[j] = Util.scaleLargeTimestamp(localObject3[j] - paramTrack.editListMediaTimes[0], 1000000L, paramTrack.timescale);
j += 1;
}
return new TrackSampleTable(paramContainerAtom, localObject1, i, localObject3, localObject2);
}
int i1 = 0;
k = 0;
m = 0;
j = 0;
if (i1 < paramTrack.editListDurations.length)
{
l1 = paramTrack.editListMediaTimes[i1];
if (l1 == -1L)
break label1961;
l2 = Util.scaleLargeTimestamp(paramTrack.editListDurations[i1], paramTrack.timescale, paramTrack.movieTimescale);
i4 = Util.binarySearchCeil(localObject3, l1, true, true);
i2 = Util.binarySearchCeil(localObject3, l2 + l1, true, false);
i3 = j + (i2 - i4);
if (m != i4)
{
j = 1;
label1497: m = j | k;
j = i3;
}
}
for (k = i2; ; k = i2)
{
i1 += 1;
i2 = k;
k = m;
m = i2;
break;
j = 0;
break label1497;
if (j != i14)
{
m = 1;
i2 = k | m;
if (i2 == 0)
break label1834;
paramGaplessInfoHolder = new long[j];
label1566: if (i2 == 0)
break label1839;
localObject4 = new int[j];
label1577: if (i2 == 0)
break label1846;
i = 0;
label1584: if (i2 == 0)
break label1849;
}
label1834: label1839: label1846: label1849: for (localObject5 = new int[j]; ; localObject5 = localObject2)
{
localObject6 = new long[j];
k = 0;
j = 0;
l1 = 0L;
if (k >= paramTrack.editListDurations.length)
break label1872;
l2 = paramTrack.editListMediaTimes[k];
l3 = paramTrack.editListDurations[k];
if (l2 == -1L)
break label1958;
l4 = Util.scaleLargeTimestamp(l3, paramTrack.timescale, paramTrack.movieTimescale);
m = Util.binarySearchCeil(localObject3, l2, true, true);
i3 = Util.binarySearchCeil(localObject3, l2 + l4, true, false);
if (i2 != 0)
{
i1 = i3 - m;
System.arraycopy(paramContainerAtom, m, paramGaplessInfoHolder, j, i1);
System.arraycopy(localObject1, m, localObject4, j, i1);
System.arraycopy(localObject2, m, localObject5, j, i1);
}
while (m < i3)
{
l4 = Util.scaleLargeTimestamp(l1, 1000000L, paramTrack.movieTimescale);
localObject6[j] = (Util.scaleLargeTimestamp(localObject3[m] - l2, 1000000L, paramTrack.timescale) + l4);
i1 = i;
if (i2 != 0)
{
i1 = i;
if (localObject4[j] > i)
i1 = localObject1[m];
}
j += 1;
m += 1;
i = i1;
}
m = 0;
break;
paramGaplessInfoHolder = paramContainerAtom;
break label1566;
localObject4 = localObject1;
break label1577;
break label1584;
}
label1958:
while (true)
{
k += 1;
l1 = l3 + l1;
break;
label1872: k = 0;
j = 0;
if ((j < localObject5.length) && (k == 0))
{
if ((localObject5[j] & 0x1) != 0);
for (m = 1; ; m = 0)
{
k |= m;
j += 1;
break;
}
}
if (k == 0)
throw new ParserException("The edited sample sequence does not contain a sync sample.");
return new TrackSampleTable(paramGaplessInfoHolder, localObject4, i, localObject6, localObject5);
}
label1961: i2 = m;
m = k;
}
i = j;
j = k;
}
label1986: m = i;
i13 = i7;
}
label1996: i = -1;
paramContainerAtom = (Atom.ContainerAtom)localObject1;
j = 0;
}
}
private static StsdData parseStsd(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2, String paramString, DrmInitData paramDrmInitData, boolean paramBoolean)
{
paramParsableByteArray.setPosition(12);
int j = paramParsableByteArray.readInt();
StsdData localStsdData = new StsdData(j);
int i = 0;
if (i < j)
{
int k = paramParsableByteArray.getPosition();
int m = paramParsableByteArray.readInt();
boolean bool;
label53: int n;
if (m > 0)
{
bool = true;
Assertions.checkArgument(bool, "childAtomSize should be positive");
n = paramParsableByteArray.readInt();
if ((n != Atom.TYPE_avc1) && (n != Atom.TYPE_avc3) && (n != Atom.TYPE_encv) && (n != Atom.TYPE_mp4v) && (n != Atom.TYPE_hvc1) && (n != Atom.TYPE_hev1) && (n != Atom.TYPE_s263) && (n != Atom.TYPE_vp08) && (n != Atom.TYPE_vp09))
break label180;
parseVideoSampleEntry(paramParsableByteArray, n, k, m, paramInt1, paramInt2, paramDrmInitData, localStsdData, i);
}
while (true)
{
paramParsableByteArray.setPosition(k + m);
i += 1;
break;
bool = false;
break label53;
label180: if ((n == Atom.TYPE_mp4a) || (n == Atom.TYPE_enca) || (n == Atom.TYPE_ac_3) || (n == Atom.TYPE_ec_3) || (n == Atom.TYPE_dtsc) || (n == Atom.TYPE_dtse) || (n == Atom.TYPE_dtsh) || (n == Atom.TYPE_dtsl) || (n == Atom.TYPE_samr) || (n == Atom.TYPE_sawb) || (n == Atom.TYPE_lpcm) || (n == Atom.TYPE_sowt) || (n == Atom.TYPE__mp3))
{
parseAudioSampleEntry(paramParsableByteArray, n, k, m, paramInt1, paramString, paramBoolean, paramDrmInitData, localStsdData, i);
continue;
}
if (n == Atom.TYPE_TTML)
{
localStsdData.format = Format.createTextSampleFormat(Integer.toString(paramInt1), "application/ttml+xml", null, -1, 0, paramString, paramDrmInitData);
continue;
}
if (n == Atom.TYPE_tx3g)
{
localStsdData.format = Format.createTextSampleFormat(Integer.toString(paramInt1), "application/x-quicktime-tx3g", null, -1, 0, paramString, paramDrmInitData);
continue;
}
if (n == Atom.TYPE_wvtt)
{
localStsdData.format = Format.createTextSampleFormat(Integer.toString(paramInt1), "application/x-mp4vtt", null, -1, 0, paramString, paramDrmInitData);
continue;
}
if (n == Atom.TYPE_stpp)
{
localStsdData.format = Format.createTextSampleFormat(Integer.toString(paramInt1), "application/ttml+xml", null, -1, 0, paramString, paramDrmInitData, 0L);
continue;
}
if (n == Atom.TYPE_c608)
{
localStsdData.format = Format.createTextSampleFormat(Integer.toString(paramInt1), "application/cea-608", null, -1, 0, paramString, paramDrmInitData);
localStsdData.requiredSampleTransformation = 1;
continue;
}
if (n != Atom.TYPE_camm)
continue;
localStsdData.format = Format.createSampleFormat(Integer.toString(paramInt1), "application/x-camera-motion", null, -1, paramDrmInitData);
}
}
return localStsdData;
}
private static TkhdData parseTkhd(ParsableByteArray paramParsableByteArray)
{
int j = 8;
paramParsableByteArray.setPosition(8);
int i1 = Atom.parseFullAtomVersion(paramParsableByteArray.readInt());
int i;
int n;
int m;
label62: int k;
long l1;
if (i1 == 0)
{
i = 8;
paramParsableByteArray.skipBytes(i);
n = paramParsableByteArray.readInt();
paramParsableByteArray.skipBytes(4);
m = 1;
int i2 = paramParsableByteArray.getPosition();
i = j;
if (i1 == 0)
i = 4;
j = 0;
k = m;
if (j < i)
{
if (paramParsableByteArray.data[(i2 + j)] == -1)
break label177;
k = 0;
}
if (k == 0)
break label184;
paramParsableByteArray.skipBytes(i);
l1 = -9223372036854775807L;
paramParsableByteArray.skipBytes(16);
i = paramParsableByteArray.readInt();
j = paramParsableByteArray.readInt();
paramParsableByteArray.skipBytes(4);
k = paramParsableByteArray.readInt();
m = paramParsableByteArray.readInt();
if ((i != 0) || (j != 65536) || (k != -65536) || (m != 0))
break label223;
i = 90;
}
while (true)
{
return new TkhdData(n, l1, i);
i = 16;
break;
label177: j += 1;
break label62;
label184: long l2;
if (i1 == 0)
l2 = paramParsableByteArray.readUnsignedInt();
while (true)
{
l1 = l2;
if (l2 != 0L)
break;
l1 = -9223372036854775807L;
break;
l2 = paramParsableByteArray.readUnsignedLongToLong();
}
label223: if ((i == 0) && (j == -65536) && (k == 65536) && (m == 0))
{
i = 270;
continue;
}
if ((i == -65536) && (j == 0) && (k == 0) && (m == -65536))
{
i = 180;
continue;
}
i = 0;
}
}
public static Track parseTrak(Atom.ContainerAtom paramContainerAtom, Atom.LeafAtom paramLeafAtom, long paramLong, DrmInitData paramDrmInitData, boolean paramBoolean)
{
Atom.ContainerAtom localContainerAtom1 = paramContainerAtom.getContainerAtomOfType(Atom.TYPE_mdia);
int i = parseHdlr(localContainerAtom1.getLeafAtomOfType(Atom.TYPE_hdlr).data);
if (i == -1)
return null;
TkhdData localTkhdData = parseTkhd(paramContainerAtom.getLeafAtomOfType(Atom.TYPE_tkhd).data);
if (paramLong == -9223372036854775807L)
paramLong = localTkhdData.duration;
while (true)
{
long l = parseMvhd(paramLeafAtom.data);
if (paramLong == -9223372036854775807L)
paramLong = -9223372036854775807L;
while (true)
{
Atom.ContainerAtom localContainerAtom2 = localContainerAtom1.getContainerAtomOfType(Atom.TYPE_minf).getContainerAtomOfType(Atom.TYPE_stbl);
paramLeafAtom = parseMdhd(localContainerAtom1.getLeafAtomOfType(Atom.TYPE_mdhd).data);
paramDrmInitData = parseStsd(localContainerAtom2.getLeafAtomOfType(Atom.TYPE_stsd).data, localTkhdData.id, localTkhdData.rotationDegrees, (String)paramLeafAtom.second, paramDrmInitData, paramBoolean);
paramContainerAtom = parseEdts(paramContainerAtom.getContainerAtomOfType(Atom.TYPE_edts));
if (paramDrmInitData.format != null)
break;
return null;
paramLong = Util.scaleLargeTimestamp(paramLong, 1000000L, l);
}
return new Track(localTkhdData.id, i, ((Long)paramLeafAtom.first).longValue(), l, paramLong, paramDrmInitData.format, paramDrmInitData.requiredSampleTransformation, paramDrmInitData.trackEncryptionBoxes, paramDrmInitData.nalUnitLengthFieldLength, (long[])paramContainerAtom.first, (long[])paramContainerAtom.second);
}
}
public static Metadata parseUdta(Atom.LeafAtom paramLeafAtom, boolean paramBoolean)
{
if (paramBoolean);
while (true)
{
return null;
paramLeafAtom = paramLeafAtom.data;
paramLeafAtom.setPosition(8);
while (paramLeafAtom.bytesLeft() >= 8)
{
int i = paramLeafAtom.getPosition();
int j = paramLeafAtom.readInt();
if (paramLeafAtom.readInt() == Atom.TYPE_meta)
{
paramLeafAtom.setPosition(i);
return parseMetaAtom(paramLeafAtom, i + j);
}
paramLeafAtom.skipBytes(j - 8);
}
}
}
private static void parseVideoSampleEntry(ParsableByteArray paramParsableByteArray, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, DrmInitData paramDrmInitData, StsdData paramStsdData, int paramInt6)
{
paramParsableByteArray.setPosition(paramInt2 + 8);
paramParsableByteArray.skipBytes(24);
int m = paramParsableByteArray.readUnsignedShort();
int n = paramParsableByteArray.readUnsignedShort();
int k = 0;
float f = 1.0F;
paramParsableByteArray.skipBytes(50);
int j = paramParsableByteArray.getPosition();
int i = paramInt1;
if (paramInt1 == Atom.TYPE_encv)
{
i = parseSampleEntryEncryptionData(paramParsableByteArray, paramInt2, paramInt3, paramStsdData, paramInt6);
paramParsableByteArray.setPosition(j);
}
Object localObject1 = null;
String str = null;
byte[] arrayOfByte = null;
paramInt6 = -1;
paramInt1 = k;
int i1;
if (j - paramInt2 < paramInt3)
{
paramParsableByteArray.setPosition(j);
i1 = paramParsableByteArray.getPosition();
k = paramParsableByteArray.readInt();
if ((k != 0) || (paramParsableByteArray.getPosition() - paramInt2 != paramInt3));
}
else
{
if (str != null)
break label573;
return;
}
boolean bool;
label142: int i2;
label171: Object localObject2;
if (k > 0)
{
bool = true;
Assertions.checkArgument(bool, "childAtomSize should be positive");
i2 = paramParsableByteArray.readInt();
if (i2 != Atom.TYPE_avcC)
break label246;
if (str != null)
break label240;
bool = true;
Assertions.checkState(bool);
str = "video/avc";
paramParsableByteArray.setPosition(i1 + 8);
localObject2 = AvcConfig.parse(paramParsableByteArray);
localObject1 = ((AvcConfig)localObject2).initializationData;
paramStsdData.nalUnitLengthFieldLength = ((AvcConfig)localObject2).nalUnitLengthFieldLength;
if (paramInt1 == 0)
f = ((AvcConfig)localObject2).pixelWidthAspectRatio;
}
while (true)
{
j += k;
break;
bool = false;
break label142;
label240: bool = false;
break label171;
label246: if (i2 == Atom.TYPE_hvcC)
{
if (str == null);
for (bool = true; ; bool = false)
{
Assertions.checkState(bool);
str = "video/hevc";
paramParsableByteArray.setPosition(i1 + 8);
localObject2 = HevcConfig.parse(paramParsableByteArray);
localObject1 = ((HevcConfig)localObject2).initializationData;
paramStsdData.nalUnitLengthFieldLength = ((HevcConfig)localObject2).nalUnitLengthFieldLength;
break;
}
}
if (i2 == Atom.TYPE_vpcC)
{
if (str == null)
{
bool = true;
label329: Assertions.checkState(bool);
if (i != Atom.TYPE_vp08)
break label356;
}
label356: for (str = "video/x-vnd.on2.vp8"; ; str = "video/x-vnd.on2.vp9")
{
break;
bool = false;
break label329;
}
}
if (i2 == Atom.TYPE_d263)
{
if (str == null);
for (bool = true; ; bool = false)
{
Assertions.checkState(bool);
str = "video/3gpp";
break;
}
}
if (i2 == Atom.TYPE_esds)
{
if (str == null);
for (bool = true; ; bool = false)
{
Assertions.checkState(bool);
localObject1 = parseEsdsFromParent(paramParsableByteArray, i1);
str = (String)((Pair)localObject1).first;
localObject1 = Collections.singletonList(((Pair)localObject1).second);
break;
}
}
if (i2 == Atom.TYPE_pasp)
{
f = parsePaspFromParent(paramParsableByteArray, i1);
paramInt1 = 1;
continue;
}
if (i2 == Atom.TYPE_sv3d)
{
arrayOfByte = parseProjFromParent(paramParsableByteArray, i1, k);
continue;
}
if (i2 == Atom.TYPE_st3d)
{
i1 = paramParsableByteArray.readUnsignedByte();
paramParsableByteArray.skipBytes(3);
if (i1 != 0);
}
switch (paramParsableByteArray.readUnsignedByte())
{
default:
break;
case 0:
paramInt6 = 0;
break;
case 1:
paramInt6 = 1;
break;
case 2:
paramInt6 = 2;
}
}
label573: paramStsdData.format = Format.createVideoSampleFormat(Integer.toString(paramInt4), str, null, -1, -1, m, n, -1.0F, (List)localObject1, paramInt5, f, arrayOfByte, paramInt6, paramDrmInitData);
}
private static final class ChunkIterator
{
private final ParsableByteArray chunkOffsets;
private final boolean chunkOffsetsAreLongs;
public int index;
public final int length;
private int nextSamplesPerChunkChangeIndex;
public int numSamples;
public long offset;
private int remainingSamplesPerChunkChanges;
private final ParsableByteArray stsc;
public ChunkIterator(ParsableByteArray paramParsableByteArray1, ParsableByteArray paramParsableByteArray2, boolean paramBoolean)
{
this.stsc = paramParsableByteArray1;
this.chunkOffsets = paramParsableByteArray2;
this.chunkOffsetsAreLongs = paramBoolean;
paramParsableByteArray2.setPosition(12);
this.length = paramParsableByteArray2.readUnsignedIntToInt();
paramParsableByteArray1.setPosition(12);
this.remainingSamplesPerChunkChanges = paramParsableByteArray1.readUnsignedIntToInt();
if (paramParsableByteArray1.readInt() == 1);
for (paramBoolean = bool; ; paramBoolean = false)
{
Assertions.checkState(paramBoolean, "first_chunk must be 1");
this.index = -1;
return;
}
}
public boolean moveNext()
{
int i = this.index + 1;
this.index = i;
if (i == this.length)
return false;
long l;
if (this.chunkOffsetsAreLongs)
{
l = this.chunkOffsets.readUnsignedLongToLong();
this.offset = l;
if (this.index == this.nextSamplesPerChunkChangeIndex)
{
this.numSamples = this.stsc.readUnsignedIntToInt();
this.stsc.skipBytes(4);
i = this.remainingSamplesPerChunkChanges - 1;
this.remainingSamplesPerChunkChanges = i;
if (i <= 0)
break label116;
}
}
label116: for (i = this.stsc.readUnsignedIntToInt() - 1; ; i = -1)
{
this.nextSamplesPerChunkChangeIndex = i;
return true;
l = this.chunkOffsets.readUnsignedInt();
break;
}
}
}
private static abstract interface SampleSizeBox
{
public abstract int getSampleCount();
public abstract boolean isFixedSampleSize();
public abstract int readNextSampleSize();
}
private static final class StsdData
{
public Format format;
public int nalUnitLengthFieldLength;
public int requiredSampleTransformation;
public final TrackEncryptionBox[] trackEncryptionBoxes;
public StsdData(int paramInt)
{
this.trackEncryptionBoxes = new TrackEncryptionBox[paramInt];
this.requiredSampleTransformation = 0;
}
}
static final class StszSampleSizeBox
implements AtomParsers.SampleSizeBox
{
private final ParsableByteArray data;
private final int fixedSampleSize;
private final int sampleCount;
public StszSampleSizeBox(Atom.LeafAtom paramLeafAtom)
{
this.data = paramLeafAtom.data;
this.data.setPosition(12);
this.fixedSampleSize = this.data.readUnsignedIntToInt();
this.sampleCount = this.data.readUnsignedIntToInt();
}
public int getSampleCount()
{
return this.sampleCount;
}
public boolean isFixedSampleSize()
{
return this.fixedSampleSize != 0;
}
public int readNextSampleSize()
{
if (this.fixedSampleSize == 0)
return this.data.readUnsignedIntToInt();
return this.fixedSampleSize;
}
}
static final class Stz2SampleSizeBox
implements AtomParsers.SampleSizeBox
{
private int currentByte;
private final ParsableByteArray data;
private final int fieldSize;
private final int sampleCount;
private int sampleIndex;
public Stz2SampleSizeBox(Atom.LeafAtom paramLeafAtom)
{
this.data = paramLeafAtom.data;
this.data.setPosition(12);
this.fieldSize = (this.data.readUnsignedIntToInt() & 0xFF);
this.sampleCount = this.data.readUnsignedIntToInt();
}
public int getSampleCount()
{
return this.sampleCount;
}
public boolean isFixedSampleSize()
{
return false;
}
public int readNextSampleSize()
{
if (this.fieldSize == 8)
return this.data.readUnsignedByte();
if (this.fieldSize == 16)
return this.data.readUnsignedShort();
int i = this.sampleIndex;
this.sampleIndex = (i + 1);
if (i % 2 == 0)
{
this.currentByte = this.data.readUnsignedByte();
return (this.currentByte & 0xF0) >> 4;
}
return this.currentByte & 0xF;
}
}
private static final class TkhdData
{
private final long duration;
private final int id;
private final int rotationDegrees;
public TkhdData(int paramInt1, long paramLong, int paramInt2)
{
this.id = paramInt1;
this.duration = paramLong;
this.rotationDegrees = paramInt2;
}
}
}
/* Location: C:\Documents and Settings\soran\Desktop\s\classes.jar
* Qualified Name: org.vidogram.messenger.exoplayer2.extractor.mp4.AtomParsers
* JD-Core Version: 0.6.0
*/ | gpl-2.0 |
sanyaade-iot/freedomotic-android-client | src/es/gpulido/freedomotic/ui/RoomsFragment.java | 6334 | package es.gpulido.freedomotic.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.viewpagerindicator.TitlePageIndicator;
import es.gpulido.freedomotic.R;
import es.gpulido.freedomotic.api.EnvironmentController;
//Thanks to http://tamsler.blogspot.com/2011/11/android-viewpager-and-fragments-part-ii.html
public class RoomsFragment extends SherlockFragment implements Observer{
public static int NUM_ITEMS = 0;
RoomsAdapter mAdapter;
ViewPager mPager;
static boolean mInitialized = false;
TitlePageIndicator titleIndicator;
//this is outside the adapter, to prevent the reinitialization of the hashmap.
//AS the getView is not always called this maintains in sync the data
protected static SparseArray<ZoneObjectListFragment> mPageReferenceMap= new SparseArray<ZoneObjectListFragment>();
//
// @Override
// public void onAttach(android.app.Activity activity) {
// System.out.println("GPT Rooms: onAttach");
// super.onAttach(activity);
//
// };
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// System.out.println("GPT Rooms: onCreate");
// super.onCreate(savedInstanceState);
//
// };
//
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// System.out.println("GPT Rooms: onActivityCreated");
// super.onActivityCreated(savedInstanceState);
// };
//
// @Override
// public void onStart() {
// System.out.println("GPT Rooms: onStart");
// super.onStart();
//
// };
//
// @Override
// public void onResume() {
// System.out.println("GPT Rooms: onResume");
// super.onResume();
//
// };
//
// @Override
// public void onPause() {
// System.out.println("GPT Rooms: onPause");
// // mAdapter.saveState();
// super.onPause();
//
// };
//
// @Override
// public void onStop() {
// System.out.println("GPT Rooms: onStop");
// super.onStop();
//
// };
// @Override
// public void onDestroyView() {
// System.out.println("GPT Rooms: onDestroyView");
// super.onDestroyView();
//
// };
// @Override
// public void onDestroy() {
// System.out.println("GPT Rooms: onDestroy");
// super.onDestroy();
//
// };
//
// @Override
// public void onDetach() {
// System.out.println("GPT Rooms: onDetach");
// super.onDetach();
//
// };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null)
return null;
View vi = inflater.inflate(R.layout.fragment_roomselecter, container,false);
mPager = (ViewPager) vi.findViewById(R.id.room_panel_pager);
mAdapter = new RoomsAdapter(getSherlockActivity().getSupportFragmentManager());
new setAdapterTask().execute();
// Bind the ViewPager to ViewPagerTabs
titleIndicator = (TitlePageIndicator) vi.findViewById(R.id.tabtitles);
titleIndicator.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageSelected(int currentIndex) {
ZoneObjectListFragment zoneFragment = ((RoomsAdapter)mPager.getAdapter()).getFragment(currentIndex);
if (zoneFragment != null)
zoneFragment.selectItem();
}
});
initialize();
return vi;
}
@Override
public void onResume() {
super.onResume();
EnvironmentController.getInstance().addObserver(this);
};
@Override
public void onPause() {
EnvironmentController.getInstance().deleteObserver(this);
super.onPause();
};
private class setAdapterTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(Void result) {
mPager.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
titleIndicator.setViewPager(mPager);
}
}
protected void initialize() {
if (EnvironmentController.getInstance().getEnvironment() != null)
{
RoomsFragment.mInitialized = true;
}
}
public static class RoomsAdapter extends FragmentPagerAdapter {
public RoomsAdapter (FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
if (RoomsFragment.mInitialized){
return EnvironmentController.getInstance().getNonEmptyRooms().size();
}
return 0;
}
@Override
public SherlockListFragment getItem(int position) {
//TODO: figure out how to make it circular
//TestFragment.newInstance(CONTENT[position % CONTENT.length])
ZoneObjectListFragment zoneFragment = ZoneObjectListFragment.newInstance(position);
mPageReferenceMap.put(Integer.valueOf(position), zoneFragment);
return zoneFragment;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
};
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return EnvironmentController.getInstance().getNonEmptyRoom(position).getName().toUpperCase();
}
@Override
public void destroyItem(View container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(Integer.valueOf(position));
}
public ZoneObjectListFragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
}
public void update(Observable observable, Object data) {
initialize();
getActivity().runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
}
| gpl-2.0 |
SeekingFor/jfniki | alien/src/net/pterodactylus/fcp/AllData.java | 3210 | /*
* jFCPlib - AllData.java - Copyright © 2008 David Roden
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.pterodactylus.fcp;
import java.io.InputStream;
/**
* The “AllData” message carries the payload of a successful {@link ClientGet}
* request. You will only received this message if the {@link ClientGet} request
* was started with a return type of {@link ReturnType#direct}. If you get this
* message and decide that the data is for you, call
* {@link #getPayloadInputStream()} to get the data. If an AllData message
* passes through all registered {@link FcpListener}s without the payload being
* consumed, the payload is discarded!
*
* @author David ‘Bombe’ Roden <bombe@freenetproject.org>
*/
public class AllData extends BaseMessage {
/** The payload. */
private InputStream payloadInputStream;
/**
* Creates an “AllData” message that wraps the received message.
*
* @param receivedMessage
* The received message
* @param payloadInputStream
* The payload
*/
AllData(FcpMessage receivedMessage, InputStream payloadInputStream) {
super(receivedMessage);
this.payloadInputStream = payloadInputStream;
}
/**
* Returns the identifier of the request.
*
* @return The identifier of the request
*/
public String getIdentifier() {
return getField("Identifier");
}
/**
* Returns the length of the data.
*
* @return The length of the data, or <code>-1</code> if the length could
* not be parsed
*/
public long getDataLength() {
return FcpUtils.safeParseLong(getField("DataLength"));
}
/**
* Returns the startup time of the request.
*
* @return The startup time of the request (in milliseconds since Jan 1,
* 1970 UTC), or <code>-1</code> if the time could not be parsed
*/
public long getStartupTime() {
return FcpUtils.safeParseLong(getField("StartupTime"));
}
/**
* Returns the completion time of the request.
*
* @return The completion time of the request (in milliseconds since Jan 1,
* 1970 UTC), or <code>-1</code> if the time could not be parsed
*/
public long getCompletionTime() {
return FcpUtils.safeParseLong(getField("CompletionTime"));
}
/**
* Returns the payload input stream. You <strong>have</strong> consume the
* input stream before returning from the
* {@link FcpListener#receivedAllData(FcpConnection, AllData)} method!
*
* @return The payload
*/
public InputStream getPayloadInputStream() {
return payloadInputStream;
}
}
| gpl-2.0 |
zet-evacuation/evacuation-cellular-automaton | src/test/java/org/zet/cellularautomaton/BaseTeleportCellTest.java | 4376 | /* zet evacuation tool copyright (c) 2007-20 zet evacuation team
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.zet.cellularautomaton;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.zet.cellularautomaton.algorithm.TestEvacuationCellularAutomatonAlgorithm.MockEvacCell;
/**
*
* @author Jan-Philipp Kappmeier
*/
public class BaseTeleportCellTest {
private static class FakeBaseTeleportCell extends BaseTeleportCell<MockEvacCell> {
List<MockEvacCell> removed = new LinkedList<>();
public FakeBaseTeleportCell() {
super(new EvacuationCellState(null), 1, 0, 0);
}
@Override
public void addTarget(MockEvacCell target) {
}
@Override
public void removeTarget(MockEvacCell target) {
super.teleportTargets.remove(target);
removed.add(target);
}
@Override
public EvacCell clone() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Test
public void initialization() {
BaseTeleportCell cell = new FakeBaseTeleportCell();
assertThat(cell.targetCount(), is(equalTo(0)));
}
@Test
public void removeAllRemovesAll() {
FakeBaseTeleportCell cell = new FakeBaseTeleportCell();
MockEvacCell cell1 = new MockEvacCell(0, 0);
MockEvacCell cell2 = new MockEvacCell(0, 1);
MockEvacCell cell3 = new MockEvacCell(1, 1);
cell.addTargetSimple(cell1);
cell.addTargetSimple(cell2);
cell.addTargetSimple(cell3);
cell.removeAllTargets();
assertThat(cell.removed, contains(new MockEvacCell[] {cell1, cell2, cell3}));
}
@Test
public void sizeCalculation() {
FakeBaseTeleportCell cell = new FakeBaseTeleportCell();
MockEvacCell cell1 = new MockEvacCell(0, 0);
MockEvacCell cell2 = new MockEvacCell(0, 1);
MockEvacCell cell3 = new MockEvacCell(1, 1);
cell.addTargetSimple(cell1);
cell.addTargetSimple(cell2);
assertThat(cell.targetCount(), is(equalTo(2)));
assertThat(cell.containsTarget(cell1), is(true));
assertThat(cell.containsTarget(cell2), is(true));
assertThat(cell.containsTarget(cell3), is(false));
cell.removeTarget(cell2);
assertThat(cell.containsTarget(cell2), is(false));
assertThat(cell.targetCount(), is(equalTo(1)));
}
@Test
public void noDoubleInsert() {
FakeBaseTeleportCell cell = new FakeBaseTeleportCell();
MockEvacCell cell1 = new MockEvacCell(0, 0);
assertThat(cell.targetCount(), is(equalTo(0)));
cell.addTargetSimple(cell1);
assertThat(cell.targetCount(), is(equalTo(1)));
cell.addTargetSimple(cell1);
assertThat(cell.targetCount(), is(equalTo(1)));
}
@Test
public void getByIndex() {
FakeBaseTeleportCell cell = new FakeBaseTeleportCell();
MockEvacCell cell1 = new MockEvacCell(0, 0);
MockEvacCell cell2 = new MockEvacCell(0, 1);
MockEvacCell cell3 = new MockEvacCell(1, 1);
cell.addTargetSimple(cell1);
cell.addTargetSimple(cell2);
cell.addTargetSimple(cell3);
assertThat(cell.getTarget(0), is(equalTo(cell1)));
assertThat(cell.getTarget(1), is(equalTo(cell2)));
assertThat(cell.getTarget(2), is(equalTo(cell3)));
}
}
| gpl-2.0 |
shazangroup/Mobograph | TMessagesProj/src/main/java/org/telegram/ui/Cells/DrawerProfileCell.java | 19010 | /*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.ui.Cells;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.finalsoft.messenger.R;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.VideoEditedInfo;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.PhotoViewer;
public class DrawerProfileCell extends FrameLayout implements PhotoViewer.PhotoViewerProvider{
private BackupImageView avatarImageView;
private TextView nameTextView;
private TextView phoneTextView;
private ImageView shadowView;
private CloudView cloudView;
private Rect srcRect = new Rect();
private Rect destRect = new Rect();
private Paint paint = new Paint();
private int currentColor;
private class CloudView extends View {
private Drawable cloudDrawable;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CloudView(Context context) {
super(context);
cloudDrawable = getResources().getDrawable(R.drawable.cloud);
}
@Override
protected void onDraw(Canvas canvas) {
if (ApplicationLoader.isCustomTheme() && ApplicationLoader.getCachedWallpaper() != null) {
paint.setColor(ApplicationLoader.getServiceMessageColor());
} else {
paint.setColor(0xff427ba9);
}
canvas.drawCircle(getMeasuredWidth() / 2.0f, getMeasuredHeight() / 2.0f, AndroidUtilities.dp(34) / 2.0f, paint);
int l = (getMeasuredWidth() - AndroidUtilities.dp(33)) / 2;
int t = (getMeasuredHeight() - AndroidUtilities.dp(33)) / 2;
cloudDrawable.setBounds(l, t, l + AndroidUtilities.dp(33), t + AndroidUtilities.dp(33));
cloudDrawable.draw(canvas);
}
}
public DrawerProfileCell(Context context) {
super(context);
setBackgroundColor(Theme.ACTION_BAR_PROFILE_COLOR);
shadowView = new ImageView(context);
shadowView.setVisibility(INVISIBLE);
shadowView.setScaleType(ImageView.ScaleType.FIT_XY);
shadowView.setImageResource(R.drawable.bottom_shadow);
addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 70, Gravity.LEFT | Gravity.BOTTOM));
SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
avatarImageView = new BackupImageView(context);
avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(32));
int aSize = themePrefs.getInt("drawerAvatarSize", 64);
boolean centerAvatar = themePrefs.getBoolean("drawerCenterAvatarCheck", false);
//addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 0, 67));
if(!centerAvatar){
addView(avatarImageView, LayoutHelper.createFrame(aSize, aSize, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 0, 67));
}else{
addView(avatarImageView, LayoutHelper.createFrame(aSize, aSize, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 67));
}
final Activity activity = (Activity) context;
avatarImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (activity == null) {
return;
}
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(activity);
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, DrawerProfileCell.this);
}
}
});
nameTextView = new TextView(context);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
nameTextView.setLines(1);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
if(!centerAvatar){
nameTextView.setGravity(Gravity.LEFT);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 16, 28));
}else{
nameTextView.setGravity(Gravity.CENTER);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 28));
}
phoneTextView = new TextView(context);
phoneTextView.setTextColor(0xffc2e5ff);
phoneTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
phoneTextView.setLines(1);
phoneTextView.setMaxLines(1);
phoneTextView.setSingleLine(true);
if(!centerAvatar){
phoneTextView.setGravity(Gravity.LEFT);
addView(phoneTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 16, 9));
}else{
phoneTextView.setGravity(Gravity.CENTER);
addView(phoneTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 9));
}
cloudView = new CloudView(context);
addView(cloudView, LayoutHelper.createFrame(61, 61, Gravity.RIGHT | Gravity.BOTTOM));
}
public void refreshAvatar(int size, int radius){
//SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
removeView(avatarImageView);
removeView(nameTextView);
removeView(phoneTextView);
avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(radius));
SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
if(!themePrefs.getBoolean("drawerCenterAvatarCheck", false)){
addView(avatarImageView, LayoutHelper.createFrame(size, size, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 0, 67));
nameTextView.setGravity(Gravity.LEFT);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 16, 28));
phoneTextView.setGravity(Gravity.LEFT);
addView(phoneTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 16, 9));
}else{
addView(avatarImageView, LayoutHelper.createFrame(size, size, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 67));
nameTextView.setGravity(Gravity.CENTER);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 28));
phoneTextView.setGravity(Gravity.CENTER);
addView(phoneTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 0, 9));
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (Build.VERSION.SDK_INT >= 21) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(148) + AndroidUtilities.statusBarHeight, MeasureSpec.EXACTLY));
} else {
try {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(148), MeasureSpec.EXACTLY));
} catch (Exception e) {
FileLog.e( e);
}
}
//SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences plusPreferences = ApplicationLoader.applicationContext.getSharedPreferences("TelegramConfig", Activity.MODE_PRIVATE);
if(plusPreferences.getBoolean("hideMobile", false) && !plusPreferences.getBoolean("showUsername", false)){
phoneTextView.setVisibility(GONE);
}else{
phoneTextView.setVisibility(VISIBLE);
}
}
@Override
protected void onDraw(Canvas canvas) {
Drawable backgroundDrawable = ApplicationLoader.getCachedWallpaper();
int color = ApplicationLoader.getServiceMessageColor();
if (currentColor != color) {
currentColor = color;
shadowView.getDrawable().setColorFilter(new PorterDuffColorFilter(color | 0xff000000, PorterDuff.Mode.MULTIPLY));
}
SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
if (ApplicationLoader.isCustomTheme() && backgroundDrawable != null && !themePrefs.getBoolean("drawerHeaderBGCheck", false)) {
phoneTextView.setTextColor(0xffffffff);
int visible = INVISIBLE;
if(!themePrefs.getBoolean("drawerHideBGShadowCheck", false)){
visible = VISIBLE;
}
shadowView.setVisibility(visible);
if (backgroundDrawable instanceof ColorDrawable) {
backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
backgroundDrawable.draw(canvas);
} else if (backgroundDrawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) backgroundDrawable).getBitmap();
float scaleX = (float) getMeasuredWidth() / (float) bitmap.getWidth();
float scaleY = (float) getMeasuredHeight() / (float) bitmap.getHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int) (getMeasuredWidth() / scale);
int height = (int) (getMeasuredHeight() / scale);
int x = (bitmap.getWidth() - width) / 2;
int y = (bitmap.getHeight() - height) / 2;
srcRect.set(x, y, x + width, y + height);
destRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawBitmap(bitmap, srcRect, destRect, paint);
}
} else {
shadowView.setVisibility(INVISIBLE);
phoneTextView.setTextColor(0xffc2e5ff);
super.onDraw(canvas);
}
updateTheme();
}
public void setUser(TLRPC.User user) {
if (user == null) {
return;
}
TLRPC.FileLocation photo = null;
if (user.photo != null) {
photo = user.photo.photo_small;
}
nameTextView.setText(UserObject.getUserName(user));
//phoneTextView.setText(PhoneFormat.getInstance().format("+" + user.phone));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("TelegramConfig", Activity.MODE_PRIVATE);
String value;
if(preferences.getBoolean("showUsername", false)) {
if (user.username != null && user.username.length() != 0) {
value = "@" + user.username;
} else {
value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty);
}
} else{
value = PhoneFormat.getInstance().format("+" + user.phone);
}
phoneTextView.setText(value);
AvatarDrawable avatarDrawable = new AvatarDrawable(user);
avatarDrawable.setColor(Theme.ACTION_BAR_MAIN_AVATAR_COLOR);
avatarImageView.setImage(photo, "50_50", avatarDrawable);
updateTheme();
}
@Override
public void updatePhotoAtIndex(int index) {}
@Override
public boolean allowCaption() {
return false;
}
@Override
public boolean scaleToFill() {
return false;
}
@Override
public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
if (fileLocation == null) {
return null;
}
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
TLRPC.FileLocation photoBig = user.photo.photo_big;
if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) {
int coords[] = new int[2];
avatarImageView.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = avatarImageView;
object.imageReceiver = avatarImageView.getImageReceiver();
object.dialogId = UserConfig.getClientUserId();
object.thumb = object.imageReceiver.getBitmap();
object.size = -1;
object.radius = avatarImageView.getImageReceiver().getRoundRadius();
return object;
}
}
return null;
}
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
return null;
}
@Override
public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { }
@Override
public void willHidePhotoViewer() {
avatarImageView.getImageReceiver().setVisible(true, true);
}
@Override
public boolean isPhotoChecked(int index) { return false; }
@Override
public void setPhotoChecked(int index) { }
@Override
public boolean cancelButtonPressed() {
return true;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo) {
}
@Override
public int getSelectedCount() { return 0; }
private void updateTheme(){
SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
int tColor = themePrefs.getInt("themeColor", AndroidUtilities.defColor);
int dColor = AndroidUtilities.getIntDarkerColor("themeColor", -0x40);
int hColor = themePrefs.getInt("drawerHeaderColor", tColor);
setBackgroundColor(hColor);
int value = themePrefs.getInt("drawerHeaderGradient", 0);
if(value > 0) {
GradientDrawable.Orientation go;
switch(value) {
case 2:
go = GradientDrawable.Orientation.LEFT_RIGHT;
break;
case 3:
go = GradientDrawable.Orientation.TL_BR;
break;
case 4:
go = GradientDrawable.Orientation.BL_TR;
break;
default:
go = GradientDrawable.Orientation.TOP_BOTTOM;
}
int gradColor = themePrefs.getInt("drawerHeaderGradientColor", tColor);
int[] colors = new int[]{hColor, gradColor};
GradientDrawable gd = new GradientDrawable(go, colors);
setBackgroundDrawable(gd);
}
nameTextView.setTextColor(themePrefs.getInt("drawerNameColor", 0xffffffff));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, themePrefs.getInt("drawerNameSize", 15));
phoneTextView.setTextColor(themePrefs.getInt("drawerPhoneColor", dColor));
phoneTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, themePrefs.getInt("drawerPhoneSize", 13));
//SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences plusPreferences = ApplicationLoader.applicationContext.getSharedPreferences("TelegramConfig", Activity.MODE_PRIVATE);
if(plusPreferences.getBoolean("hideMobile", false) && !plusPreferences.getBoolean("showUsername", false)){
phoneTextView.setVisibility(GONE);
}else{
phoneTextView.setVisibility(VISIBLE);
}
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
TLRPC.FileLocation photo = null;
if (user != null && user.photo != null && user.photo.photo_small != null ) {
photo = user.photo.photo_small;
}
AvatarDrawable avatarDrawable = new AvatarDrawable(user);
avatarDrawable.setColor(themePrefs.getInt("drawerAvatarColor", AndroidUtilities.getIntDarkerColor("themeColor", 0x15)));
int radius = AndroidUtilities.dp(themePrefs.getInt("drawerAvatarRadius", 32));
avatarDrawable.setRadius(radius);
//avatarImageView.getImageReceiver().setImageCoords(avatarImageView.getImageReceiver(), avatarTop, avatarSize, avatarSize);
avatarImageView.getImageReceiver().setRoundRadius(radius);
avatarImageView.setImage(photo, "50_50", avatarDrawable);
}
private void updateHeaderBG(){
}
@Override
public void invalidate() {
super.invalidate();
cloudView.invalidate();
}
}
| gpl-2.0 |
stelfrich/openmicroscopy | components/server/src/ome/services/scripts/ScriptRepoHelper.java | 24908 | /*
* $Id$
*
* Copyright 2010 Glencoe Software, Inc. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.services.scripts;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ome.api.local.LocalAdmin;
import ome.conditions.ApiUsageException;
import ome.conditions.InternalException;
import ome.conditions.RemovedSessionException;
import ome.model.core.OriginalFile;
import ome.model.enums.ChecksumAlgorithm;
import ome.model.meta.ExperimenterGroup;
import ome.services.delete.Deletion;
import ome.services.graphs.GraphException;
import ome.services.util.Executor;
import ome.system.EventContext;
import ome.system.Principal;
import ome.system.Roles;
import ome.system.ServiceFactory;
import ome.tools.hibernate.QueryBuilder;
import ome.tools.spring.OnContextRefreshedEventListener;
import ome.util.SqlAction;
// import omero.util.TempFileManager;
// Note: This cannot be imported because
// it's in the blitz pacakge. TODO
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.CanReadFileFilter;
import org.apache.commons.io.filefilter.EmptyFileFilter;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Session;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.transaction.annotation.Transactional;
/**
* Strategy used by the ScriptRepository for registering, loading, and saving
* files.
*
* @since Beta4.2
*/
public class ScriptRepoHelper extends OnContextRefreshedEventListener {
/**
* Id used by all script repositories. Having a well defined string allows
* for various repositories to all provide the same functionality.
*/
public final static String SCRIPT_REPO = "ScriptRepo";
/**
* {@link IOFileFilter} instance used during {@link #iterate()} to find the
* matching scripts in the given directory.
*/
public final static IOFileFilter BASE_SCRIPT_FILTER = new AndFileFilter(Arrays
.asList(new FileFilter[] { EmptyFileFilter.NOT_EMPTY,
HiddenFileFilter.VISIBLE, CanReadFileFilter.CAN_READ }));
private final Map<String, ScriptFileType> types =
new HashMap<String, ScriptFileType>();
/**
* {@link Set} of mimetypes from each of the {@link ScriptFileType} instances
* in {@link #types}. Not final since the value needs to be made immutable since
* the collection is frequently passed out.
*/
private/* final */ Set<String> mimetypes = new HashSet<String>();
private final String uuid;
private final File dir;
private final Executor ex;
private final Principal p;
private final Roles roles;
/**
* {@link IOFileFilter} set on {@link #handleContextRefreshedEvent(ContextRefreshedEvent).
*/
private/* final */IOFileFilter scriptFilter;
protected final Logger log = LoggerFactory.getLogger(getClass());
/**
* @see #ScriptRepoHelper(String, File, Executor, Principal)
*/
public ScriptRepoHelper(Executor ex, String sessionUuid, Roles roles) {
this(new File(getDefaultScriptDir()), ex, new Principal(sessionUuid),
roles);
}
/**
* @see #ScriptRepoHelper(String, File, Executor, Principal)
*/
public ScriptRepoHelper(File dir, Executor ex, Principal p, Roles roles) {
this(SCRIPT_REPO, dir, ex, p, roles);
}
/**
*
* @param uuid
* Allows setting a non-default uuid for this script service.
* Primarily for testing, since services rely on the repository
* name for finding one another.
* @param dir
* The directory used by the repo as its root. Other constructors
* use {@link #getDefaultScriptDir()} internally.
* @param ex
* @param p
*/
public ScriptRepoHelper(String uuid, File dir, Executor ex, Principal p,
Roles roles) {
this.roles = roles;
this.uuid = uuid;
this.dir = sanityCheck(log, dir);
this.ex = ex;
this.p = p;
}
/**
* Loads all {@link ScriptFileType} instances from the context,
* and uses them to initialize all scripts in the repo.
*/
@Override
public void handleContextRefreshedEvent(ContextRefreshedEvent event) {
types.putAll(
event.getApplicationContext()
.getBeansOfType(ScriptFileType.class));
final List<FileFilter> andFilters = new ArrayList<FileFilter>();
final List<FileFilter> orFilters= new ArrayList<FileFilter>();
for (Map.Entry<String, ScriptFileType> entry : types.entrySet()) {
IOFileFilter found = entry.getValue().getFileFilter();
log.info("Registering {}: {}", entry.getKey(), found);
orFilters.add(found);
mimetypes.add(entry.getValue().getMimetype());
}
mimetypes = Collections.unmodifiableSet(mimetypes);
andFilters.add(BASE_SCRIPT_FILTER);
andFilters.add(new OrFileFilter(orFilters));
this.scriptFilter = new AndFileFilter(andFilters);
try {
loadAll(true);
} catch (RemovedSessionException rse) {
log.error("Script failure!!! RemovedSession on startup: are we testing?");
}
}
/**
* Adds a single clause of the form "AND (A OR B ...)" where each
* {@link ScriptFileType} A, B, etc. is given a chance to define
* its own clause.
*/
public void buildQuery(QueryBuilder qb) {
boolean first = true;
qb.and(" ("); // will prepend "AND" if not first clause.
for (String mimetype : mimetypes) {
if (first) {
first = false;
} else {
qb.append(" OR ");
}
qb.append("o.mimetype = '" + mimetype + "'");
}
qb.append(") ");
}
public void setMimetype(OriginalFile ofile) {
for (Map.Entry<String, ScriptFileType> entry : types.entrySet()) {
if (entry.getValue().setMimetype(ofile)) {
log.debug("Mimetype set by {} for {}",
entry.getKey(), ofile.getName());
return; // EARLY EXIT.
}
}
log.warn("No mimetype set for {}", ofile.getName());
}
/**
* Search through all {@link ScriptFileType} instances and find one with
* a matching mimetype string. Otherwise, return null.
*/
protected Map.Entry<String, ScriptFileType> findByMimetype(String mimetype) {
for (Map.Entry<String, ScriptFileType> entry : types.entrySet()) {
ScriptFileType type = entry.getValue();
if (type.getMimetype().equals(mimetype)) {
return entry;
}
}
return null;
}
/**
* Find an "omero.launcher..." property string for the given mimetype or
* return "" if none is found.
*/
public String getLauncher(String mimetype) {
Map.Entry<String, ScriptFileType> entry = findByMimetype(mimetype);
if (entry == null) {
log.warn("No mimetype equals to {}", mimetype);
return "";
}
return entry.getValue().getLauncher();
}
/**
* Find an "omero.process..." property string for the given mimetype or
* return "" if none is found.
*/
public String getProcess(String mimetype) {
Map.Entry<String, ScriptFileType> entry = findByMimetype(mimetype);
if (entry == null) {
log.warn("No mimetype equals to {}", mimetype);
return "";
}
return entry.getValue().getProcess();
}
/**
* If we're in a testing scenario we need to ignore the fact that there
* is no lib/script directory. Otherwise, all devs will need to mkdir -p
* that directory both at the top-level and under blitz/ etc.
*/
static File sanityCheck(Logger log, File dir) {
String error = null;
String testing = System.getProperty("omero.testing", "false").toLowerCase();
testing = testing.toLowerCase();
if (dir == null) {
throw new InternalException("Null dir!");
}
if (!dir.exists()) {
error = "Does not exist: ";
} else if (!dir.canRead()) {
error = "Cannot read: ";
}
if (error != null) {
if (testing.equals("true")) {
log.error(error + dir.getAbsolutePath());
try {
//dir = TempFileManager.create_path("lib", "scripts", true);
dir = getTmpDir();
} catch (IOException e) {
throw new InternalException(
"Failed to make temp path for testing");
}
} else {
throw new InternalException(error + dir.getAbsolutePath());
}
}
return dir;
}
/**
* This method creates a temporary directory under
* ${java.io.tmpdir}/tmp_lib_scripts" which can be
* used during testing. This method would be better
* implemeneted using omero.util.TempFileManager
* but that's currently not possible for packaging
* reasons.
*/
static File getTmpDir() throws IOException {
String tmpDirName = System.getProperty("java.io.tmpdir", null);
File tmpDir = new File(tmpDirName);
File libDir = new File(tmpDir, "tmp_lib_scripts");
File dir = File.createTempFile("lib", "scripts", tmpDir);
dir.delete();
dir.mkdirs();
return dir;
}
/**
* Directory which will be used as the root of this repository if no
* directory is passed to a constructor. Equivalent to "lib/scripts" from
* the current directory.
*/
public static String getDefaultScriptDir() {
File current = new File(".");
File lib = new File(current, "lib");
File scripts = new File(lib, "scripts");
return scripts.getAbsolutePath();
}
/**
* Returns the actual root of this repository.
*
* @see #getDefaultScriptDir()
*/
public String getScriptDir() {
return dir.getAbsolutePath();
}
/**
* Uuid of this repository. In the normal case, this will equal
* {@link #SCRIPT_REPO}.
*/
public String getUuid() {
return uuid;
}
/**
* Returns the number of files which match {@link #scriptFilter} in
* {@link #dir}. Uses {@link #iterate()} internally.
*/
public int countOnDisk() {
int size = 0;
Iterator<File> it = iterate();
while (it.hasNext()) {
File f = it.next();
if (f.canRead() && f.isFile() && !f.isHidden()) {
size++;
}
}
return size;
}
public int countInDb() {
return (Integer) ex.executeSql(new Executor.SimpleSqlWork(
this, "countInDb") {
@Transactional(readOnly = true)
public Object doWork(SqlAction sql) {
return countInDb(sql);
}
});
}
public int countInDb(SqlAction sql) {
return sql.repoScriptCount(uuid, mimetypes);
}
@SuppressWarnings("unchecked")
public List<Long> idsInDb() {
return (List<Long>) ex
.executeSql(new Executor.SimpleSqlWork(this,
"idsInDb") {
@Transactional(readOnly = true)
public Object doWork(SqlAction sql) {
return idsInDb(sql);
}
});
}
public List<Long> idsInDb(SqlAction sql) {
try {
return sql.fileIdsInDb(uuid, mimetypes);
} catch (EmptyResultDataAccessException e) {
return Collections.emptyList();
}
}
public boolean isInRepo(final long id) {
return (Boolean) ex.executeSql(new Executor.SimpleSqlWork(
this, "isInRepo", id) {
@Transactional(readOnly = true)
public Object doWork(SqlAction sql) {
return isInRepo(sql, id);
}
});
}
public boolean isInRepo(SqlAction sql, final long id) {
try {
int count = sql.isFileInRepo(uuid, id, mimetypes);
return count > 0;
} catch (EmptyResultDataAccessException e) {
return false;
}
}
public Long findInDb(final String path, final boolean scriptsOnly) {
RepoFile repoFile = new RepoFile(dir, path);
return findInDb(repoFile, scriptsOnly);
}
public Long findInDb(final RepoFile file, final boolean scriptsOnly) {
return (Long) ex.executeSql(new Executor.SimpleSqlWork(
this, "findInDb", file, scriptsOnly) {
@Transactional(readOnly = true)
public Object doWork(SqlAction sql) {
return findInDb(sql, file, scriptsOnly);
}
});
}
/**
* Looks to see if a path is contained in the repository.
*/
public Long findInDb(SqlAction sql, RepoFile repoFile, boolean scriptsOnly) {
return sql.findRepoFile(uuid, repoFile.dirname(), repoFile.basename(),
scriptsOnly ? mimetypes : null);
}
@SuppressWarnings("unchecked")
public Iterator<File> iterate() {
List<String> problems = new ArrayList<String>();
// Can occur if lib/scripts is deleted (#9785)
if (!dir.exists()) {
problems.add("does not exist");
} else {
if (!dir.canRead()) {
problems.add("is not readable");
}
if (!dir.isDirectory()) {
problems.add("is not a directory");
}
}
if (!problems.isEmpty()) {
throw new InternalException(String.format("Cannot list %s " +
"since it %s", dir, StringUtils.join(problems, " and ")));
}
return FileUtils.iterateFiles(dir, scriptFilter, TrueFileFilter.TRUE);
}
/**
* Walks all files in the repository (via {@link #iterate()} and adds them
* if not found in the database.
*
* If modificationCheck is true, then a change in the hash for a file in
* the repository will cause the old file to be removed from the repository
* <pre>(uuid == null)</pre> and a new file created in its place.
*
* @param modificationCheck
* @return
*/
@SuppressWarnings("unchecked")
public List<OriginalFile> loadAll(final boolean modificationCheck) {
final Iterator<File> it = iterate();
final List<OriginalFile> rv = new ArrayList<OriginalFile>();
return (List<OriginalFile>) ex.execute(p, new Executor.SimpleWork(this,
"loadAll", modificationCheck) {
@Transactional(readOnly = false)
public Object doWork(Session session, ServiceFactory sf) {
SqlAction sqlAction = getSqlAction();
File f = null;
RepoFile file = null;
while (it.hasNext()) {
f = it.next();
file = new RepoFile(dir, f);
Long id = findInDb(sqlAction, file, false); // non-scripts count
String hash = null;
OriginalFile ofile = null;
if (id == null) {
ofile = addOrReplace(session, sqlAction, sf, file, null);
} else {
ofile = load(id, session, getSqlAction(), true); // checks for type & repo
if (ofile == null) {
continue; // wrong type or similar
}
if (modificationCheck) {
hash = file.hash();
if (!hash.equals(ofile.getHash())) {
ofile = addOrReplace(session, sqlAction, sf, file, id);
}
}
}
rv.add(ofile);
}
removeMissingFilesFromDb(sqlAction, session, rv);
return rv;
}});
}
/**
*
* @param repoFile
* @param old
* @return
*/
public OriginalFile addOrReplace(final RepoFile repoFile, final Long old) {
return (OriginalFile) ex.execute(p, new Executor.SimpleWork(this,
"addOrReplace", repoFile, old) {
@Transactional(readOnly = false)
public Object doWork(Session session, ServiceFactory sf) {
return addOrReplace(session, getSqlAction(), sf, repoFile, old);
}
});
}
protected OriginalFile addOrReplace(Session session, SqlAction sqlAction, ServiceFactory sf,
final RepoFile repoFile, final Long old) {
if (old != null) {
unregister(old, sqlAction);
log.info("Unregistered " + old);
}
OriginalFile ofile = new OriginalFile();
return update(session, repoFile, sqlAction, sf, ofile);
}
/**
* Given the current files on disk, {@link #unregister(Long, Session)}
* all files which have been removed from disk.
*/
public long removeMissingFilesFromDb(SqlAction sqlAction, Session session, List<OriginalFile> filesOnDisk) {
List<Long> idsInDb = idsInDb(sqlAction);
if (idsInDb.size() != filesOnDisk.size()) {
log.info(String.format(
"Script missing from disk: %s in db, %s on disk!",
idsInDb.size(), filesOnDisk.size()));
}
Set<Long> setInDb = new HashSet<Long>();
Set<Long> setOnDisk = new HashSet<Long>();
setInDb.addAll(idsInDb);
for (OriginalFile f : filesOnDisk) {
setOnDisk.add(f.getId());
}
// Now contains only those which are missing
setInDb.removeAll(setOnDisk);
for (Long l : setInDb) {
unregister(l, sqlAction);
}
return setInDb.size();
}
/**
* Unregisters a given file from the script repository by setting its
* Repo uuid to null.
*/
protected void unregister(final Long old, SqlAction sqlAction) {
sqlAction.setFileRepo(Collections.singleton(old), null);
}
public OriginalFile update(final RepoFile repoFile, final Long id,
Map<String,String> context) {
return (OriginalFile) ex.execute(context, p, new Executor.SimpleWork(this,
"update", repoFile, id) {
@Transactional(readOnly = false)
public Object doWork(Session session, ServiceFactory sf) {
OriginalFile ofile = load(id, session, getSqlAction(), true);
return update(session, repoFile, getSqlAction(), sf, ofile);
}
});
}
private ExperimenterGroup loadUserGroup(Session session) {
return (ExperimenterGroup)
session.get(ExperimenterGroup.class, roles.getUserGroupId());
}
private ChecksumAlgorithm loadChecksum(Session session, String hasher) {
return (ChecksumAlgorithm)
session.createQuery(
"select ca from ChecksumAlgorithm ca where ca.value = :value")
.setParameter("value", hasher).uniqueResult();
}
private OriginalFile update(Session session, final RepoFile repoFile, SqlAction sqlAction,
ServiceFactory sf, OriginalFile ofile) {
ExperimenterGroup group = loadUserGroup(session);
ChecksumAlgorithm hasher = loadChecksum(session, repoFile.hasher().getValue());
ofile.setPath(repoFile.dirname());
ofile.setName(repoFile.basename());
ofile.setHasher(hasher);
ofile.setHash(repoFile.hash());
ofile.setSize(repoFile.length());
ofile.getDetails().setGroup(group);
ofile = sf.getUpdateService().saveAndReturnObject(ofile);
setMimetype(ofile);
sqlAction.setFileRepo(Collections.singleton(ofile.getId()), uuid);
return ofile;
}
public String read(String path) throws IOException {
final RepoFile repo = new RepoFile(dir, path);
return FileUtils.readFileToString(repo.file());
}
public RepoFile write(String path, String text) throws IOException {
RepoFile repo = new RepoFile(dir, path);
return write(repo, text);
}
public RepoFile write(RepoFile repo, String text) throws IOException {
FileUtils.writeStringToFile(repo.file(), text); // truncates itself. ticket:2337
return repo;
}
public OriginalFile load(final long id, final boolean check) {
return (OriginalFile) ex.execute(p, new Executor.SimpleWork(this,
"load", id) {
@Transactional(readOnly = true)
public Object doWork(Session session, ServiceFactory sf) {
return load(id, session, getSqlAction(), check);
}
});
}
public OriginalFile load(final long id, Session s, SqlAction sqlAction, boolean check) {
if (check) {
String repo = sqlAction.scriptRepo(id, mimetypes);
if (!uuid.equals(repo)) {
return null;
}
}
return (OriginalFile) s.get(OriginalFile.class, id);
}
/**
* Checks if
*/
public void modificationCheck() {
loadAll(true);
}
public boolean delete(long id) {
final OriginalFile file = load(id, true);
if (file == null) {
return false;
}
simpleDelete(null, ex, p, id);
FileUtils.deleteQuietly(new File(dir, file.getPath() + file.getName()));
return true;
}
/**
* Unlike {@link #delete(long)} this method simply performs the DB delete
* on the given original file id.
*
* @param context
* Call context which affecets which group the current user is in.
* Can be null to pass no call context.
* @param executor
* @param p
* @param id
* Id of the {@link OriginalFile} to delete.
*/
public void simpleDelete(Map<String, String> context, final Executor executor,
Principal p, final long id) {
Deletion deletion = (Deletion) executor.execute(context, p,
new Executor.SimpleWork(this, "deleteOriginalFile") {
@Transactional(readOnly = false)
public Object doWork(Session session, ServiceFactory sf) {
try {
EventContext ec = ((LocalAdmin) sf.getAdminService())
.getEventContextQuiet();
Deletion d = executor.getContext().getBean(
Deletion.class.getName(), Deletion.class);
int steps = d.start(ec, getSqlAction(), session,
"/OriginalFile", id, null);
if (steps > 0) {
for (int i = 0; i < steps; i++) {
d.execute(i);
}
d.finish();
return d;
}
} catch (ome.conditions.ValidationException ve) {
log.debug("ValidationException on delete", ve);
}
catch (GraphException ge) {
log.debug("GraphException on delete", ge);
}
catch (Throwable e) {
log.warn("Throwable while deleting script " + id, e);
}
return null;
}
});
if (deletion != null) {
deletion.deleteFiles();
deletion.stop();
} else {
throw new ApiUsageException("Cannot delete "
+ id + "\nIs in use by other objects");
}
}
}
| gpl-2.0 |
jbaxenom/laget-framework | src/main/java/com/jbaxenom/laget/domain/core/actions/SQLAction.java | 2811 | package com.jbaxenom.laget.domain.core.actions;
import hu.meza.aao.Action;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author jbaxenom on 12/2/15.
*/
public abstract class SQLAction implements Action {
private final Connection connection;
private final Statement lastStatement;
private final String lastQuery;
private final boolean persistentConnection;
private ResultSet result;
public SQLAction(Connection connection, String sqlQuery) {
this.connection = connection;
this.lastQuery = sqlQuery;
persistentConnection = false;
try {
this.lastStatement = this.connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("ERROR: there was a problem when creating the SQL statement. Please check " +
"the stacktrace above.");
}
}
public SQLAction(Connection connection, String sqlQuery, boolean persistentConnection) {
this.connection = connection;
this.lastQuery = sqlQuery;
this.persistentConnection = persistentConnection;
try {
this.lastStatement = this.connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("ERROR: there was a problem when creating the SQL statement. Please check " +
"the stacktrace above.");
}
}
/**
* Executes the action, which implies sending the SQL query {@code lastQuery} to the DB in the {@code endpointUrl}
* address. The resulting data will be saved in the {@code result} attribute.
*/
@Override
public void execute() {
this.result = sendQuery(this.lastQuery);
if (!persistentConnection) {
closeConnection();
}
}
/**
* @return true if the SQL query returned values, false otherwise
*/
public boolean wasSuccessful() {
try {
return !this.result.wasNull();
} catch (SQLException e) {
return false;
}
}
@Override
public SQLAction copyOf() {
return this;
}
private ResultSet sendQuery(String query) {
try {
return this.lastStatement.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("There was an error in the SQL query (see stacktrace above)");
}
}
private void closeConnection() {
try {
if (this.connection != null) {
this.connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
kruzel/citypark-android | lib/src/osmdroid/osmdroid-read-only/OpenStreetMapViewer/src/org/osmdroid/MapActivity.java | 8543 | // Created by plusminus on 00:23:14 - 03.10.2008
package org.osmdroid;
import org.osmdroid.constants.OpenStreetMapConstants;
import org.osmdroid.samples.SampleLoader;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.CloudmadeUtil;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MyLocationOverlay;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
/**
* Default map view activity.
*
* @author Manuel Stahl
*
*/
public class MapActivity extends Activity implements OpenStreetMapConstants {
// ===========================================================
// Constants
// ===========================================================
private static final int MENU_MY_LOCATION = Menu.FIRST;
private static final int MENU_MAP_MODE = MENU_MY_LOCATION + 1;
private static final int MENU_OFFLINE = MENU_MAP_MODE + 1;
private static final int MENU_SAMPLES = MENU_OFFLINE + 1;
private static final int MENU_ABOUT = MENU_SAMPLES + 1;
private static final int MENU_COMPASS = MENU_ABOUT + 1;
private static final int DIALOG_ABOUT_ID = 1;
// ===========================================================
// Fields
// ===========================================================
private SharedPreferences mPrefs;
private MapView mOsmv;
private MyLocationOverlay mLocationOverlay;
private ResourceProxy mResourceProxy;
// ===========================================================
// Constructors
// ===========================================================
/** Called when the activity is first created. */
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mResourceProxy = new ResourceProxyImpl(getApplicationContext());
mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
final RelativeLayout rl = new RelativeLayout(this);
CloudmadeUtil.retrieveCloudmadeKey(getApplicationContext());
this.mOsmv = new MapView(this, 256);
this.mOsmv.setResourceProxy(mResourceProxy);
this.mLocationOverlay = new MyLocationOverlay(this.getBaseContext(), this.mOsmv,
mResourceProxy);
this.mOsmv.setBuiltInZoomControls(true);
this.mOsmv.setMultiTouchControls(true);
this.mOsmv.getOverlays().add(this.mLocationOverlay);
rl.addView(this.mOsmv, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
this.setContentView(rl);
mOsmv.getController().setZoom(mPrefs.getInt(PREFS_ZOOM_LEVEL, 1));
mOsmv.scrollTo(mPrefs.getInt(PREFS_SCROLL_X, 0), mPrefs.getInt(PREFS_SCROLL_Y, 0));
}
@Override
protected void onPause() {
final SharedPreferences.Editor edit = mPrefs.edit();
edit.putString(PREFS_TILE_SOURCE, mOsmv.getTileProvider().getTileSource().name());
edit.putInt(PREFS_SCROLL_X, mOsmv.getScrollX());
edit.putInt(PREFS_SCROLL_Y, mOsmv.getScrollY());
edit.putInt(PREFS_ZOOM_LEVEL, mOsmv.getZoomLevel());
edit.putBoolean(PREFS_SHOW_LOCATION, mLocationOverlay.isMyLocationEnabled());
edit.putBoolean(PREFS_SHOW_COMPASS, mLocationOverlay.isCompassEnabled());
edit.commit();
this.mLocationOverlay.disableMyLocation();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
final String tileSourceName = mPrefs.getString(PREFS_TILE_SOURCE,
TileSourceFactory.DEFAULT_TILE_SOURCE.name());
try {
final ITileSource tileSource = TileSourceFactory.getTileSource(tileSourceName);
mOsmv.setTileSource(tileSource);
} catch (final IllegalArgumentException ignore) {
}
if (mPrefs.getBoolean(PREFS_SHOW_LOCATION, false)) {
this.mLocationOverlay.enableMyLocation();
}
if (mPrefs.getBoolean(PREFS_SHOW_COMPASS, false)) {
this.mLocationOverlay.enableCompass();
}
}
@Override
public boolean onCreateOptionsMenu(final Menu pMenu) {
pMenu.add(0, MENU_MY_LOCATION, Menu.NONE, R.string.my_location).setIcon(
android.R.drawable.ic_menu_mylocation);
pMenu.add(0, MENU_COMPASS, Menu.NONE, R.string.compass).setIcon(
android.R.drawable.ic_menu_compass);
{
final SubMenu mapMenu = pMenu
.addSubMenu(0, MENU_MAP_MODE, Menu.NONE, R.string.map_mode).setIcon(
android.R.drawable.ic_menu_mapmode);
for (final ITileSource tileSource : TileSourceFactory.getTileSources()) {
mapMenu.add(MENU_MAP_MODE, 1000 + tileSource.ordinal(), Menu.NONE,
tileSource.localizedName(mResourceProxy));
}
mapMenu.setGroupCheckable(MENU_MAP_MODE, true, true);
}
pMenu.add(0, MENU_OFFLINE, Menu.NONE, R.string.offline).setIcon(R.drawable.ic_menu_offline);
pMenu.add(0, MENU_SAMPLES, Menu.NONE, R.string.samples).setIcon(
android.R.drawable.ic_menu_gallery);
pMenu.add(0, MENU_ABOUT, Menu.NONE, R.string.about).setIcon(
android.R.drawable.ic_menu_info_details);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final int ordinal = mOsmv.getTileProvider().getTileSource().ordinal();
menu.findItem(1000 + ordinal).setChecked(true);
return true;
}
@Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case MENU_MY_LOCATION:
if (this.mLocationOverlay.isMyLocationEnabled()) {
this.mLocationOverlay.disableMyLocation();
} else {
this.mLocationOverlay.enableMyLocation();
final Location lastFix = this.mLocationOverlay.getLastFix();
if (lastFix != null) {
this.mOsmv.getController().setCenter(new GeoPoint(lastFix));
}
}
Toast.makeText(
this,
this.mLocationOverlay.isMyLocationEnabled() ? R.string.set_mode_show_me
: R.string.set_mode_hide_me, Toast.LENGTH_LONG).show();
return true;
case MENU_COMPASS:
if (this.mLocationOverlay.isCompassEnabled()) {
this.mLocationOverlay.disableCompass();
} else {
this.mLocationOverlay.enableCompass();
}
return true;
case MENU_MAP_MODE:
this.mOsmv.invalidate();
return true;
case MENU_OFFLINE:
final boolean useDataConnection = !this.mOsmv.useDataConnection();
final int id = useDataConnection ? R.string.set_mode_online : R.string.set_mode_offline;
Toast.makeText(this, id, Toast.LENGTH_LONG).show();
this.mOsmv.setUseDataConnection(useDataConnection);
return true;
case MENU_SAMPLES:
startActivity(new Intent(this, SampleLoader.class));
return true;
case MENU_ABOUT:
showDialog(DIALOG_ABOUT_ID);
return true;
default: // Map mode submenu items
mOsmv.setTileSource(TileSourceFactory.getTileSource(item.getItemId() - 1000));
}
return false;
}
@Override
protected Dialog onCreateDialog(final int id) {
Dialog dialog;
switch (id) {
case DIALOG_ABOUT_ID:
return new AlertDialog.Builder(MapActivity.this).setIcon(R.drawable.icon)
.setTitle(R.string.app_name).setMessage(R.string.about_message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int whichButton) {
}
}).create();
default:
dialog = null;
break;
}
return dialog;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onTrackballEvent(final MotionEvent event) {
return this.mOsmv.onTrackballEvent(event);
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
this.mLocationOverlay.followLocation(false);
}
return super.onTouchEvent(event);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/external/bouncycastle/crypto/CryptoException.java | 2724 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package org.bouncycastle.crypto;
/**
* the foundation class for the hard exceptions thrown by the crypto packages.
*/
public class CryptoException
extends Exception
{
/**
* base constructor.
*/
public CryptoException()
{
}
/**
* create a CryptoException with the given message.
*
* @param message the message to be carried with the exception.
*/
public CryptoException(
String message)
{
super(message);
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest05482.java | 2434 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest05482")
public class BenchmarkTest05482 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] values = request.getParameterValues("foo");
String param;
if (values.length != 0)
param = request.getParameterValues("foo")[0];
else param = null;
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
try {
javax.naming.directory.InitialDirContext idc = org.owasp.benchmark.helpers.Utils.getInitialDirContext();
idc.search("name", bar, new javax.naming.directory.SearchControls());
} catch (javax.naming.NamingException e) {
throw new ServletException(e);
}
}
}
| gpl-2.0 |
juliocamarero/jukebox-portlet | docroot/WEB-INF/src/org/liferay/jukebox/asset/SongAssetRenderer.java | 6440 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.liferay.jukebox.asset;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.portlet.LiferayPortletRequest;
import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
import com.liferay.portal.kernel.trash.TrashRenderer;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.LayoutConstants;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletURLFactoryUtil;
import com.liferay.portlet.asset.model.AssetRendererFactory;
import com.liferay.portlet.asset.model.BaseAssetRenderer;
import com.liferay.portlet.trash.util.TrashUtil;
import java.util.Locale;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import org.liferay.jukebox.model.Song;
import org.liferay.jukebox.portlet.SongsPortlet;
import org.liferay.jukebox.service.permission.SongPermission;
import org.liferay.jukebox.util.PortletKeys;
/**
* @author Julio Camarero
*/
public class SongAssetRenderer
extends BaseAssetRenderer implements TrashRenderer {
public SongAssetRenderer(Song song) {
_song = song;
}
@Override
public String getClassName() {
return Song.class.getName();
}
@Override
public long getClassPK() {
return _song.getSongId();
}
@Override
public long getGroupId() {
return _song.getGroupId();
}
@Override
public String getIconPath(ThemeDisplay themeDisplay) {
return themeDisplay.getPortalURL() +
"/jukebox-portlet/icons/songs.png";
}
public String getPortletId() {
AssetRendererFactory assetRendererFactory = getAssetRendererFactory();
return assetRendererFactory.getPortletId();
}
@Override
public String getSummary(
PortletRequest portletRequest, PortletResponse portletResponse) {
String summary = _song.getName();
return summary;
}
@Override
public String getThumbnailPath(PortletRequest portletRequest)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
String thumbnailSrc = _song.getImageURL(themeDisplay);
if (Validator.isNotNull(thumbnailSrc)) {
return thumbnailSrc;
}
return themeDisplay.getPortalURL() +
"/jukebox-portlet/icons/songs.png";
}
@Override
public String getTitle(Locale locale) {
if (!_song.isInTrash()) {
return _song.getName();
}
return TrashUtil.getOriginalTitle(_song.getName());
}
public String getType() {
return SongAssetRendererFactory.TYPE;
}
@Override
public PortletURL getURLEdit(
LiferayPortletRequest liferayPortletRequest,
LiferayPortletResponse liferayPortletResponse)
throws Exception {
PortletURL portletURL = liferayPortletResponse.createLiferayPortletURL(
getControlPanelPlid(liferayPortletRequest), SongsPortlet.PORTLET_ID,
PortletRequest.RENDER_PHASE);
portletURL.setParameter("jspPage", "/html/songs/edit_song.jsp");
portletURL.setParameter("songId", String.valueOf(_song.getSongId()));
return portletURL;
}
@Override
public PortletURL getURLView(
LiferayPortletResponse liferayPortletResponse,
WindowState windowState)
throws Exception {
PortletURL portletURL = liferayPortletResponse.createLiferayPortletURL(
SongsPortlet.PORTLET_ID, PortletRequest.RENDER_PHASE);
portletURL.setParameter("jspPage", "/html/songs/view_song.jsp");
portletURL.setParameter("songId", String.valueOf(_song.getSongId()));
portletURL.setWindowState(windowState);
return portletURL;
}
@Override
public String getURLViewInContext(
LiferayPortletRequest liferayPortletRequest,
LiferayPortletResponse liferayPortletResponse,
String noSuchEntryRedirect) {
try {
long plid = PortalUtil.getPlidFromPortletId(
_song.getGroupId(), PortletKeys.SONGS);
if (plid == LayoutConstants.DEFAULT_PLID) {
return StringPool.BLANK;
}
PortletURL portletURL = PortletURLFactoryUtil.create(
liferayPortletRequest, PortletKeys.SONGS, plid,
PortletRequest.RENDER_PHASE);
portletURL.setParameter("jspPage", "/html/songs/view_song.jsp");
portletURL.setParameter(
"songId", String.valueOf(_song.getSongId()));
return portletURL.toString();
}
catch (Exception e) {
}
return StringPool.BLANK;
}
@Override
public long getUserId() {
return _song.getUserId();
}
@Override
public String getUserName() {
return _song.getUserName();
}
@Override
public String getUuid() {
return _song.getUuid();
}
public boolean hasDeletePermission(PermissionChecker permissionChecker)
throws PortalException {
return SongPermission.contains(
permissionChecker, _song.getSongId(), ActionKeys.DELETE);
}
@Override
public boolean hasEditPermission(PermissionChecker permissionChecker)
throws PortalException {
return SongPermission.contains(
permissionChecker, _song.getSongId(), ActionKeys.UPDATE);
}
@Override
public boolean hasViewPermission(PermissionChecker permissionChecker)
throws PortalException {
return SongPermission.contains(
permissionChecker, _song.getSongId(), ActionKeys.VIEW);
}
@Override
public boolean isPrintable() {
return true;
}
@Override
public String render(
RenderRequest renderRequest, RenderResponse renderResponse,
String template)
throws Exception {
if (template.equals(TEMPLATE_FULL_CONTENT)) {
renderRequest.setAttribute("jukebox_song", _song);
return "/html/songs/asset/" + template + ".jsp";
}
else {
return null;
}
}
private Song _song;
} | gpl-2.0 |
heftich/iuk_chinit | JEETutMaven/src/ch/chinit/model/UserRolePK.java | 1269 | package ch.chinit.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The primary key class for the user_roles database table.
*
*/
@Embeddable
public class UserRolePK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="user_name")
private String userName;
@Column(name="role_name")
private String roleName;
public UserRolePK() {
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof UserRolePK)) {
return false;
}
UserRolePK castOther = (UserRolePK)other;
return
this.userName.equals(castOther.userName)
&& this.roleName.equals(castOther.roleName);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.userName.hashCode();
hash = hash * prime + this.roleName.hashCode();
return hash;
}
} | gpl-2.0 |
gdevsign/pfrc | AppWebGBIE/src/java/entity/Occupant.java | 15364 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Fabou
*/
@Entity
@Table(name = "occupant")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Occupant.findAll", query = "SELECT o FROM Occupant o"),
@NamedQuery(name = "Occupant.findByIdOccupant", query = "SELECT o FROM Occupant o WHERE o.idOccupant = :idOccupant"),
@NamedQuery(name = "Occupant.findByNomOccupant", query = "SELECT o FROM Occupant o WHERE o.nomOccupant = :nomOccupant"),
@NamedQuery(name = "Occupant.findByPrenomOccupant", query = "SELECT o FROM Occupant o WHERE o.prenomOccupant = :prenomOccupant"),
@NamedQuery(name = "Occupant.findBySexeOccupant", query = "SELECT o FROM Occupant o WHERE o.sexeOccupant = :sexeOccupant"),
@NamedQuery(name = "Occupant.findByCiviliteOccupant", query = "SELECT o FROM Occupant o WHERE o.civiliteOccupant = :civiliteOccupant"),
@NamedQuery(name = "Occupant.findByDateNaissanceOccupant", query = "SELECT o FROM Occupant o WHERE o.dateNaissanceOccupant = :dateNaissanceOccupant"),
@NamedQuery(name = "Occupant.findByLieuNaissanceOccupant", query = "SELECT o FROM Occupant o WHERE o.lieuNaissanceOccupant = :lieuNaissanceOccupant"),
@NamedQuery(name = "Occupant.findByTitreOccupation", query = "SELECT o FROM Occupant o WHERE o.titreOccupation = :titreOccupation"),
@NamedQuery(name = "Occupant.findByTypeOccupation", query = "SELECT o FROM Occupant o WHERE o.typeOccupation = :typeOccupation"),
@NamedQuery(name = "Occupant.findByNumeroPieceIdentite", query = "SELECT o FROM Occupant o WHERE o.numeroPieceIdentite = :numeroPieceIdentite"),
@NamedQuery(name = "Occupant.findByValiditeNumeroPieceIdentite", query = "SELECT o FROM Occupant o WHERE o.validiteNumeroPieceIdentite = :validiteNumeroPieceIdentite"),
@NamedQuery(name = "Occupant.findByNumeroPassport", query = "SELECT o FROM Occupant o WHERE o.numeroPassport = :numeroPassport"),
@NamedQuery(name = "Occupant.findByLieuEmissionPassport", query = "SELECT o FROM Occupant o WHERE o.lieuEmissionPassport = :lieuEmissionPassport"),
@NamedQuery(name = "Occupant.findByValiditePassport", query = "SELECT o FROM Occupant o WHERE o.validitePassport = :validitePassport"),
@NamedQuery(name = "Occupant.findByTypeOccupant", query = "SELECT o FROM Occupant o WHERE o.typeOccupant = :typeOccupant"),
@NamedQuery(name = "Occupant.findByPermisDeConduire", query = "SELECT o FROM Occupant o WHERE o.permisDeConduire = :permisDeConduire"),
@NamedQuery(name = "Occupant.findByAutrePieceKidentite", query = "SELECT o FROM Occupant o WHERE o.autrePieceKidentite = :autrePieceKidentite"),
@NamedQuery(name = "Occupant.findByResidence", query = "SELECT o FROM Occupant o WHERE o.residence = :residence"),
@NamedQuery(name = "Occupant.findByActeEngagement", query = "SELECT o FROM Occupant o WHERE o.acteEngagement = :acteEngagement"),
@NamedQuery(name = "Occupant.findByNumeroMatriculeFxPublique", query = "SELECT o FROM Occupant o WHERE o.numeroMatriculeFxPublique = :numeroMatriculeFxPublique"),
@NamedQuery(name = "Occupant.findByHierarchie", query = "SELECT o FROM Occupant o WHERE o.hierarchie = :hierarchie"),
@NamedQuery(name = "Occupant.findByGrade", query = "SELECT o FROM Occupant o WHERE o.grade = :grade"),
@NamedQuery(name = "Occupant.findByEchellon", query = "SELECT o FROM Occupant o WHERE o.echellon = :echellon"),
@NamedQuery(name = "Occupant.findByService", query = "SELECT o FROM Occupant o WHERE o.service = :service"),
@NamedQuery(name = "Occupant.findByLieuDeTravail", query = "SELECT o FROM Occupant o WHERE o.lieuDeTravail = :lieuDeTravail"),
@NamedQuery(name = "Occupant.findByTauxSalarial", query = "SELECT o FROM Occupant o WHERE o.tauxSalarial = :tauxSalarial"),
@NamedQuery(name = "Occupant.findByEmailOccupant", query = "SELECT o FROM Occupant o WHERE o.emailOccupant = :emailOccupant"),
@NamedQuery(name = "Occupant.findByPhoneJob", query = "SELECT o FROM Occupant o WHERE o.phoneJob = :phoneJob"),
@NamedQuery(name = "Occupant.findByPhoneHouse", query = "SELECT o FROM Occupant o WHERE o.phoneHouse = :phoneHouse"),
@NamedQuery(name = "Occupant.findByProfession", query = "SELECT o FROM Occupant o WHERE o.profession = :profession"),
@NamedQuery(name = "Occupant.findByMemo", query = "SELECT o FROM Occupant o WHERE o.memo = :memo")})
public class Occupant implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_occupant")
private Integer idOccupant;
@Size(max = 60)
@Column(name = "nom_occupant")
private String nomOccupant;
@Size(max = 60)
@Column(name = "prenom_occupant")
private String prenomOccupant;
@Size(max = 30)
@Column(name = "sexe_occupant")
private String sexeOccupant;
@Size(max = 60)
@Column(name = "civilite_occupant")
private String civiliteOccupant;
@Column(name = "date_naissance_occupant")
@Temporal(TemporalType.DATE)
private Date dateNaissanceOccupant;
@Size(max = 60)
@Column(name = "lieu_naissance_occupant")
private String lieuNaissanceOccupant;
@Size(max = 60)
@Column(name = "titre_occupation")
private String titreOccupation;
@Size(max = 60)
@Column(name = "type_occupation")
private String typeOccupation;
@Size(max = 60)
@Column(name = "numero_piece_identite")
private String numeroPieceIdentite;
@Size(max = 60)
@Column(name = "validite_numero_piece_identite")
private String validiteNumeroPieceIdentite;
@Size(max = 60)
@Column(name = "numero_passport")
private String numeroPassport;
@Size(max = 60)
@Column(name = "lieu_emission_passport")
private String lieuEmissionPassport;
@Column(name = "validite_passport")
@Temporal(TemporalType.DATE)
private Date validitePassport;
@Size(max = 60)
@Column(name = "type_occupant")
private String typeOccupant;
@Size(max = 60)
@Column(name = "permis_de_conduire")
private String permisDeConduire;
@Size(max = 60)
@Column(name = "autre_piece_kidentite")
private String autrePieceKidentite;
@Size(max = 60)
@Column(name = "residence")
private String residence;
@Size(max = 60)
@Column(name = "acte_engagement")
private String acteEngagement;
@Size(max = 60)
@Column(name = "numero_matricule_fx_publique")
private String numeroMatriculeFxPublique;
@Size(max = 60)
@Column(name = "hierarchie")
private String hierarchie;
@Size(max = 60)
@Column(name = "grade")
private String grade;
@Size(max = 60)
@Column(name = "echellon")
private String echellon;
@Size(max = 60)
@Column(name = "service")
private String service;
@Size(max = 60)
@Column(name = "lieu_de_travail")
private String lieuDeTravail;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "taux_salarial")
private Double tauxSalarial;
@Size(max = 100)
@Column(name = "email_occupant")
private String emailOccupant;
@Size(max = 60)
@Column(name = "phone_job")
private String phoneJob;
@Size(max = 60)
@Column(name = "phone_house")
private String phoneHouse;
@Size(max = 60)
@Column(name = "profession")
private String profession;
@Size(max = 60)
@Column(name = "memo")
private String memo;
@JoinColumn(name = "id_batiment_batiment", referencedColumnName = "id_batiment")
@ManyToOne
private Batiment idBatimentBatiment;
public Occupant() {
}
public Occupant(Integer idOccupant) {
this.idOccupant = idOccupant;
}
public Integer getIdOccupant() {
return idOccupant;
}
public void setIdOccupant(Integer idOccupant) {
this.idOccupant = idOccupant;
}
public String getNomOccupant() {
return nomOccupant;
}
public void setNomOccupant(String nomOccupant) {
this.nomOccupant = nomOccupant;
}
public String getPrenomOccupant() {
return prenomOccupant;
}
public void setPrenomOccupant(String prenomOccupant) {
this.prenomOccupant = prenomOccupant;
}
public String getSexeOccupant() {
return sexeOccupant;
}
public void setSexeOccupant(String sexeOccupant) {
this.sexeOccupant = sexeOccupant;
}
public String getCiviliteOccupant() {
return civiliteOccupant;
}
public void setCiviliteOccupant(String civiliteOccupant) {
this.civiliteOccupant = civiliteOccupant;
}
public Date getDateNaissanceOccupant() {
return dateNaissanceOccupant;
}
public void setDateNaissanceOccupant(Date dateNaissanceOccupant) {
this.dateNaissanceOccupant = dateNaissanceOccupant;
}
public String getLieuNaissanceOccupant() {
return lieuNaissanceOccupant;
}
public void setLieuNaissanceOccupant(String lieuNaissanceOccupant) {
this.lieuNaissanceOccupant = lieuNaissanceOccupant;
}
public String getTitreOccupation() {
return titreOccupation;
}
public void setTitreOccupation(String titreOccupation) {
this.titreOccupation = titreOccupation;
}
public String getTypeOccupation() {
return typeOccupation;
}
public void setTypeOccupation(String typeOccupation) {
this.typeOccupation = typeOccupation;
}
public String getNumeroPieceIdentite() {
return numeroPieceIdentite;
}
public void setNumeroPieceIdentite(String numeroPieceIdentite) {
this.numeroPieceIdentite = numeroPieceIdentite;
}
public String getValiditeNumeroPieceIdentite() {
return validiteNumeroPieceIdentite;
}
public void setValiditeNumeroPieceIdentite(String validiteNumeroPieceIdentite) {
this.validiteNumeroPieceIdentite = validiteNumeroPieceIdentite;
}
public String getNumeroPassport() {
return numeroPassport;
}
public void setNumeroPassport(String numeroPassport) {
this.numeroPassport = numeroPassport;
}
public String getLieuEmissionPassport() {
return lieuEmissionPassport;
}
public void setLieuEmissionPassport(String lieuEmissionPassport) {
this.lieuEmissionPassport = lieuEmissionPassport;
}
public Date getValiditePassport() {
return validitePassport;
}
public void setValiditePassport(Date validitePassport) {
this.validitePassport = validitePassport;
}
public String getTypeOccupant() {
return typeOccupant;
}
public void setTypeOccupant(String typeOccupant) {
this.typeOccupant = typeOccupant;
}
public String getPermisDeConduire() {
return permisDeConduire;
}
public void setPermisDeConduire(String permisDeConduire) {
this.permisDeConduire = permisDeConduire;
}
public String getAutrePieceKidentite() {
return autrePieceKidentite;
}
public void setAutrePieceKidentite(String autrePieceKidentite) {
this.autrePieceKidentite = autrePieceKidentite;
}
public String getResidence() {
return residence;
}
public void setResidence(String residence) {
this.residence = residence;
}
public String getActeEngagement() {
return acteEngagement;
}
public void setActeEngagement(String acteEngagement) {
this.acteEngagement = acteEngagement;
}
public String getNumeroMatriculeFxPublique() {
return numeroMatriculeFxPublique;
}
public void setNumeroMatriculeFxPublique(String numeroMatriculeFxPublique) {
this.numeroMatriculeFxPublique = numeroMatriculeFxPublique;
}
public String getHierarchie() {
return hierarchie;
}
public void setHierarchie(String hierarchie) {
this.hierarchie = hierarchie;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getEchellon() {
return echellon;
}
public void setEchellon(String echellon) {
this.echellon = echellon;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getLieuDeTravail() {
return lieuDeTravail;
}
public void setLieuDeTravail(String lieuDeTravail) {
this.lieuDeTravail = lieuDeTravail;
}
public Double getTauxSalarial() {
return tauxSalarial;
}
public void setTauxSalarial(Double tauxSalarial) {
this.tauxSalarial = tauxSalarial;
}
public String getEmailOccupant() {
return emailOccupant;
}
public void setEmailOccupant(String emailOccupant) {
this.emailOccupant = emailOccupant;
}
public String getPhoneJob() {
return phoneJob;
}
public void setPhoneJob(String phoneJob) {
this.phoneJob = phoneJob;
}
public String getPhoneHouse() {
return phoneHouse;
}
public void setPhoneHouse(String phoneHouse) {
this.phoneHouse = phoneHouse;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Batiment getIdBatimentBatiment() {
return idBatimentBatiment;
}
public void setIdBatimentBatiment(Batiment idBatimentBatiment) {
this.idBatimentBatiment = idBatimentBatiment;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idOccupant != null ? idOccupant.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Occupant)) {
return false;
}
Occupant other = (Occupant) object;
if ((this.idOccupant == null && other.idOccupant != null) || (this.idOccupant != null && !this.idOccupant.equals(other.idOccupant))) {
return false;
}
return true;
}
@Override
public String toString() {
return idOccupant + " "+nomOccupant+" "+prenomOccupant;
}
}
| gpl-2.0 |
eshen1991/kivasim | alphabetsoup/userinterface/WordStationRender.java | 2670 | /**
*
*/
package alphabetsoup.userinterface;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.Disk;
import alphabetsoup.base.WordStationBase;
import alphabetsoup.framework.Word;
/**Draws the WordStation
* @author Chris Hazard
*/
public class WordStationRender implements Renderable {
WordStationBase wordStation = null;
public WordStationRender(WordStationBase wordStation) {
this.wordStation = wordStation;
}
static private Disk disk = new Disk();
/* (non-Javadoc)
* @see alphabetsoup.framework.Renderable#render()
*/
public void render() {
GL11.glPushMatrix();
GL11.glTranslatef(wordStation.getX(), wordStation.getY(), 0.0f);
GL11.glColor4ub((byte)0x66, (byte)0xFF, (byte)0x33, (byte)0xC0);
disk.draw(0.0f, wordStation.getRadius(), 14, 1);
//draw a point in the center
GL11.glColor4ub((byte)0x66, (byte)0xFF, (byte)0x33, (byte)0xFF);
GL11.glBegin(GL11.GL_POINTS);
GL11.glVertex2f(0, 0);
GL11.glEnd();
GL11.glPopMatrix();
}
/* (non-Javadoc)
* @see alphabetsoup.framework.Renderable#renderDetails()
*/
public void renderDetails() {
float x = RenderWindow.getWindowWidth() - RenderWindow.getWindowRightPanelWidth(),
y = RenderWindow.getWindowHeight() / 3 + RenderWindow.getFontRenderHeight() + RenderWindow.getFontRenderHeight();
GL11.glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
RenderWindow.renderString(x, y, "Word Station");
y += RenderWindow.getFontRenderHeight();
for(Word w : wordStation.assignedWords) {
RenderWindow.renderTiledWord(x, y, w);
y += RenderWindow.getFontRenderHeight();
}
//render additional info
x = 10.0f;
y = 100.0f;
GL11.glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
for(String s : wordStation.getAdditionalInfo()) {
RenderWindow.renderString(x, y, s);
y += RenderWindow.getFontRenderHeight();
}
}
/* (non-Javadoc)
* @see alphabetsoup.framework.Renderable#renderOverlayDetails(float, float)
*/
public void renderOverlayDetails() {
GL11.glPushMatrix();
GL11.glTranslatef(wordStation.getX(), wordStation.getY(), 0.0f);
GL11.glColor4ub((byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xA0);
disk.draw(0.0f, wordStation.getRadius(), 14, 1);
//draw a point in the center
GL11.glColor4ub((byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF);
GL11.glBegin(GL11.GL_POINTS);
GL11.glVertex2f(0, 0);
GL11.glEnd();
GL11.glPopMatrix();
}
/* (non-Javadoc)
* @see alphabetsoup.framework.Renderable#isMouseOver(float, float)
*/
public boolean isMouseOver(float mouse_x, float mouse_y) {
return wordStation.IsCollision(mouse_x, mouse_y, 0);
}
}
| gpl-2.0 |
nologic/nabs | client/trunk/shared/libraries/jcommon-1.0.10/source/org/jfree/base/modules/AbstractModule.java | 20754 | /* ========================================================================
* JCommon : a free general purpose class library for the Java(tm) platform
* ========================================================================
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -------------------
* AbstractModule.java
* -------------------
* (C)opyright 2003, 2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: AbstractModule.java,v 1.3 2005/10/18 13:14:50 mungady Exp $
*
* Changes
* -------
* 05-Jul-2003 : Initial version
* 07-Jun-2004 : Added JCommon header (DG);
*
*/
package org.jfree.base.modules;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.jfree.util.ObjectUtilities;
/**
* The abstract module provides a default implementation of the module interface.
* <p>
* The module can be specified in an external property file. The file name of this
* specification defaults to "module.properties". This file is no real property file,
* it follows a more complex rule set.
* <p>
* Lines starting with '#' are considered comments.
* Section headers start at the beginning of the line, section properties
* are indented with at least one whitespace.
* <p>
* The first section is always the module info and contains the basic module
* properties like name, version and a short description.
* <p>
* <pre>
* module-info:
* name: xls-export-gui
* producer: The JFreeReport project - www.jfree.org/jfreereport
* description: A dialog component for the Excel table export.
* version.major: 0
* version.minor: 84
* version.patchlevel: 0
* </pre>
* The properties name, producer and description are simple strings. They may
* span multiple lines, but may not contain a colon (':').
* The version properties are integer values.
* <p>
* This section may be followed by one or more "depends" sections. These
* sections describe the base modules that are required to be active to make this
* module work. The package manager will enforce this policy and will deactivate this
* module if one of the base modules is missing.
* <p>
* <pre>
* depends:
* module: org.jfree.report.modules.output.table.xls.XLSTableModule
* version.major: 0
* version.minor: 84
* </pre>
* <p>
* The property module references to the module implementation of the module package.
*
* @author Thomas Morgner
*/
public abstract class AbstractModule extends DefaultModuleInfo implements Module
{
/**
* The reader helper provides a pushback interface for the reader to read and
* buffer complete lines.
* @author Thomas Morgner
*/
private static class ReaderHelper
{
/** The line buffer containing the last line read. */
private String buffer;
/** The reader from which to read the text. */
private final BufferedReader reader;
/**
* Creates a new reader helper for the given buffered reader.
*
* @param reader the buffered reader that is the source of the text.
*/
public ReaderHelper(final BufferedReader reader)
{
this.reader = reader;
}
/**
* Checks, whether the reader contains a next line. Returns false if the end
* of the stream has been reached.
*
* @return true, if there is a next line to read, false otherwise.
* @throws IOException if an error occures.
*/
public boolean hasNext() throws IOException
{
if (this.buffer == null)
{
this.buffer = readLine();
}
return this.buffer != null;
}
/**
* Returns the next line.
*
* @return the next line.
*/
public String next()
{
final String line = this.buffer;
this.buffer = null;
return line;
}
/**
* Pushes the given line back into the buffer. Only one line can be contained in
* the buffer at one time.
*
* @param line the line that should be pushed back into the buffer.
*/
public void pushBack(final String line)
{
this.buffer = line;
}
/**
* Reads the next line skipping all comment lines.
*
* @return the next line, or null if no line can be read.
* @throws IOException if an IO error occures.
*/
protected String readLine() throws IOException
{
String line = this.reader.readLine();
while (line != null && (line.length() == 0 || line.startsWith("#")))
{
// empty line or comment is ignored
line = this.reader.readLine();
}
return line;
}
/**
* Closes the reader.
*
* @throws IOException if an IOError occurs.
*/
public void close() throws IOException
{
this.reader.close();
}
}
/** The list of required modules. */
private ModuleInfo[] requiredModules;
/** The list of optional modules. */
private ModuleInfo[] optionalModules;
/** The name of the module. */
private String name;
/** A short description of the module. */
private String description;
/** The name of the module producer. */
private String producer;
/** The modules subsystem. */
private String subsystem;
/**
* Default Constructor.
*/
public AbstractModule()
{
setModuleClass(this.getClass().getName());
}
/**
* Loads the default module description from the file "module.properties". This file
* must be in the same package as the implementing class.
*
* @throws ModuleInitializeException if an error occurs.
*/
protected void loadModuleInfo() throws ModuleInitializeException
{
final InputStream in = ObjectUtilities.getResourceRelativeAsStream
("module.properties", getClass());
if (in == null)
{
throw new ModuleInitializeException
("File 'module.properties' not found in module package.");
}
loadModuleInfo(in);
}
/**
* Loads the module descriptiong from the given input stream. The module description
* must conform to the rules define in the class description. The file must be encoded
* with "ISO-8859-1" (like property files).
*
* @param in the input stream from where to read the file
* @throws ModuleInitializeException if an error occurs.
*/
protected void loadModuleInfo(final InputStream in) throws ModuleInitializeException
{
try
{
if (in == null)
{
throw new NullPointerException
("Given InputStream is null.");
}
final ReaderHelper rh = new ReaderHelper(new BufferedReader
(new InputStreamReader(in, "ISO-8859-1")));
final ArrayList optionalModules = new ArrayList();
final ArrayList dependendModules = new ArrayList();
while (rh.hasNext())
{
final String lastLineRead = rh.next();
if (lastLineRead.startsWith("module-info:"))
{
readModuleInfo(rh);
}
else if (lastLineRead.startsWith("depends:"))
{
dependendModules.add(readExternalModule(rh));
}
else if (lastLineRead.startsWith("optional:"))
{
optionalModules.add(readExternalModule(rh));
}
else
{
// we dont understand the current line, so we skip it ...
// should we throw a parse exception instead?
}
}
rh.close();
this.optionalModules = (ModuleInfo[])
optionalModules.toArray(new ModuleInfo[optionalModules.size()]);
this.requiredModules = (ModuleInfo[])
dependendModules.toArray(new ModuleInfo[dependendModules.size()]);
}
catch (IOException ioe)
{
throw new ModuleInitializeException("Failed to load properties", ioe);
}
}
/**
* Reads a multiline value the stream. This will read the stream until
* a new key is found or the end of the file is reached.
*
* @param reader the reader from where to read.
* @param firstLine the first line (which was read elsewhere).
* @return the complete value, never null
* @throws IOException if an IO error occurs.
*/
private String readValue(final ReaderHelper reader, String firstLine) throws IOException
{
final StringBuffer b = new StringBuffer(firstLine.trim());
boolean newLine = true;
while (isNextLineValueLine(reader))
{
firstLine = reader.next();
final String trimedLine = firstLine.trim();
if (trimedLine.length() == 0 && (newLine == false))
{
b.append ("\n");
newLine = true;
}
else
{
if (newLine == false)
{
b.append(" ");
}
b.append(parseValue(trimedLine));
newLine = false;
}
}
return b.toString();
}
/**
* Checks, whether the next line in the reader is a value line.
*
* @param reader from where to read the lines.
* @return true, if the next line is a value line, false otherwise.
* @throws IOException if an IO error occurs.
*/
private boolean isNextLineValueLine (final ReaderHelper reader) throws IOException
{
if (reader.hasNext() == false)
{
return false;
}
final String firstLine = reader.next();
if (firstLine == null)
{
return false;
}
if (parseKey(firstLine) != null)
{
reader.pushBack(firstLine);
return false;
}
reader.pushBack(firstLine);
return true;
}
/**
* Reads the module definition header. This header contains information about
* the module itself.
*
* @param reader the reader from where to read the content.
* @throws IOException if an error occures
*/
private void readModuleInfo(final ReaderHelper reader) throws IOException
{
while (reader.hasNext())
{
final String lastLineRead = reader.next();
if (Character.isWhitespace(lastLineRead.charAt(0)) == false)
{
// break if the current character is no whitespace ...
reader.pushBack(lastLineRead);
return;
}
final String line = lastLineRead.trim();
final String key = parseKey(line);
if (key != null)
{
// parse error: Non data line does not contain a colon
final String b = readValue(reader, parseValue(line.trim()));
if (key.equals("name"))
{
setName(b);
}
else if (key.equals("producer"))
{
setProducer(b);
}
else if (key.equals("description"))
{
setDescription(b);
}
else if (key.equals("subsystem"))
{
setSubSystem(b);
}
else if (key.equals("version.major"))
{
setMajorVersion(b);
}
else if (key.equals("version.minor"))
{
setMinorVersion(b);
}
else if (key.equals("version.patchlevel"))
{
setPatchLevel(b);
}
}
}
}
/**
* Parses an string to find the key section of the line. This section ends with
* an colon.
*
* @param line the line which to parse
* @return the key or null if no key is found.
*/
private String parseKey(final String line)
{
final int idx = line.indexOf(':');
if (idx == -1)
{
return null;
}
return line.substring(0, idx);
}
/**
* Parses the value section of the given line.
*
* @param line the line that should be parsed
* @return the value, never null
*/
private String parseValue(final String line)
{
final int idx = line.indexOf(':');
if (idx == -1)
{
return line;
}
if ((idx + 1) == line.length())
{
return "";
}
return line.substring(idx + 1);
}
/**
* Reads an external module description. This describes either an optional or
* a required module.
*
* @param reader the reader from where to read the module
* @return the read module, never null
* @throws IOException if an error occures.
*/
private DefaultModuleInfo readExternalModule(final ReaderHelper reader)
throws IOException
{
final DefaultModuleInfo mi = new DefaultModuleInfo();
while (reader.hasNext())
{
final String lastLineRead = reader.next();
if (Character.isWhitespace(lastLineRead.charAt(0)) == false)
{
// break if the current character is no whitespace ...
reader.pushBack(lastLineRead);
return mi;
}
final String line = lastLineRead.trim();
final String key = parseKey(line);
if (key != null)
{
final String b = readValue(reader, parseValue(line));
if (key.equals("module"))
{
mi.setModuleClass(b);
}
else if (key.equals("version.major"))
{
mi.setMajorVersion(b);
}
else if (key.equals("version.minor"))
{
mi.setMinorVersion(b);
}
else if (key.equals("version.patchlevel"))
{
mi.setPatchLevel(b);
}
}
}
return mi;
}
/**
* Returns the name of this module.
*
* @see Module#getName()
*
* @return the module name
*/
public String getName()
{
return this.name;
}
/**
* Defines the name of the module.
*
* @param name the module name.
*/
protected void setName(final String name)
{
this.name = name;
}
/**
* Returns the module description.
* @see Module#getDescription()
*
* @return the description of the module.
*/
public String getDescription()
{
return this.description;
}
/**
* Defines the description of the module.
*
* @param description the module's desciption.
*/
protected void setDescription(final String description)
{
this.description = description;
}
/**
* Returns the producer of the module.
*
* @see Module#getProducer()
*
* @return the producer.
*/
public String getProducer()
{
return this.producer;
}
/**
* Defines the producer of the module.
*
* @param producer the producer.
*/
protected void setProducer(final String producer)
{
this.producer = producer;
}
/**
* Returns a copy of the required modules array. This array contains all
* description of the modules that need to be present to make this module work.
* @see Module#getRequiredModules()
*
* @return an array of all required modules.
*/
public ModuleInfo[] getRequiredModules()
{
final ModuleInfo[] retval = new ModuleInfo[this.requiredModules.length];
System.arraycopy(this.requiredModules, 0, retval, 0, this.requiredModules.length);
return retval;
}
/**
* Returns a copy of the required modules array. This array contains all
* description of the optional modules that may improve the modules functonality.
* @see Module#getRequiredModules()
*
* @return an array of all required modules.
*/
public ModuleInfo[] getOptionalModules()
{
final ModuleInfo[] retval = new ModuleInfo[this.optionalModules.length];
System.arraycopy(this.optionalModules, 0, retval, 0, this.optionalModules.length);
return retval;
}
/**
* Defines the required module descriptions for this module.
*
* @param requiredModules the required modules.
*/
protected void setRequiredModules(final ModuleInfo[] requiredModules)
{
this.requiredModules = new ModuleInfo[requiredModules.length];
System.arraycopy(requiredModules, 0, this.requiredModules, 0, requiredModules.length);
}
/**
* Defines the optional module descriptions for this module.
*
* @param optionalModules the optional modules.
*/
public void setOptionalModules(final ModuleInfo[] optionalModules)
{
this.optionalModules = new ModuleInfo[optionalModules.length];
System.arraycopy(optionalModules, 0, this.optionalModules, 0, optionalModules.length);
}
/**
* Returns a string representation of this module.
* @see java.lang.Object#toString()
*
* @return the string representation of this module for debugging purposes.
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
buffer.append("Module : ");
buffer.append(getName());
buffer.append("\n");
buffer.append("ModuleClass : ");
buffer.append(getModuleClass());
buffer.append("\n");
buffer.append("Version: ");
buffer.append(getMajorVersion());
buffer.append(".");
buffer.append(getMinorVersion());
buffer.append(".");
buffer.append(getPatchLevel());
buffer.append("\n");
buffer.append("Producer: ");
buffer.append(getProducer());
buffer.append("\n");
buffer.append("Description: ");
buffer.append(getDescription());
buffer.append("\n");
return buffer.toString();
}
/**
* Tries to load a class to indirectly check for the existence
* of a certain library.
*
* @param name the name of the library class.
* @return true, if the class could be loaded, false otherwise.
*/
protected static boolean isClassLoadable(final String name)
{
try
{
Thread.currentThread().getContextClassLoader().loadClass(name);
return true;
}
catch (Exception e)
{
return false;
}
}
/**
* Configures the module by loading the configuration properties and
* adding them to the package configuration.
*
* @param subSystem the subsystem.
*/
public void configure(final SubSystem subSystem)
{
final InputStream in = ObjectUtilities.getResourceRelativeAsStream
("configuration.properties", getClass());
if (in == null)
{
return;
}
subSystem.getPackageManager().getPackageConfiguration().load(in);
}
/**
* Tries to load an module initializer and uses this initializer to initialize
* the module.
*
* @param classname the class name of the initializer.
* @throws ModuleInitializeException if an error occures
*/
protected void performExternalInitialize(final String classname)
throws ModuleInitializeException
{
try
{
final Class c = Thread.currentThread().getContextClassLoader().loadClass(classname);
final ModuleInitializer mi = (ModuleInitializer) c.newInstance();
mi.performInit();
}
catch (ModuleInitializeException mie)
{
throw mie;
}
catch (Exception e)
{
throw new ModuleInitializeException("Failed to load specified initializer class.", e);
}
}
/**
* Returns the modules subsystem. If this module is not part of an subsystem
* then return the modules name, but never null.
*
* @return the name of the subsystem.
*/
public String getSubSystem()
{
if (this.subsystem == null)
{
return getName();
}
return this.subsystem;
}
/**
* Defines the subsystem name for this module.
*
* @param name the new name of the subsystem.
*/
protected void setSubSystem (final String name)
{
this.subsystem = name;
}
}
| gpl-2.0 |
ta-apps/GpsPrune | src/tim/prune/undo/UndoEditPoint.java | 2001 | package tim.prune.undo;
import tim.prune.App;
import tim.prune.I18nManager;
import tim.prune.PruneApp;
import tim.prune.data.DataPoint;
import tim.prune.data.TrackInfo;
import tim.prune.function.edit.FieldEditList;
/**
* Operation to undo the edit of a single point
*/
public class UndoEditPoint implements UndoOperation
{
private DataPoint _originalPoint = null;
private FieldEditList _undoFieldList = null;
private FieldEditList _editList = null;
/**
* Constructor
* @param inPoint data point
* @param inUndoFieldList FieldEditList for undo operation
*/
public UndoEditPoint(DataPoint inPoint, FieldEditList inUndoFieldList, FieldEditList inEditList)
{
_originalPoint = inPoint;
_undoFieldList = inUndoFieldList;
_editList = inEditList;
}
/**
* @return description of operation including point name if any
*/
public String getDescription()
{
String desc = I18nManager.getText("undo.editpoint");
String newName = _undoFieldList.getEdit(0).getValue();
String pointName = _originalPoint.getWaypointName();
if (newName != null && !newName.equals(""))
desc = desc + " " + newName;
else if (pointName != null && !pointName.equals(""))
desc = desc + " " + pointName;
return desc;
}
/**
* Perform the undo operation on the given Track
* @param inTrackInfo TrackInfo object on which to perform the operation
*/
public void performUndo(TrackInfo inTrackInfo, FieldEditList editList) throws UndoException
{
// Restore contents of point into track
if (!inTrackInfo.getTrack().editPoint(_originalPoint, editList, true))
{
// throw exception if failed
throw new UndoException(getDescription());
}
}
public void performUndo( App app ) throws UndoException {
performUndo(((PruneApp) app).getTrackInfo(), _undoFieldList);
}
@Override
public void performRedo(App app) throws UndoException {
performUndo(((PruneApp) app).getTrackInfo(), _editList);
}
} | gpl-2.0 |
sungsoo/esper | esper/src/test/java/com/espertech/esper/view/window/TestExternallyTimedWindowView.java | 6358 | /*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.view.window;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.scopetest.EPAssertionUtil;
import com.espertech.esper.epl.expression.ExprNode;
import com.espertech.esper.support.bean.SupportBean;
import com.espertech.esper.support.epl.SupportExprNodeFactory;
import com.espertech.esper.support.event.SupportEventBeanFactory;
import com.espertech.esper.support.view.SupportBeanClassView;
import com.espertech.esper.support.view.SupportStatementContextFactory;
import com.espertech.esper.support.view.SupportStreamImpl;
import com.espertech.esper.support.view.SupportViewDataChecker;
import junit.framework.TestCase;
public class TestExternallyTimedWindowView extends TestCase
{
private ExternallyTimedWindowView myView;
private SupportBeanClassView childView;
public void setUp() throws Exception
{
// Set up timed window view and a test child view, set the time window size to 1 second
ExprNode node = SupportExprNodeFactory.makeIdentNodeBean("longPrimitive");
myView = new ExternallyTimedWindowView(null, node, node.getExprEvaluator(), 1000, null, SupportStatementContextFactory.makeAgentInstanceViewFactoryContext());
childView = new SupportBeanClassView(SupportBean.class);
myView.addView(childView);
}
public void testIncorrectUse() throws Exception
{
try
{
myView = new ExternallyTimedWindowView(null, SupportExprNodeFactory.makeIdentNodeBean("theString"), null, 0, null, SupportStatementContextFactory.makeAgentInstanceViewFactoryContext());
}
catch (IllegalArgumentException ex)
{
// Expected exception
}
}
public void testViewPush()
{
// Set up a feed for the view under test - it will have a depth of 3 trades
SupportStreamImpl stream = new SupportStreamImpl(SupportBean.class, 3);
stream.addView(myView);
EventBean[] a = makeBeans("a", 10000, 1);
stream.insert(a);
SupportViewDataChecker.checkOldData(childView, null);
SupportViewDataChecker.checkNewData(childView, new EventBean[] { a[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{a[0]}, myView.iterator());
EventBean[] b = makeBeans("b", 10500, 2);
stream.insert(b);
SupportViewDataChecker.checkOldData(childView, null);
SupportViewDataChecker.checkNewData(childView, new EventBean[] { b[0], b[1] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{a[0], b[0], b[1]}, myView.iterator());
EventBean[] c = makeBeans("c", 10900, 1);
stream.insert(c);
SupportViewDataChecker.checkOldData(childView, null);
SupportViewDataChecker.checkNewData(childView, new EventBean[] { c[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{a[0], b[0], b[1], c[0]}, myView.iterator());
EventBean[] d = makeBeans("d", 10999, 1);
stream.insert(d);
SupportViewDataChecker.checkOldData(childView, null);
SupportViewDataChecker.checkNewData(childView, new EventBean[] { d[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{a[0], b[0], b[1], c[0], d[0]}, myView.iterator());
EventBean[] e = makeBeans("e", 11000, 2);
stream.insert(e);
SupportViewDataChecker.checkOldData(childView, new EventBean[] { a[0] });
SupportViewDataChecker.checkNewData(childView, new EventBean[] { e[0], e[1] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{b[0], b[1], c[0], d[0], e[0], e[1]}, myView.iterator());
EventBean[] f = makeBeans("f", 11500, 1);
stream.insert(f);
SupportViewDataChecker.checkOldData(childView, new EventBean[] { b[0], b[1] });
SupportViewDataChecker.checkNewData(childView, new EventBean[] { f[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{c[0], d[0], e[0], e[1], f[0]}, myView.iterator());
EventBean[] g = makeBeans("g", 11899, 1);
stream.insert(g);
SupportViewDataChecker.checkOldData(childView, null);
SupportViewDataChecker.checkNewData(childView, new EventBean[] { g[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{c[0], d[0], e[0], e[1], f[0], g[0]}, myView.iterator());
EventBean[] h = makeBeans("h", 11999, 3);
stream.insert(h);
SupportViewDataChecker.checkOldData(childView, new EventBean[] { c[0], d[0] });
SupportViewDataChecker.checkNewData(childView, new EventBean[] { h[0], h[1], h[2] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{e[0], e[1], f[0], g[0], h[0], h[1], h[2]}, myView.iterator());
EventBean[] i = makeBeans("i", 13001, 1);
stream.insert(i);
SupportViewDataChecker.checkOldData(childView, new EventBean[] { e[0], e[1], f[0], g[0], h[0], h[1], h[2] });
SupportViewDataChecker.checkNewData(childView, new EventBean[] { i[0] });
EPAssertionUtil.assertEqualsExactOrder(new EventBean[]{i[0]}, myView.iterator());
}
private EventBean[] makeBeans(String id, long timestamp, int numBeans)
{
EventBean[] beans = new EventBean[numBeans];
for (int i = 0; i < numBeans; i++)
{
SupportBean bean = new SupportBean();
bean.setLongPrimitive(timestamp);
bean.setTheString(id + 1);
beans[i] = SupportEventBeanFactory.createObject(bean);
}
return beans;
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/rm/bswap_o16_rDXr10.java | 1755 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.rm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class bswap_o16_rDXr10 extends Executable
{
public bswap_o16_rDXr10(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
}
public Branch execute(Processor cpu)
{
cpu.r_edx.set16((short)0);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
shamim2014/ResultManagement | src/java/WebApp/Util/TeacherMapper.java | 872 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package WebApp.Util;
import WebApp.Model.Teacher;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author shamim
*/
public class TeacherMapper implements ObjectRowMapper<Teacher>
{
@Override
public Teacher mapRowToObject(ResultSet resultSet) throws SQLException
{
Teacher teacher = new Teacher();
teacher.setName(resultSet.getString("name"));
teacher.setDesignation(resultSet.getString("designation"));
teacher.setDepartment(resultSet.getString("dept_name"));
teacher.setEmail(resultSet.getString("email"));
teacher.setPhone(resultSet.getString("phone"));
return teacher;
}
}
| gpl-2.0 |
codelibs/n2dms | src/main/java/com/openkm/util/impexp/metadata/CategoryMetadata.java | 1608 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.util.impexp.metadata;
public class CategoryMetadata {
private String uuid;
private String path;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("uuid=");
sb.append(uuid);
sb.append(", path=");
sb.append(path);
sb.append("}");
return sb.toString();
}
}
| gpl-2.0 |
mangash/cdbms | cdbms/src/org/bgu/nlp/wicket/demo/WicketDemo.java | 587 | package org.bgu.nlp.wicket.demo;
//import org.apache.wicket.bootstrap.Bootstrap;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.request.resource.CssResourceReference;
public class WicketDemo extends WebPage {
@Override
public void renderHead(IHeaderResponse response) {
//super.renderHead(response);
//Bootstrap.renderHeadPlain(response);
}
public WicketDemo()
{
//Label label=new Label("message","hello world!");
//add(label);
}
}
| gpl-2.0 |
flyroom/PeerfactSimKOM_Clone | src/org/peerfact/impl/util/toolkits/NumberFormatToolkit.java | 3638 | /*
* Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org>
* Copyright (c) 2011-2012 University of Paderborn - UPB
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM 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
* any later version.
*
* PeerfactSim.KOM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.peerfact.impl.util.toolkits;
import org.peerfact.impl.simengine.Simulator;
/**
* Allows generic tool methods for formatting numbers for human-readable
* representation.
*
* @author Leo Nobach <peerfact@kom.tu-darmstadt.de>
*
* @version 05/06/2011
*/
public class NumberFormatToolkit {
/**
* Formats the given double value of the simulation time to a string
* representing the seconds from simulation beginning.
*
* @param simTime
* , the current simulation time
* @param decimals
* , the trailing decimal digit count.
* @return
*/
public static String formatSecondsFromSimTime(double simTime, int decimals) {
return floorToDecimals(simTime / Simulator.SECOND_UNIT, decimals)
+ " s";
}
/**
* Formats the given quota value to a string representing the percentage,
* where quota = 1 results in '100%' and quota=0 results in '0%'
*
*/
public static String formatPercentage(double quota, int decimals) {
return floorToDecimals(quota * 100d, decimals) + "%";
}
/**
* Floors the given double to the largest double value that is less than or
* equal to the argument and is a decimal fraction value representable with
* the given decimal digit count.
*
* @param value
* @param decimals
* , the given decimal count.
* @return
*/
public static double floorToDecimals(double value, int decimals) {
double pow = Math.pow(10, decimals);
return (Math.floor(value * pow)) / pow;
}
/**
* Floors the given double to the largest double value that is less than or
* equal to the argument and is a decimal fraction value representable with
* the given decimal digit count. Returns a string.
*
* @param value
* @param decimals
* , the given decimal count.
* @return
*/
public static String floorToDecimalsString(double value, int decimals) {
return String.valueOf(floorToDecimals(value, decimals));
}
/**
* Formats the given value by using SI prefixes. Currently does NOT support
* values smaller than 1 (m, µ, n, p, ...)
*
* @param value
* @param decimals
* , the amount of decimal fraction digits to use to represent
* the value
* @param use1024
* , whether to use 1K = 1024, instead of 1K = 1000
* @return
*/
public static String formatSIPrefix(final double value, int decimals,
boolean use1024) {
char[] siPrefixes = { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };
int divisor = use1024 ? 1024 : 1000;
double valTemp = value;
int i = 0;
while (valTemp > divisor && i < siPrefixes.length) {
valTemp /= divisor;
i++;
}
return floorToDecimalsString(valTemp, decimals)
+ (i == 0 ? "" : siPrefixes[i - 1]);
}
}
| gpl-2.0 |
bayasist/vbox | out/linux.amd64/debug/obj/vboxjxpcom-gen/jxpcomgen/java/interfaces/ISerialPort.java | 1393 |
/**
* Copyright (C) 2010-2013 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* ISerialPort.java
*
* DO NOT EDIT! This is a generated file.
* Generated from: src/VBox/Main/idl/VirtualBox.xidl (VirtualBox's interface definitions in XML)
* Generator: src/VBox/src/libs/xpcom18a4/java/tools/genjifaces.xsl
*/
package org.mozilla.interfaces;
public interface ISerialPort extends nsISupports {
public static final String ISERIALPORT_IID =
"{937f6970-5103-4745-b78e-d28dcf1479a8}";
public long getSlot();
public boolean getEnabled();
public void setEnabled(boolean arg1);
public long getIOBase();
public void setIOBase(long arg1);
public long getIRQ();
public void setIRQ(long arg1);
public long getHostMode();
public void setHostMode(long arg1);
public boolean getServer();
public void setServer(boolean arg1);
public String getPath();
public void setPath(String arg1);
}
| gpl-2.0 |
mikemurussi/classificador-neural | src/redeneural/mlp/funcao/FuncaoTangenteHiperbolica.java | 399 | package redeneural.mlp.funcao;
/**
*
* @author Michael Murussi
*/
public class FuncaoTangenteHiperbolica extends Funcao {
@Override
public double calcula(double entrada) {
return (Math.exp(entrada) - Math.exp(-entrada)) / (Math.exp(entrada) + Math.exp(-entrada));
}
@Override
public double derivada(double saida) {
return (1 - Math.pow(saida, 2));
}
}
| gpl-2.0 |
bbones/proto1 | services/src/main/java/org/proto1/services/UtilityService.java | 916 | /*******************************************************************************
* Copyright (C) 2015 Valentin Pogrebinsky
*
* mail:pva@isd.com.ua
* https://github.com/bbones
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* GNU v2 license text in root directory of project
*******************************************************************************/
package org.proto1.services;
public interface UtilityService {
}
| gpl-2.0 |
Malkuthe/BattleClasses | battleclassmod/BattleClassMod.java | 2977 | package battleclassmod;
import java.io.File;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.common.MinecraftForge;
import battleclassmod.commands.CommandHandler;
import battleclassmod.config.ConfigHandler;
import battleclassmod.guis.BCMGuiHandler;
import battleclassmod.items.Items;
import battleclassmod.items.crafting.BCMClasses;
import battleclassmod.items.crafting.BoonCraftingHandler;
import battleclassmod.util.BCMClassConfigHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod( modid = BCMInfo.ID, name = BCMInfo.NAME, version = BCMInfo.VERSION )
@NetworkMod( channels = {BCMInfo.CHANNEL}, clientSideRequired = true, serverSideRequired = true, packetHandler = BCMPacketHandler.class )
public class BattleClassMod {
private static int modGuiIndex = 0;
public static final int GUI_CLASS_INTERFACE_INV = modGuiIndex++;
public static final String classConfigPath = "\\battleclassmodClassConfig.xml";
public static File confPath;
@Instance(BCMInfo.ID)
public static BattleClassMod instance = new BattleClassMod();
@EventHandler
public void preInit( FMLPreInitializationEvent event ){
ConfigHandler.Init(event.getSuggestedConfigurationFile());
this.confPath = event.getModConfigurationDirectory();
File classconf = new File(this.confPath + this.classConfigPath);
if (!classconf.isFile() || !classconf.exists()){
BCMClassConfigHandler.ClassCreate();
} else {
System.out.println("[BCM] classConfig.xml detected. Not creating new file.");
}
Items.init();
Items.addNames();
LanguageRegistry.instance().addStringLocalization("itemGroup.battleClasses", "en_US", "Battle Classes");
}
@EventHandler
public void Init( FMLInitializationEvent event ){
MinecraftForge.EVENT_BUS.register(new BCMEventHandler());
NetworkRegistry.instance().registerGuiHandler(this, new BCMGuiHandler());
proxy.registerRenderers();
BCMClasses.readConfig();
BoonCraftingHandler.Init();
}
@EventHandler
public void serverStart( FMLServerStartingEvent event ){
CommandHandler.Init();
}
@EventHandler
public void postInit( FMLPostInitializationEvent event ){
}
public static CreativeTabs tabCustom = new BCMCreativeTab(CreativeTabs.getNextID(), "battleClasses");
@SidedProxy( clientSide = BCMInfo.PROXY_LOCATION + ".ClientProxy", serverSide = BCMInfo.PROXY_LOCATION + ".CommonProxy" )
public static CommonProxy proxy;
}
| gpl-2.0 |
bdaum/zoraPD | com.bdaum.zoom.net.communities/src/com/bdaum/zoom/net/communities/MissingSignatureException.java | 1267 | /*
* This file is part of the ZoRa project: http://www.photozora.org.
* It is an adaptation of the equally named file from the jUploadr project (http://sourceforge.net/projects/juploadr/)
* (c) 2009 Steve Cohen and others
*
* jUploadr is licensed under the GNU Library or Lesser General Public License (LGPL).
*
* ZoRa is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* ZoRa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ZoRa; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Modifications (c) 2009 Berthold Daum
*/
package com.bdaum.zoom.net.communities;
import org.scohen.juploadr.uploadapi.ProtocolException;
@SuppressWarnings("serial")
public class MissingSignatureException extends ProtocolException {
// do nothing
}
| gpl-2.0 |
ButterFlyDevs/BrainStudio | app/src/main/java/butterflydevs/brainstudio/Ajustes.java | 9133 | /*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2015 Jose A. Gonzalez Cervera
Copyright 2015 Juan A. Fernández Sánchez
*/
package butterflydevs.brainstudio;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import butterflydevs.brainstudio.extras.ConexionServidor;
import butterflydevs.brainstudio.extras.Dialogos.DialogoBorrarBD;
import butterflydevs.brainstudio.extras.Dialogos.DialogoGrabadoAlias;
import butterflydevs.brainstudio.extras.utilidades;
/**
* Actividad que permite al usuario configurar algunos ajustes de la aplicación.
* En principio, su nombre de usuario (que será el que se use para grabar sus datos en el ranking)
* y el color en el que prefiere la aplicación (por meter algo distinto, ya que no había muchos más
* ajustes que hacer).
*/
public class Ajustes extends Activity {
private Button buttonBack, buttonBorrarDatos, buttonEditarNombre;
private TextView textNombreUsuario;
private Button colorA, colorB, colorC, colorD;
private info.hoang8f.android.segmented.SegmentedGroup grupo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajustes);
//Con esta orden conseguimos hacer que no se muestre la ActionBar.
//getSupportActionBar().hide();
//Con esta hacemos que la barra de estado del teléfono no se vea y la actividad sea a pantalla completa.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
buttonBack=(Button)findViewById(R.id.buttonBack);
buttonBorrarDatos=(Button)findViewById(R.id.buttonBorrarDatos);
textNombreUsuario=(TextView)findViewById(R.id.textViewNombreUsuario2);
buttonEditarNombre=(Button)findViewById(R.id.buttonEditName);
colorA=(Button)findViewById(R.id.ColorA);
colorB=(Button)findViewById(R.id.ColorB);
colorC=(Button)findViewById(R.id.ColorC);
colorD=(Button)findViewById(R.id.ColorD);
grupo=(info.hoang8f.android.segmented.SegmentedGroup)findViewById(R.id.grupoLista);
cargarNombreUsuario();
//Al pulsar uno de los colores cambiamos el color de fondo.
colorA.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Cambiamos de color el fondo, extrayendolo desde colors.xml
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.colorfondoA));
grabaColor("a");
}
}
);
colorB.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Cambiamos de color el fondo, extrayendolo desde colors.xml
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.colorfondoB));
grabaColor("b");
}
}
);
colorC.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Cambiamos de color el fondo, extrayendolo desde colors.xml
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.colorfondoC));
grabaColor("c");
}
}
);
colorD.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Cambiamos de color el fondo, extrayendolo desde colors.xml
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.colorfondoD));
grabaColor("d");
}
}
);
buttonBack.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creamos el Intent
Intent intent = new Intent(Ajustes.this, ActividadPrincipal.class);
//Iniciamos la nueva actividad
startActivity(intent);
}
}
);
buttonEditarNombre.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
//Se procede de la misma manera que cuando se arranca la activida principal por primera vez.
DialogoGrabadoAlias dga = new DialogoGrabadoAlias();
dga.setPadre(Ajustes.this); //Para que pueda acceder a las sharesPreferences de la app
dga.show(getFragmentManager(), "");
}
}
);
buttonBorrarDatos.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
/*Cuando el usuario quiere borra la base de datos tenemos que advertirle
de las consecuencias con un diálogo.
*/
//Creamos el dialogo:
DialogoBorrarBD dialogoAlerta = new DialogoBorrarBD();
dialogoAlerta.setPadre(Ajustes.this);
//Lo mostramos:
dialogoAlerta.show(getFragmentManager(), "");
}
}
);
utilidades.cargarColorFondo(this);
String colorUsado=utilidades.colorUsado(this);
if (colorUsado.contains("a"))
grupo.check(colorA.getId());
if(colorUsado.contains("b"))
grupo.check(colorB.getId());
if(colorUsado.contains("c"))
grupo.check(colorC.getId());
if(colorUsado.contains("d"))
grupo.check(colorD.getId());
}
/**
* Función para grabar color en las shared preferences.
*/
public void grabaColor(String color){
SharedPreferences datos=getSharedPreferences("datos", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=datos.edit();
editor.putString("colorFondo",color);
editor.commit(); //Cuando se hace realmente la grabación.
}
/**
* Cambia el nombre del usuario en la base de datos.
*/
public void cambiarNombreUsuarioBD(){
SharedPreferences prefe=getSharedPreferences("datos", Context.MODE_PRIVATE);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ConexionServidor miConexion = new ConexionServidor();
miConexion.actualizarNombre(prefe.getString("alias","Nombre"),telephonyManager.getDeviceId() );
}
/**
* Se extrae a una función para que pueda llamarse desde un par de sitios y así no duplicar código.
*/
public void cargarNombreUsuario(){
SharedPreferences prefe=getSharedPreferences("datos", Context.MODE_PRIVATE);
textNombreUsuario.setText(prefe.getString("alias","Nombre"));
}
/**
* Comprueba si el dispositivo tiene conexión de red.
* @return
*/
public boolean hayRed(){
boolean salida=true;
System.out.println("HAY RED??");
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getActiveNetworkInfo();
if(info!=null)
return true;
else
return false;
}
@Override
protected void onResume(){
super.onResume();
}
@Override
protected void onStart(){
super.onStart();
}
@Override
protected void onPause(){
super.onPause();
}
}
| gpl-2.0 |
oscarservice/oscar-old | src/test/java/org/oscarehr/common/dao/TicklerLinkDaoTest.java | 1803 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package org.oscarehr.common.dao;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import org.oscarehr.common.dao.utils.EntityDataGenerator;
import org.oscarehr.common.dao.utils.SchemaUtils;
import org.oscarehr.common.model.TicklerLink;
import org.oscarehr.util.SpringUtils;
public class TicklerLinkDaoTest {
private TicklerLinkDao dao = SpringUtils.getBean(TicklerLinkDao.class);
public TicklerLinkDaoTest() {
}
@Before
public void before() throws Exception {
SchemaUtils.restoreTable("tickler_link");
}
@Test
public void testCreate() throws Exception {
TicklerLink entity = new TicklerLink();
EntityDataGenerator.generateTestDataForModelClass(entity);
dao.persist(entity);
assertNotNull(entity.getId());
}
}
| gpl-2.0 |
Stachel/TeaSche | src/mj/android/teasche/TeaScheActivity.java | 540 | package mj.android.teasche;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class TeaScheActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tea_sche, menu);
return true;
}
//something new
// from site
}
| gpl-2.0 |
haiko/experimental | treinadvies/src/main/java/nl/cybercompany/treinadvies/web/application/TreinAdviesApplication.java | 4953 | package nl.cybercompany.treinadvies.web.application;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import nl.cybercompany.treinadvies.business.ReisplannerService;
import nl.cybercompany.treinadvies.domain.StationList;
import nl.cybercompany.treinadvies.web.pages.HomePage;
import nl.cybercompany.treinadvies.web.pages.ReisAdviesPage;
import org.apache.wicket.Application;
import org.apache.wicket.RuntimeConfigurationType;
import org.apache.wicket.Session;
import org.apache.wicket.core.request.mapper.MountedMapper;
import org.apache.wicket.devutils.DevelopmentUtilitiesNotEnabledException;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.mapper.parameter.PageParametersEncoder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import de.agilecoders.wicket.Bootstrap;
import de.agilecoders.wicket.settings.BootstrapSettings;
import de.agilecoders.wicket.settings.BootswatchThemeProvider;
import de.agilecoders.wicket.settings.ThemeProvider;
/**
* Application object for your web application. If you want to run this
* application without deploying, run the Start class.
*
* @see nl.cybercompany.treinadvies.web.pages.application.Start#main(String[])
*/
public class TreinAdviesApplication extends WebApplication {
private Properties properties;
@SpringBean
private ReisplannerService reisplannerService;
private StationList stationList;
/**
* Get Application for current thread.
*
* @return The current thread's Application
*/
public static TreinAdviesApplication get() {
return (TreinAdviesApplication) Application.get();
}
public TreinAdviesApplication() {
super();
properties = loadProperties();
setConfigurationType(RuntimeConfigurationType.valueOf(properties
.getProperty("configuration.type")));
}
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init() {
super.init();
getComponentInstantiationListeners().add(
new SpringComponentInjector(this));
Injector.get().inject(this);
getRootRequestMapperAsCompound().add(
new MountedMapper("advies", ReisAdviesPage.class,
new PageParametersEncoder()));
this.getApplicationSettings().setPageExpiredErrorPage(getHomePage());
this.getApplicationSettings().setInternalErrorPage(getHomePage());
this.getApplicationSettings().setAccessDeniedPage(getHomePage());
BootstrapSettings settings = new BootstrapSettings();
settings.minify(true); // use minimized version of all bootstrap
// references
Bootstrap.install(this, settings);
if(RuntimeConfigurationType.DEVELOPMENT.equals(this.getConfigurationType())){
getDebugSettings().setDevelopmentUtilitiesEnabled(true);
getMarkupSettings().setCompressWhitespace(true);
}
if(RuntimeConfigurationType.DEPLOYMENT.equals(this.getConfigurationType())){
getMarkupSettings().setCompressWhitespace(true);
getMarkupSettings().setStripComments(true);
getMarkupSettings().setStripWicketTags(true);
}
}
/**
* Get {@link StationList}
*
* @return
*/
public StationList getStationList() {
if (stationList == null) {
// initialize stationlist.
this.stationList = reisplannerService.getStationList();
}
return stationList;
}
@Override
public Session newSession(Request request, Response response) {
Session session = super.newSession(request, response);
// fix on dutch for now
session.setLocale(new Locale("nl"));
return session;
}
public ReisplannerService getReisplannerService() {
return reisplannerService;
}
public void setReisplannerService(ReisplannerService reisplannerService) {
this.reisplannerService = reisplannerService;
}
public Properties getProperties() {
return properties;
}
private Properties loadProperties() {
Properties properties = new Properties();
try {
properties.load(getClass()
.getResourceAsStream("/config.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
return properties;
}
private void configureBootstrap() {
BootstrapSettings settings = new BootstrapSettings();
settings.minify(true) // use minimized version of all bootstrap references
.useJqueryPP(true)
.useModernizr(true)
.useResponsiveCss(true)
.getBootstrapLessCompilerSettings().setUseLessCompiler(true);
ThemeProvider themeProvider = new BootswatchThemeProvider() {{
defaultTheme("bootstrap");
}};
settings.setThemeProvider(themeProvider);
Bootstrap.install(this, settings);
}
}
| gpl-2.0 |
marchold/taxi-driver-droid | TaxiDriver Droid Paid/gen/com/catglo/taxidroidpaid/R.java | 31382 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.catglo.taxidroidpaid;
public final class R {
public static final class anim {
public static final int slide_left_in=0x7f040000;
public static final int slide_left_out=0x7f040001;
public static final int slide_right_in=0x7f040002;
public static final int slide_right_out=0x7f040003;
}
public static final class array {
public static final int DaysOfTheWeek=0x7f060000;
public static final int DaysOfWeekValues=0x7f060001;
}
public static final class attr {
}
public static final class drawable {
public static final int abc=0x7f020000;
public static final int abc_selected=0x7f020001;
public static final int abc_selector=0x7f020002;
public static final int action_drop_icon=0x7f020003;
public static final int back_for_nav=0x7f020004;
public static final int black_calculator_icon=0x7f020005;
public static final int black_vertical_line=0x7f020006;
public static final int blue_gradent_background=0x7f020007;
public static final int blue_gradent_background_small=0x7f020008;
public static final int bubble_point_bottom_left=0x7f020009;
public static final int bubble_point_top_left=0x7f02000a;
public static final int button_back=0x7f02000b;
public static final int button_pad=0x7f02000c;
public static final int calendar_icon=0x7f02000d;
public static final int clock=0x7f02000e;
public static final int del=0x7f02000f;
public static final int del_selected=0x7f020010;
public static final int dot=0x7f020011;
public static final int dot_selected=0x7f020012;
public static final int happy=0x7f020013;
public static final int ic_launcher_maps=0x7f020014;
public static final int ic_menu_bank=0x7f020015;
public static final int ic_menu_calculator=0x7f020016;
public static final int ic_menu_convert_csv=0x7f020017;
public static final int ic_menu_guy_clock=0x7f020018;
public static final int ic_mp_move=0x7f020019;
public static final int ic_nav=0x7f02001a;
public static final int icon=0x7f02001b;
public static final int icon_plus=0x7f02001c;
public static final int marker=0x7f02001d;
public static final int marker_green=0x7f02001e;
public static final int mirror_rect=0x7f02001f;
public static final int next=0x7f020020;
public static final int next_selected=0x7f020021;
public static final int num0=0x7f020022;
public static final int num0_selected=0x7f020023;
public static final int num1=0x7f020024;
public static final int num1_selected=0x7f020025;
public static final int num2=0x7f020026;
public static final int num2_selected=0x7f020027;
public static final int num3=0x7f020028;
public static final int num3_selected=0x7f020029;
public static final int num4=0x7f02002a;
public static final int num4_selected=0x7f02002b;
public static final int num5=0x7f02002c;
public static final int num5_selected=0x7f02002d;
public static final int num6=0x7f02002e;
public static final int num6_selected=0x7f02002f;
public static final int num7=0x7f020030;
public static final int num7_selected=0x7f020031;
public static final int num8=0x7f020032;
public static final int num8_selected=0x7f020033;
public static final int num9=0x7f020034;
public static final int num9_selected=0x7f020035;
public static final int odo_icon=0x7f020036;
public static final int selector0=0x7f020037;
public static final int selector1=0x7f020038;
public static final int selector2=0x7f020039;
public static final int selector3=0x7f02003a;
public static final int selector4=0x7f02003b;
public static final int selector5=0x7f02003c;
public static final int selector6=0x7f02003d;
public static final int selector7=0x7f02003e;
public static final int selector8=0x7f02003f;
public static final int selector9=0x7f020040;
public static final int selector_del=0x7f020041;
public static final int selector_dot=0x7f020042;
public static final int selector_next=0x7f020043;
public static final int slider_nosnap=0x7f020044;
public static final int slider_snap=0x7f020045;
public static final int space=0x7f020046;
public static final int space_button=0x7f020047;
public static final int space_selected=0x7f020048;
public static final int table_title_backgtound=0x7f020049;
public static final int talk_bubble1=0x7f02004a;
public static final int white_calculator_icon=0x7f02004b;
public static final int white_vertical_line=0x7f02004c;
}
public static final class id {
public static final int ActionBar=0x7f070004;
public static final int AddDelevery=0x7f07004f;
public static final int AddOrder=0x7f07005c;
public static final int Button01=0x7f07001c;
public static final int Button02=0x7f07001d;
public static final int Button03=0x7f07001e;
public static final int Button04=0x7f070019;
public static final int Button05=0x7f07001a;
public static final int Button06=0x7f07001b;
public static final int Button07=0x7f070016;
public static final int Button08=0x7f070017;
public static final int Button09=0x7f070018;
public static final int ButtonAbc=0x7f070023;
public static final int ButtonDel=0x7f070021;
public static final int ButtonDot=0x7f07001f;
public static final int ButtonGoSearch=0x7f07008b;
public static final int ButtonNext=0x7f070024;
public static final int ButtonNoSearch=0x7f07008d;
public static final int ButtonSpace=0x7f070022;
public static final int ButtonSpeech=0x7f070026;
public static final int ButtonZero=0x7f070020;
public static final int CashTips=0x7f070070;
public static final int CashTipsText=0x7f07006e;
public static final int Checkout=0x7f070050;
public static final int DeliveriesSummaryList=0x7f070076;
public static final int EditText01=0x7f070062;
public static final int HelpDrag=0x7f070052;
public static final int ImageView01=0x7f070060;
public static final int LinearLayout1=0x7f070080;
public static final int LinearLayout2=0x7f070047;
public static final int ListView01=0x7f070063;
public static final int MapLayout=0x7f070085;
public static final int MapLayoutWrapper=0x7f070089;
public static final int Navigate=0x7f07007e;
public static final int NewOrderLastScreen=0x7f070054;
public static final int OrderAddress=0x7f07005a;
public static final int OrderNotes=0x7f07005e;
public static final int OrderNumber=0x7f070056;
public static final int OrderNumberText=0x7f070055;
public static final int OrderPlacedTime=0x7f07009a;
public static final int OrderTime=0x7f070057;
public static final int ProgressBar01=0x7f070028;
public static final int RadiusPicker=0x7f070087;
public static final int RelativeLayout01=0x7f070088;
public static final int RelativeLayout1=0x7f07007b;
public static final int TableLayout01=0x7f07009f;
public static final int TableLayout05=0x7f070074;
public static final int TableLayout1=0x7f070035;
public static final int TableRow01=0x7f0700a0;
public static final int TableRow02=0x7f0700a1;
public static final int TableRow03=0x7f0700a2;
public static final int TextView01=0x7f070061;
public static final int TextView02=0x7f0700a3;
public static final int ZiptextArea=0x7f070086;
public static final int addressAutocomplete1=0x7f070001;
public static final int addressListText=0x7f070097;
public static final int addressSelectedLine=0x7f070011;
public static final int addressSmall=0x7f07009e;
public static final int autoCompleteTextView1=0x7f07004b;
public static final int backButton=0x7f070008;
public static final int bigMainButton=0x7f070079;
public static final int button1=0x7f070025;
public static final int button2=0x7f07004c;
public static final int button3=0x7f07007f;
public static final int buttonLayout=0x7f07004e;
public static final int buttonPadButtonLayout=0x7f070015;
public static final int buttonPadEdit=0x7f070014;
public static final int buttonPadList=0x7f070027;
public static final int buttonPadText=0x7f070029;
public static final int cash_check_card=0x7f07007d;
public static final int checkBox1=0x7f070045;
public static final int check_out_order_number=0x7f07002c;
public static final int checkout_trip_type=0x7f07002d;
public static final int complex=0x7f07009d;
public static final int currentAddress=0x7f070078;
public static final int databasePrimaryKey=0x7f070048;
public static final int datePicker1=0x7f07002f;
public static final int datePicker2=0x7f07002e;
public static final int dateSliderButLayout=0x7f070031;
public static final int dateSliderCancelButton=0x7f070033;
public static final int dateSliderMainLayout=0x7f070030;
public static final int dateSliderOkButton=0x7f070032;
public static final int dateSliderTitleText=0x7f070034;
public static final int detailsSelectedLine=0x7f070013;
public static final int dropOffContainer=0x7f07005b;
public static final int editText1=0x7f070003;
public static final int editText2=0x7f070043;
public static final int editText3=0x7f070039;
public static final int editText4=0x7f070046;
public static final int headingA=0x7f070075;
public static final int icon=0x7f07009c;
public static final int idField=0x7f070002;
public static final int imageButton1=0x7f070044;
public static final int imageView1=0x7f070005;
public static final int imageView2=0x7f070006;
public static final int imageView4=0x7f070009;
public static final int linearLayout1=0x7f07002a;
public static final int linearLayout2=0x7f070038;
public static final int linearLayout3=0x7f07003d;
public static final int linearLayout4=0x7f07003a;
public static final int linearLayout5=0x7f07003e;
public static final int linearLayout6=0x7f070041;
public static final int listView1=0x7f07004a;
public static final int look_up_store_address=0x7f0700a8;
public static final int mapview=0x7f070053;
public static final int numberSelectedLine=0x7f07000d;
public static final int orderList=0x7f070051;
public static final int osCashCollected=0x7f070072;
public static final int osCreditTips=0x7f070073;
public static final int osCreditTipsText=0x7f070071;
public static final int osDate=0x7f070065;
public static final int osLinearLayout1=0x7f070069;
public static final int osMoneyCollected=0x7f07006b;
public static final int osNumberOfDeliveries=0x7f070067;
public static final int osShift=0x7f070066;
public static final int osStreightLine1=0x7f070068;
public static final int osTextCashCollected=0x7f07006c;
public static final int osTextMoneyCollected=0x7f07006a;
public static final int osTextTipsMade=0x7f07006d;
public static final int osTipsMade=0x7f07006f;
public static final int osTopLayout=0x7f070064;
public static final int outOfTownCheck2=0x7f07009b;
public static final int paymentTotal_2=0x7f07007c;
public static final int priceSelectedLine=0x7f07000f;
public static final int progressBar1=0x7f07000a;
public static final int radio0=0x7f070082;
public static final int radio1=0x7f070083;
public static final int radio2=0x7f070084;
public static final int radioGroup1=0x7f070081;
public static final int relativeLayout=0x7f070049;
public static final int relativeLayout1=0x7f070000;
public static final int relativeLayout2=0x7f07008e;
public static final int scrollView1=0x7f07007a;
public static final int sewidget29=0x7f070098;
public static final int sewidget606=0x7f07005f;
public static final int spinner1=0x7f07003f;
public static final int storeAddress=0x7f0700a7;
public static final int tableRow1=0x7f070036;
public static final int tableRow2=0x7f07003c;
public static final int tableRow3=0x7f070037;
public static final int tableRow4=0x7f070040;
public static final int table_row=0x7f07002b;
public static final int text2=0x7f07008c;
public static final int textOrder=0x7f070058;
public static final int textView1=0x7f07000c;
public static final int textView10=0x7f070091;
public static final int textView11=0x7f070094;
public static final int textView12=0x7f070092;
public static final int textView13=0x7f070093;
public static final int textView14=0x7f0700a5;
public static final int textView2=0x7f070007;
public static final int textView3=0x7f07000e;
public static final int textView4=0x7f070010;
public static final int textView5=0x7f070012;
public static final int textView6=0x7f07008f;
public static final int textView7=0x7f070096;
public static final int textView8=0x7f070090;
public static final int textView9=0x7f070095;
public static final int timeStampEditField=0x7f07003b;
public static final int userZip=0x7f0700a9;
public static final int variableLabel=0x7f070042;
public static final int view1=0x7f07000b;
public static final int viewPartLayout=0x7f070099;
public static final int widget169=0x7f070059;
public static final int widget170=0x7f07005d;
public static final int widget29=0x7f070077;
public static final int widget38=0x7f07004d;
public static final int wordtTip=0x7f0700a4;
public static final int zipCodeMap=0x7f07008a;
public static final int zipDialog=0x7f0700a6;
}
public static final class layout {
public static final int address_list_item=0x7f030000;
public static final int address_time_row=0x7f030001;
public static final int button_pad=0x7f030002;
public static final int check_out_list=0x7f030003;
public static final int date_range_dialog=0x7f030004;
public static final int dateslider=0x7f030005;
public static final int dialogtitle=0x7f030006;
public static final int drop_edit_row=0x7f030007;
public static final int drop_input_row=0x7f030008;
public static final int dropoff_input_row=0x7f030009;
public static final int expense_input_row=0x7f03000a;
public static final int expense_row=0x7f03000b;
public static final int expenses=0x7f03000c;
public static final int export_csv_how_dialog=0x7f03000d;
public static final int main=0x7f03000e;
public static final int main_map=0x7f03000f;
public static final int new_order_last_screen=0x7f030010;
public static final int number_input=0x7f030011;
public static final int odometer_input=0x7f030012;
public static final int order_summary=0x7f030013;
public static final int out_the_door=0x7f030014;
public static final int payment=0x7f030015;
public static final int payment_noshow=0x7f030016;
public static final int scroller=0x7f030017;
public static final int settings=0x7f030018;
public static final int setup_location=0x7f030019;
public static final int start_end_shift=0x7f03001a;
public static final int street_address_list=0x7f03001b;
public static final int summary_edit=0x7f03001c;
public static final int table_row=0x7f03001d;
public static final int text=0x7f03001e;
public static final int tips_totals=0x7f03001f;
public static final int user_location=0x7f030020;
public static final int zip_code_list=0x7f030021;
}
public static final class string {
public static final int AddOrder=0x7f050002;
public static final int AddStreetDialogMessage=0x7f050030;
public static final int Address=0x7f0500a4;
public static final int AddressHouseNumber=0x7f05009f;
public static final int AuthorizationNumber=0x7f0500cc;
public static final int Cancel=0x7f05002b;
public static final int Cash=0x7f05000c;
public static final int Check=0x7f05000b;
public static final int ClearValues=0x7f05009b;
public static final int Commission_for_scheduled_jobs=0x7f0500aa;
public static final int Commission_for_scheduled_jobs_account=0x7f0500ae;
public static final int Commission_for_scheduled_jobs_credit=0x7f0500ac;
public static final int Commission_for_scheduled_jobs_sum=0x7f0500ab;
public static final int Commission_for_scheduled_jobs_sum_account=0x7f0500af;
public static final int Commission_for_scheduled_jobs_sum_credit=0x7f0500ad;
public static final int Commission_for_street_hire=0x7f0500b0;
public static final int Commission_for_street_hire_account=0x7f0500b4;
public static final int Commission_for_street_hire_credit=0x7f0500b2;
public static final int Commission_for_street_hire_sum=0x7f0500b1;
public static final int Commission_for_street_hire_sum_account=0x7f0500b5;
public static final int Commission_for_street_hire_sum_credit=0x7f0500b3;
public static final int Credit=0x7f05000a;
public static final int CustomDateRange=0x7f050072;
public static final int DeletetreetDialogTitle=0x7f05002d;
public static final int Delivery_time=0x7f050058;
public static final int Details=0x7f0500a6;
public static final int DriverEarnings=0x7f050012;
public static final int EDITORDER=0x7f05001c;
public static final int EditStreetDialogMessage=0x7f05002c;
public static final int EditStreetDialogTitle=0x7f050029;
public static final int ExportTo=0x7f050077;
public static final int Feedback=0x7f050037;
public static final int Finish=0x7f0500a5;
public static final int Initial_Order_Number=0x7f050064;
public static final int Initial_Order_Number_daigTitle=0x7f050066;
public static final int Initial_Order_Number_desc=0x7f050065;
public static final int Mileage=0x7f050013;
public static final int MileagePay=0x7f05003c;
public static final int MileagePaySum=0x7f05003d;
public static final int Mileagepayperdelivery=0x7f05003e;
public static final int MinutesAddress=0x7f05001d;
public static final int MoneyCollected=0x7f0500e2;
public static final int NewStreetDialogTitle=0x7f05002f;
public static final int Next=0x7f05000f;
public static final int No=0x7f05001a;
public static final int No_addresses=0x7f050067;
public static final int No_addresses_desc=0x7f050068;
public static final int Number=0x7f0500a2;
public static final int Ok=0x7f05002a;
public static final int Order=0x7f0500a7;
public static final int OrderAddress=0x7f050004;
public static final int OrderEntrySettings=0x7f050082;
public static final int OrderNotes=0x7f050003;
public static final int OrderNumber=0x7f050007;
public static final int OrderTime=0x7f050006;
public static final int OrderTotal=0x7f050005;
public static final int Order_placed=0x7f050059;
public static final int OutOfTown=0x7f05001f;
public static final int PayPercentageSum=0x7f050042;
public static final int PayPercentageTitle=0x7f050043;
public static final int PayPercentageTotalTitle=0x7f050041;
public static final int Payment=0x7f050010;
public static final int PendingDeliveries=0x7f050011;
public static final int PreviousDelivery=0x7f05001b;
public static final int Price=0x7f0500a3;
public static final int Review=0x7f05003a;
public static final int Save_Changes=0x7f050027;
public static final int SendFeedback=0x7f050035;
public static final int Speak_address=0x7f050026;
public static final int SplitOrder=0x7f050008;
public static final int StartOfWorkWeek=0x7f05007f;
public static final int StartOfWorkWeek_diagSum=0x7f050080;
public static final int StartOfWorkWeek_diagTitle=0x7f050081;
public static final int StartRunDialogMessage=0x7f05001e;
public static final int StartRunDialogTitle=0x7f050018;
public static final int Start_End_Shift=0x7f050085;
public static final int Store_Address=0x7f050069;
public static final int Store_Address_desc=0x7f05006a;
public static final int ThisMonth=0x7f050070;
public static final int ThisYear=0x7f050071;
public static final int Yes=0x7f050019;
public static final int account=0x7f0500ca;
public static final int actualPickupTime=0x7f0500c1;
public static final int addDropoff=0x7f0500b8;
public static final int addExpense=0x7f0500f5;
public static final int addPickup=0x7f0500b7;
public static final int add_new_street=0x7f050022;
public static final int altMilDiagTitle=0x7f05004c;
public static final int altMilSum=0x7f05004b;
public static final int altMilTitle=0x7f05004a;
public static final int altPay2=0x7f05004d;
public static final int altPay2Sum=0x7f050050;
public static final int altPay3=0x7f05004e;
public static final int altPay4=0x7f05004f;
public static final int altPayDT=0x7f050051;
public static final int altPayL=0x7f050052;
public static final int altPayLDT=0x7f050055;
public static final int altPayLSum=0x7f050053;
public static final int altPayLSum1=0x7f050054;
public static final int altPaySettingsInstructions=0x7f050061;
public static final int apartmentNumber=0x7f050034;
public static final int app_name=0x7f050001;
public static final int arrivalTime=0x7f0500c3;
public static final int average=0x7f05008f;
public static final int averageTip=0x7f050092;
public static final int bankHeading=0x7f050097;
public static final int bany_till_drop=0x7f050088;
public static final int bestTip=0x7f050091;
public static final int black_color_value=0x7f05005a;
public static final int blank=0x7f050095;
public static final int cancelOrder=0x7f0500bf;
public static final int cancled=0x7f0500e5;
public static final int cashTips=0x7f050017;
public static final int chargeNoShowFee=0x7f0500e4;
public static final int commision=0x7f0500f2;
public static final int commision_help=0x7f0500fa;
public static final int commissionChargeSettings=0x7f0500a8;
public static final int commissionChargeSettings_sum=0x7f0500a9;
public static final int complete=0x7f0500e7;
public static final int contactdev=0x7f050036;
public static final int coustomerGotInCab=0x7f0500c4;
public static final int creditTips=0x7f050016;
public static final int currentAddress=0x7f0500e9;
public static final int currentEarnings=0x7f050015;
public static final int customerInCabButton=0x7f0500c7;
public static final int cvs_email_subject=0x7f05007d;
public static final int date=0x7f050057;
public static final int deleteStreetButton=0x7f050032;
public static final int deleteThisRecord=0x7f0500e1;
public static final int deleteThisShift=0x7f0500dc;
public static final int delete_street_message=0x7f05002e;
public static final int delete_street_name=0x7f050021;
public static final int deliveries=0x7f0500d4;
public static final int done=0x7f0500ee;
public static final int drag_deliveries=0x7f050031;
public static final int drivingToPickup=0x7f0500c5;
public static final int dropOff=0x7f0500c9;
public static final int dropOffAddress=0x7f0500bc;
public static final int dropOffHeading=0x7f0500c8;
public static final int drops=0x7f05009a;
public static final int ebt=0x7f05005f;
public static final int editThisStreet=0x7f050033;
public static final int edit_street_name=0x7f050023;
public static final int edit_street_names=0x7f050020;
public static final int email=0x7f050079;
public static final int email_save_html_warning=0x7f0500f9;
public static final int endDate=0x7f050075;
public static final int endThisShift=0x7f0500d9;
public static final int enterFileName=0x7f050078;
public static final int expences=0x7f0500f3;
public static final int export=0x7f05007a;
public static final int exportWhereDialogTitle=0x7f0500f8;
public static final int export_dialog_title=0x7f05007b;
public static final int foodStamps=0x7f050009;
public static final int goBacAShift=0x7f0500da;
public static final int goBack=0x7f05005d;
public static final int goToDay=0x7f0500dd;
public static final int hello=0x7f050000;
public static final int help=0x7f050060;
public static final int hour=0x7f05006c;
public static final int hourly_pay_at_work=0x7f05008b;
public static final int hourly_pay_rate=0x7f050089;
public static final int hoursWorked=0x7f0500e0;
public static final int immediatePickup=0x7f0500d2;
public static final int leaveBlankForGPSAddress=0x7f0500ea;
public static final int loanFromWork=0x7f05009e;
public static final int logSheet=0x7f0500f0;
public static final int lookingUpCurrentAddress=0x7f0500e8;
public static final int maps_AIP_KEY_debug=0x7f0500ed;
public static final int maps_API_KEY=0x7f0500eb;
public static final int maps_API_KEY_RELASE=0x7f0500ec;
public static final int meterAmount=0x7f0500cb;
public static final int midnight=0x7f0500a0;
public static final int mileageRunDiagTitle=0x7f050049;
public static final int mileageRunSum=0x7f050048;
public static final int mileageRunTitle=0x7f050047;
public static final int mileageand=0x7f05003b;
public static final int milesDriven=0x7f0500df;
public static final int minute=0x7f05006d;
public static final int minutes=0x7f05000d;
public static final int navy_color_code=0x7f05005b;
public static final int noShow=0x7f0500be;
public static final int no_order_numbers=0x7f050062;
public static final int no_order_numbers_desc=0x7f050063;
public static final int noon=0x7f0500a1;
public static final int not_split=0x7f05006b;
public static final int notes=0x7f0500bb;
public static final int oder_number=0x7f050024;
public static final int odoDiagTitle=0x7f050046;
public static final int odoSum=0x7f050045;
public static final int odo_and_hr=0x7f0500db;
public static final int odometerAtEnd=0x7f0500d8;
public static final int odometerTitle=0x7f050044;
public static final int odometerTotal=0x7f0500d3;
public static final int onScene=0x7f0500bd;
public static final int orderEntrySettingsHelp=0x7f050083;
public static final int order_number=0x7f050028;
public static final int order_price=0x7f050025;
public static final int order_summary=0x7f050087;
public static final int orders=0x7f0500e3;
public static final int pay_rate_on_run=0x7f05008d;
public static final int pay_rate_on_run_sum=0x7f05008e;
public static final int paymentType=0x7f0500cd;
public static final int pickup=0x7f0500c0;
public static final int pickupAddress=0x7f0500ba;
public static final int pickupTime=0x7f0500b9;
public static final int pickups=0x7f0500d0;
public static final int please_enter_persentage=0x7f0500b6;
public static final int printableHTML=0x7f0500f7;
public static final int quit=0x7f05005c;
public static final int rawCSVData=0x7f0500f6;
public static final int reimburse=0x7f0500f4;
public static final int reviewapp=0x7f050038;
public static final int scheduledPickupTime=0x7f0500c2;
public static final int sdcard=0x7f05007c;
public static final int selectDateRange=0x7f050076;
public static final int set_amount_per_hour=0x7f05008c;
public static final int settings=0x7f050084;
public static final int shiftEndTime=0x7f0500d6;
public static final int shiftStartOdometer=0x7f0500d7;
public static final int shiftStartTime=0x7f0500d5;
public static final int showNotes=0x7f0500de;
public static final int startDate=0x7f050074;
public static final int status=0x7f0500e6;
public static final int streetHire=0x7f0500f1;
public static final int summary=0x7f0500d1;
public static final int textMessage=0x7f050094;
public static final int tha_amount_pait_by_store=0x7f05008a;
public static final int theamount=0x7f05003f;
public static final int theamounttitle=0x7f050040;
public static final int thisShift=0x7f05006e;
public static final int thisWeek=0x7f05006f;
public static final int time=0x7f050056;
public static final int tipHistory=0x7f050086;
public static final int tips=0x7f050014;
public static final int tipsHistoryExportEmailTop=0x7f050096;
public static final int tipsMade=0x7f050090;
public static final int today=0x7f050073;
public static final int total=0x7f05009c;
public static final int totalYouOwe=0x7f050098;
public static final int totalYourOwed=0x7f050099;
public static final int tripType=0x7f0500ef;
public static final int undelivered=0x7f05005e;
public static final int wait=0x7f05000e;
public static final int waitingForCoustomer=0x7f0500c6;
public static final int workOwsYou=0x7f0500ce;
public static final int worstTip=0x7f050093;
public static final int wrote=0x7f05007e;
public static final int youOweWork=0x7f0500cf;
public static final int youlike=0x7f050039;
public static final int yourMoney=0x7f05009d;
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest18021.java | 2474 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest18021")
public class BenchmarkTest18021 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> names = request.getParameterNames();
if (names.hasMoreElements()) {
param = names.nextElement(); // just grab first element
}
String bar = doSomething(param);
try {
java.nio.file.Path path = java.nio.file.Paths.get(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
java.io.InputStream is = java.nio.file.Files.newInputStream(path, java.nio.file.StandardOpenOption.READ);
} catch (Exception e) {
// OK to swallow any exception for now
// TODO: Fix this, if possible.
System.out.println("File exception caught and swallowed: " + e.getMessage());
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int i = 86;
if ( (7*42) - i > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
}
| gpl-2.0 |
qiuxs/ice-demos | java/Freeze/library/BookI.java | 2674 | // **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// **********************************************************************
import Demo.*;
class BookI extends Book
{
//
// No read/write mutexes in Java - hence use native
// synchronization.
//
@Override
synchronized public BookDescription
getBookDescription(Ice.Current current)
{
if(_destroyed)
{
throw new Ice.ObjectNotExistException();
}
//
// Immutable.
//
return description;
}
@Override
synchronized public String
getRenterName(Ice.Current current)
throws BookNotRentedException
{
if(_destroyed)
{
throw new Ice.ObjectNotExistException();
}
if(rentalCustomerName.length() == 0)
{
throw new BookNotRentedException();
}
return rentalCustomerName;
}
@Override
synchronized public void
rentBook(String name, Ice.Current current)
throws BookRentedException
{
if(_destroyed)
{
throw new Ice.ObjectNotExistException();
}
if(rentalCustomerName.length() != 0)
{
throw new BookRentedException();
}
rentalCustomerName = name;
}
@Override
synchronized public void
returnBook(Ice.Current current)
throws BookNotRentedException
{
if(_destroyed)
{
throw new Ice.ObjectNotExistException();
}
if(rentalCustomerName.length() == 0)
{
throw new BookNotRentedException();
}
rentalCustomerName = new String();;
}
@Override
synchronized public void
destroy(Ice.Current current)
throws DatabaseException
{
if(_destroyed)
{
throw new Ice.ObjectNotExistException();
}
_destroyed = true;
try
{
_library.remove(description);
}
catch(Freeze.DatabaseException ex)
{
DatabaseException e = new DatabaseException();
e.message = ex.message;
throw e;
}
}
BookI(LibraryI library)
{
_library = library;
_destroyed = false;
//
// This could be avoided by having two constructors (one for
// new creation of a book, and the other for restoring a
// previously saved book).
//
rentalCustomerName = new String();
}
private LibraryI _library;
private boolean _destroyed;
}
| gpl-2.0 |
secern/gfreader | src/cn/gfreader/util/FileCharsetDetector.java | 3689 | package cn.gfreader.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
public class FileCharsetDetector {
private boolean found = false;
/**
* 如果完全匹配某个字符集检测算法, 则该属性保存该字符集的名称. 否则(如二进制文件)其值就为默认值 null, 这时应当查询属性
*/
private String encoding = null;
/**
* 传入一个文件(File)对象,检查文件编码
*
* @param file
* File对象实例
* @return 文件编码,若无,则返回null
* @throws FileNotFoundException
* @throws IOException
*/
public String guestFileEncoding(File file) throws FileNotFoundException,
IOException {
return geestFileEncoding(file, new nsDetector());
}
/**
* 获取文件的编码
*
* @param file
* File对象实例
* @param languageHint
* 语言提示区域代码 eg:1 : Japanese; 2 : Chinese; 3 : Simplified Chinese;
* 4 : Traditional Chinese; 5 : Korean; 6 : Dont know (default)
* @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
* @throws FileNotFoundException
* @throws IOException
*/
public String guestFileEncoding(File file, int languageHint)
throws FileNotFoundException, IOException {
return geestFileEncoding(file, new nsDetector(languageHint));
}
/**
* 获取文件的编码
*
* @param path
* 文件路径
* @return 文件编码,eg:UTF-8,GBK,GB2312形式,若无,则返回null
* @throws FileNotFoundException
* @throws IOException
*/
public String guestFileEncoding(String path) throws FileNotFoundException,
IOException {
return guestFileEncoding(new File(path));
}
/**
* 获取文件的编码
*
* @param path
* 文件路径
* @param languageHint
* 语言提示区域代码 eg:1 : Japanese; 2 : Chinese; 3 : Simplified Chinese;
* 4 : Traditional Chinese; 5 : Korean; 6 : Dont know (default)
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public String guestFileEncoding(String path, int languageHint)
throws FileNotFoundException, IOException {
return guestFileEncoding(new File(path), languageHint);
}
/**
* 获取文件的编码
*
* @param file
* @param det
* @return
* @throws FileNotFoundException
* @throws IOException
*/
private String geestFileEncoding(File file, nsDetector det)
throws FileNotFoundException, IOException {
// Set an observer...
// The Notify() will be called when a matching charset is found.
det.Init(new nsICharsetDetectionObserver() {
public void Notify(String charset) {
found = true;
encoding = charset;
}
});
BufferedInputStream imp = new BufferedInputStream(new FileInputStream(
file));
byte[] buf = new byte[1024];
int len;
boolean done = false;
boolean isAscii = true;
while ((len = imp.read(buf, 0, buf.length)) != -1) {
// Check if the stream is only ascii.
if (isAscii)
isAscii = det.isAscii(buf, len);
// DoIt if non-ascii and not done yet.
if (!isAscii && !done)
done = det.DoIt(buf, len, false);
}
det.DataEnd();
imp.close();
if (isAscii) {
encoding = "ASCII";
found = true;
}
if (!found) {
String prob[] = det.getProbableCharsets();
if (prob.length > 0) {
// 在没有发现情况下,则取第一个可能的编码
encoding = prob[0];
} else {
return null;
}
}
return encoding;
}
} | gpl-2.0 |
h3xstream/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00441.java | 2385 | /**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark 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.
*
* @author Nick Sanidas
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/sqli-00/BenchmarkTest00441")
public class BenchmarkTest00441 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = request.getParameter("BenchmarkTest00441");
if (param == null) param = "";
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String bar = thing.doSomething(param);
String sql = "INSERT INTO users (username, password) VALUES ('foo','"+ bar + "')";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
int count = statement.executeUpdate( sql, new int[] {1,2} );
org.owasp.benchmark.helpers.DatabaseHelper.outputUpdateComplete(sql, response);
} catch (java.sql.SQLException e) {
if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
response.getWriter().println(
"Error processing request."
);
return;
}
else throw new ServletException(e);
}
}
}
| gpl-2.0 |
Hewie8023/byzq | src/com/byzq/dao/SingerDao.java | 4694 | package com.byzq.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;
import com.byzq.entity.Singer;
import com.byzq.util.DbUtil;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
public class SingerDao {
/**
*
* Ìí¼Ó¸èÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-4 ÏÂÎç8:49:31
* @return
*/
public int addSinger(Singer singer) throws Exception {
String sql = "insert into singer values(null,?,?,?,?)";
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, singer.getSingername());
ps.setString(2, singer.getSingertype());
ps.setString(3, singer.getRegion());
ps.setString(4, singer.getPhotoUrl());
return ps.executeUpdate();
}
/**
*
* ͨ¹ýÃû×Ö²éѯ¸èÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-4 ÏÂÎç7:42:26
* @return
*/
public Singer querySingerByName(String singername) {
String sql = "select SingerID, SingerName,SingerType,Region,Photo from singer where SingerName='"
+ singername + "'";
Connection con = DbUtil.getConnection();
ResultSet rs = null;
Singer singer = null;
try {
rs = (ResultSet) con.createStatement().executeQuery(sql);
if (rs.next()) {
singer = new Singer();
singer.setSingerID(rs.getInt("SingerID"));
singer.setSingername(rs.getString("SingerName"));
singer.setSingertype(rs.getString("SingerType"));
singer.setRegion(rs.getString("Region"));
singer.setPhotoUrl(rs.getString("Photo"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtil.closeCon(con, rs, null);
}
return singer;
}
/**
*
* ͨ¹ýID²éÕÒ¸èÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-5 ÏÂÎç12:25:59
* @return
*/
public Singer querySingerByID(int id) {
String sql = "select SingerName,SingerType,Region,Photo from singer where SingerID="+id;
Connection con = DbUtil.getConnection();
Singer singer = null;
ResultSet rs = null;
try {
rs = (ResultSet) con.createStatement().executeQuery(sql);
if (rs.next()) {
singer = new Singer();
singer.setSingername(rs.getString("SingerName"));
singer.setSingertype(rs.getString("SingerType"));
singer.setRegion(rs.getString("Region"));
singer.setPhotoUrl(rs.getString("photo"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return singer;
}
/**
*
* ²éѯËùÓеĸèÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-4 ÏÂÎç7:47:33
* @return
*/
public List queryAllSinger() {
String sql = "select SingerID,SingerName,SingerType,Region,Photo from singer";
Connection con = DbUtil.getConnection();
Statement st = null;
ResultSet rs = null;
List list = new ArrayList();
Singer singer = null;
try {
st = (Statement) con.createStatement();
rs = (ResultSet) st.executeQuery(sql);
while (rs.next()) {
singer = new Singer();
singer.setSingerID(Integer.parseInt(rs.getString("SingerID")));
singer.setSingername(rs.getString("SingerName"));
singer.setSingertype(rs.getString("SingerType"));
singer.setRegion(rs.getString("Region"));
singer.setPhotoUrl(rs.getString("Photo"));
list.add(singer);
// System.out.println(singer+"%^^^%");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtil.closeCon(con, rs, st);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + "!!!!!!!!");
}
return list;
}
/**
*
* ɾ³ý¸èÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-4 ÏÂÎç7:48:49
* @return
*/
public int deleteSinger(String singername) throws Exception {
String sql = "delete from singer where SingerName=?";
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, singername);
return ps.executeUpdate();
}
/**
*
* ¸üиèÊÖÐÅÏ¢
*
* @author Hewie
* @version 1.0, 2015-7-4 ÏÂÎç7:59:44
* @return
* @throws Exception
*/
public int updateSinger(Singer singer) throws Exception {
String sql = "update singer set SingerName=?,SingerType=?,Region=?,Photo=? where SingerName=?";
Connection con = DbUtil.getConnection();
PreparedStatement ps = null;
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, singer.getSingername());
ps.setString(2, singer.getSingertype());
ps.setString(3, singer.getRegion());
ps.setString(4, singer.getPhotoUrl());
return ps.executeUpdate();
}
// public List querySingerBy
}
| gpl-2.0 |
prismsoul/gedgraph | sources/prismsoul.genealogy.gedgraph/gs-algo/org/graphstream/algorithm/measure/CommunityDistribution.java | 5672 | /*
* Copyright 2006 - 2013
* Stefan Balev <stefan.balev@graphstream-project.org>
* Julien Baudry <julien.baudry@graphstream-project.org>
* Antoine Dutot <antoine.dutot@graphstream-project.org>
* Yoann Pigné <yoann.pigne@graphstream-project.org>
* Guilhelm Savin <guilhelm.savin@graphstream-project.org>
*
* This file is part of GraphStream <http://graphstream-project.org>.
*
* GraphStream is a library whose purpose is to handle static or dynamic
* graph, create them from scratch, file or any source and display them.
*
* This program is free software distributed under the terms of two licenses, the
* CeCILL-C license that fits European law, and the GNU Lesser General Public
* License. You can use, modify and/ or redistribute the software under the terms
* of the CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
* URL <http://www.cecill.info> or under the terms of the GNU LGPL as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C and LGPL licenses and that you accept their terms.
*/
package org.graphstream.algorithm.measure;
/**
* Provides some statistical information on the size of current community
* assignment on the specified graph as it evolves.
*
* @author Guillaume-Jean Herbiet
*
*/
public class CommunityDistribution extends CommunityMeasure {
/**
* Biggest community currently generated.
*/
protected Object biggestCommunity = null;
/**
* Smallest community currently generated.
*/
protected Object smallestCommunity = null;
/**
* Average size of the currently generated communities.
*/
protected float avgSize = 0;
/**
* Standard deviation of the size of currently generated communities.
*/
protected float stdevSize = 0;
/**
* New size distribution measure using the specified marker as attribute
* name for the community assignment.
*
* @param marker
* Attribute name for the community assignment.
*/
public CommunityDistribution(String marker) {
super(marker);
}
@Override
/**
* Computes and update the statistical information on size distribution.
*
* @complexity O(C), where C is the expected number of communities.
*/
public void compute() {
if (graphChanged) {
// Default measure is the number of communities
M = (float) communities.size();
// Update the smallest/biggest community
// and creates the size distribution
int maxSize = 0;
int minSize = Integer.MAX_VALUE;
double[] distribution = new double[(int) M];
int k = 0;
Mean mean = new Mean();
StandardDeviation stdev = new StandardDeviation();
for (Object c : communities.keySet()) {
distribution[k++] = (communities.get(c)).size();
if ((communities.get(c)).size() > maxSize) {
biggestCommunity = c;
maxSize = (communities.get(c)).size();
}
if ((communities.get(c)).size() < minSize) {
smallestCommunity = c;
minSize = (communities.get(c)).size();
}
}
// Compute the statistical moments
avgSize = (float) mean.evaluate(distribution);
stdevSize = (float) stdev.evaluate(distribution);
graphChanged = false;
}
}
/**
* Get the number of communities
*
* @return an int representing the current number of communities
*/
public int number() {
return (int) M;
}
/**
* Get the biggest generated community
*
* @return the biggest community
*/
public Object biggestCommunity() {
return biggestCommunity;
}
/**
* Get the smallest generated community
*
* @return the smallest community
*/
public Object smallestCommunity() {
return smallestCommunity;
}
/**
* Get the maximum community size
*
* @return an int reflecting the size of the biggest community
*/
public int maxCommunitySize() {
if (communities.get(biggestCommunity) == null)
return 0;
else
return (communities.get(biggestCommunity)).size();
}
/**
* Get the minimum community size
*
* @return an int reflecting the size of the smallest community
*/
public int minCommunitySize() {
if (communities.get(smallestCommunity) == null)
return 0;
else
return (communities.get(smallestCommunity)).size();
}
/**
* Compute the average community size
*
* @return Average community size
*/
public float average() {
return avgSize;
}
/**
* Compute the standard deviation of the community size
*
* @return Standard deviation of the community size
*/
public float stdev() {
return stdevSize;
}
/**
* Updates the distribution information and returns a string for an easy
* display of the results.
*
* The string has the following format: [number of communities] [average
* size] [stdev size] [min size] ([smallest community]) [max size] ([biggest
* community])
*
* @return a String containing all computed distribution information.
*/
@Override
public String toString() {
compute();
return (int) M + " " + avgSize + " " + stdevSize + " "
+ minCommunitySize() + " (" + smallestCommunity + ") "
+ maxCommunitySize() + " (" + biggestCommunity + ")";
}
}
| gpl-2.0 |
isaacl/openjdk-jdk | src/windows/classes/sun/awt/windows/ThemeReader.java | 9838 | /*
* Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.windows;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/* !!!! WARNING !!!!
* This class has to be in sync with
* src/solaris/classes/sun/awt/windows/ThemeReader.java
* while we continue to build WinL&F on solaris
*/
/**
* Implements Theme Support for Windows XP.
*
* @author Sergey Salishev
* @author Bino George
* @author Igor Kushnirskiy
*/
public final class ThemeReader {
private static final Map<String, Long> widgetToTheme = new HashMap<>();
// lock for the cache
// reading should be done with readLock
// writing with writeLock
private static final ReadWriteLock readWriteLock =
new ReentrantReadWriteLock();
private static final Lock readLock = readWriteLock.readLock();
private static final Lock writeLock = readWriteLock.writeLock();
static void flush() {
writeLock.lock();
try {
// Close old themes.
for (Long value : widgetToTheme.values()) {
closeTheme(value.longValue());
}
widgetToTheme.clear();
} finally {
writeLock.unlock();
}
}
public static native boolean isThemed();
// this should be called only with writeLock held
private static Long getThemeImpl(String widget) {
Long theme = widgetToTheme.get(widget);
if (theme == null) {
int i = widget.indexOf("::");
if (i > 0) {
// We're using the syntax "subAppName::controlName" here, as used by msstyles.
// See documentation for SetWindowTheme on MSDN.
setWindowTheme(widget.substring(0, i));
theme = openTheme(widget.substring(i+2));
setWindowTheme(null);
} else {
theme = openTheme(widget);
}
widgetToTheme.put(widget, theme);
}
return theme;
}
// returns theme value
// this method should be invoked with readLock locked
private static Long getTheme(String widget) {
// mostly copied from the javadoc for ReentrantReadWriteLock
Long theme = widgetToTheme.get(widget);
if (theme == null) {
readLock.unlock();
writeLock.lock();
try {
theme = getThemeImpl(widget);
} finally {
readLock.lock();
writeLock.unlock();// Unlock write, still hold read
}
}
return theme;
}
private static native void paintBackground(int[] buffer, long theme,
int part, int state, int x,
int y, int w, int h, int stride);
public static void paintBackground(int[] buffer, String widget,
int part, int state, int x, int y, int w, int h, int stride) {
readLock.lock();
try {
paintBackground(buffer, getTheme(widget), part, state, x, y, w, h, stride);
} finally {
readLock.unlock();
}
}
private static native Insets getThemeMargins(long theme, int part,
int state, int marginType);
public static Insets getThemeMargins(String widget, int part, int state, int marginType) {
readLock.lock();
try {
return getThemeMargins(getTheme(widget), part, state, marginType);
} finally {
readLock.unlock();
}
}
private static native boolean isThemePartDefined(long theme, int part, int state);
public static boolean isThemePartDefined(String widget, int part, int state) {
readLock.lock();
try {
return isThemePartDefined(getTheme(widget), part, state);
} finally {
readLock.unlock();
}
}
private static native Color getColor(long theme, int part, int state,
int property);
public static Color getColor(String widget, int part, int state, int property) {
readLock.lock();
try {
return getColor(getTheme(widget), part, state, property);
} finally {
readLock.unlock();
}
}
private static native int getInt(long theme, int part, int state,
int property);
public static int getInt(String widget, int part, int state, int property) {
readLock.lock();
try {
return getInt(getTheme(widget), part, state, property);
} finally {
readLock.unlock();
}
}
private static native int getEnum(long theme, int part, int state,
int property);
public static int getEnum(String widget, int part, int state, int property) {
readLock.lock();
try {
return getEnum(getTheme(widget), part, state, property);
} finally {
readLock.unlock();
}
}
private static native boolean getBoolean(long theme, int part, int state,
int property);
public static boolean getBoolean(String widget, int part, int state,
int property) {
readLock.lock();
try {
return getBoolean(getTheme(widget), part, state, property);
} finally {
readLock.unlock();
}
}
private static native boolean getSysBoolean(long theme, int property);
public static boolean getSysBoolean(String widget, int property) {
readLock.lock();
try {
return getSysBoolean(getTheme(widget), property);
} finally {
readLock.unlock();
}
}
private static native Point getPoint(long theme, int part, int state,
int property);
public static Point getPoint(String widget, int part, int state, int property) {
readLock.lock();
try {
return getPoint(getTheme(widget), part, state, property);
} finally {
readLock.unlock();
}
}
private static native Dimension getPosition(long theme, int part, int state,
int property);
public static Dimension getPosition(String widget, int part, int state,
int property) {
readLock.lock();
try {
return getPosition(getTheme(widget), part,state,property);
} finally {
readLock.unlock();
}
}
private static native Dimension getPartSize(long theme, int part,
int state);
public static Dimension getPartSize(String widget, int part, int state) {
readLock.lock();
try {
return getPartSize(getTheme(widget), part, state);
} finally {
readLock.unlock();
}
}
private static native long openTheme(String widget);
private static native void closeTheme(long theme);
private static native void setWindowTheme(String subAppName);
private static native long getThemeTransitionDuration(long theme, int part,
int stateFrom, int stateTo, int propId);
public static long getThemeTransitionDuration(String widget, int part,
int stateFrom, int stateTo, int propId) {
readLock.lock();
try {
return getThemeTransitionDuration(getTheme(widget),
part, stateFrom, stateTo, propId);
} finally {
readLock.unlock();
}
}
public static native boolean isGetThemeTransitionDurationDefined();
private static native Insets getThemeBackgroundContentMargins(long theme,
int part, int state, int boundingWidth, int boundingHeight);
public static Insets getThemeBackgroundContentMargins(String widget,
int part, int state, int boundingWidth, int boundingHeight) {
readLock.lock();
try {
return getThemeBackgroundContentMargins(getTheme(widget),
part, state, boundingWidth, boundingHeight);
} finally {
readLock.unlock();
}
}
}
| gpl-2.0 |
iriber/miGestionModel | src/main/java/com/migestion/model/ConceptoMovimiento.java | 1454 | package com.migestion.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
/**
* Representa un concepto de movimiento.
*
* @author Bernardo Iribarne (ber.iribarne@gmail.com)
* @since 30/10/2013
*
*/
@Entity
@Table(name="concepto_movimiento")
public class ConceptoMovimiento extends GenericEntity{
/**
* nombre
*/
@Column
@NotNull(message="{conceptoMovimiento.nombre.required}")
private String nombre;
/**
* descripción
*/
@Column
private String descripcion;
/**
* identificador de la entity
*/
@Id @GeneratedValue
@Column
private Long oid;
/**
* @return the oid
*/
public Long getOid() {
return oid;
}
/**
* @param oid the oid to set
*/
public void setOid(Long oid) {
this.oid = oid;
}
public ConceptoMovimiento(){
}
public String toString(){
return getNombre();
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the descripcion
*/
public String getDescripcion() {
return descripcion;
}
/**
* @param descripcion the descripcion to set
*/
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
} | gpl-2.0 |
sealor/prototype-JPA-EclipseLink-H2 | src/test/java/io/github/sealor/prototype/jpa/eclipselink/h2/SimpleEntityTest.java | 1495 | package io.github.sealor.prototype.jpa.eclipselink.h2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import javax.persistence.RollbackException;
import org.junit.Test;
public class SimpleEntityTest extends AbstractTest {
@Test
public void testPersist() {
beginTransaction();
SimpleEntity simpleEntity1 = new SimpleEntity();
simpleEntity1.setText("stefan");
this.em.persist(simpleEntity1);
commitTransaction();
beginTransaction();
String jpql = "SELECT se FROM SimpleEntity se WHERE se.id = 1";
SimpleEntity simpleEntity2 = this.em.createQuery(jpql, SimpleEntity.class).getSingleResult();
assertEquals(simpleEntity1.getId(), simpleEntity2.getId());
assertEquals("stefan", simpleEntity2.getText());
commitTransaction();
}
@Test
public void testTextLength() {
beginTransaction();
SimpleEntity simpleEntity1 = new SimpleEntity();
simpleEntity1.setText("123456789");
this.em.persist(simpleEntity1);
commitTransaction();
try {
beginTransaction();
SimpleEntity simpleEntity2 = new SimpleEntity();
simpleEntity2.setText("1234567890");
this.em.persist(simpleEntity2);
commitTransaction();
fail();
} catch (RollbackException e) {
assertFalse(this.transaction.isActive());
assertTrue(e.getMessage().contains("Value too long for column"));
}
}
}
| gpl-2.0 |
Leopard2A5/XFTL | xftl-interfaces/src/main/java/de/xftl/spec/model/systems/MannableSystem.java | 117 | package de.xftl.spec.model.systems;
public interface MannableSystem extends ShipSystem {
// TODO implement me
}
| gpl-2.0 |